calepin 0.0.8

A Rust CLI for preprocessing Typst documents with executable code chunks
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
mod assets;
mod syntax;
mod theme;

use anyhow::{anyhow, Context, Result};
use minijinja::{AutoEscape, Environment};
use serde::Serialize;
use std::path::{Path, PathBuf};

use syntax::HtmlSyntaxTheme;

#[derive(Serialize)]
struct HtmlInMarkdownStyle {
    css: String,
}

const HTML_INPUT_LIGHT_THEME_PATH: &str = ".calepin/calepin-input-light.tmTheme";
const HTML_INPUT_LIGHT_THEME_REF: &str = "/.calepin/calepin-input-light.tmTheme";
const HTML_IN_MD_LAYOUT: &str = include_str!("../templates/html/html-in-md/layout.html");

#[derive(Debug, Clone)]
pub(crate) struct PreparedHtmlTheme {
    pub(crate) syntax_theme: HtmlSyntaxTheme,
    pub(crate) raw_theme_input: Option<String>,
}

pub(crate) fn prepare_html_theme(
    root: &Path,
    format: Option<&str>,
    html_theme: Option<&str>,
    html_theme_light: Option<&str>,
    html_theme_dark: Option<&str>,
) -> Result<PreparedHtmlTheme> {
    if format != Some("html") {
        return Ok(PreparedHtmlTheme {
            syntax_theme: HtmlSyntaxTheme::builtin(),
            raw_theme_input: None,
        });
    }

    match (html_theme_light, html_theme_dark) {
        (None, None) => Ok(PreparedHtmlTheme {
            syntax_theme: HtmlSyntaxTheme::builtin(),
            raw_theme_input: None,
        }),
        (Some(light), Some(dark)) => {
            if html_theme.is_none() {
                return Err(anyhow!(
                    "`html-theme-light` and `html-theme-dark` require `html-theme`"
                ));
            }
            let light_path = resolve_setup_theme_path(root, light);
            let dark_path = resolve_setup_theme_path(root, dark);
            let light_source = std::fs::read_to_string(&light_path)
                .with_context(|| format!("failed to read {}", light_path.display()))?;
            let dark_source = std::fs::read_to_string(&dark_path)
                .with_context(|| format!("failed to read {}", dark_path.display()))?;
            let syntax_theme = HtmlSyntaxTheme::from_tmtheme_sources(&light_source, &dark_source)?;

            let prepared_path = root.join(HTML_INPUT_LIGHT_THEME_PATH);
            if let Some(parent) = prepared_path.parent() {
                std::fs::create_dir_all(parent)
                    .with_context(|| format!("failed to create {}", parent.display()))?;
            }
            std::fs::write(&prepared_path, light_source)
                .with_context(|| format!("failed to write {}", prepared_path.display()))?;

            Ok(PreparedHtmlTheme {
                syntax_theme,
                raw_theme_input: Some(HTML_INPUT_LIGHT_THEME_REF.to_string()),
            })
        }
        _ => Err(anyhow!(
            "`html-theme-light` and `html-theme-dark` must be supplied together"
        )),
    }
}

pub(crate) fn apply_html_theme_file(
    path: &Path,
    html_theme: Option<&str>,
    themes_dir: &Path,
    syntax_theme: &HtmlSyntaxTheme,
) -> Result<()> {
    let html = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read {}", path.display()))?;
    let themed = theme::apply_html_theme(&html, html_theme, themes_dir, syntax_theme)?;
    if themed != html {
        std::fs::write(path, themed)
            .with_context(|| format!("failed to write {}", path.display()))?;
    }
    Ok(())
}

pub(crate) fn inline_html_images_file(path: &Path, root: &Path) -> Result<()> {
    let html = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read {}", path.display()))?;
    let base_dir = path.parent().unwrap_or(root);
    let inlined = assets::inline_html_images(&html, root, base_dir)?;
    if inlined != html {
        std::fs::write(path, inlined)
            .with_context(|| format!("failed to write {}", path.display()))?;
    }
    Ok(())
}

pub(crate) fn render_html_in_markdown(path: &Path) -> Result<()> {
    let rendered = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read {}", path.display()))?;
    let head = extract_tag_content(&rendered, "head")
        .context("generated Calepin HTML is missing <head>")?;
    let body = extract_tag_content(&rendered, "body")
        .context("generated Calepin HTML is missing <body>")?;
    let styles = extract_style_tags(&head)
        .into_iter()
        .map(|css| HtmlInMarkdownStyle {
            css: rewrite_artifact_urls(&css),
        })
        .collect();
    let body = rewrite_artifact_urls(body.trim());
    let context = HtmlInMarkdownTemplateContext { styles, body };
    let rendered = render_output_template(context)?;

    std::fs::write(path, rendered.trim_start())
        .with_context(|| format!("failed to write {}", path.display()))?;
    Ok(())
}

#[derive(Serialize)]
struct HtmlInMarkdownTemplateContext {
    styles: Vec<HtmlInMarkdownStyle>,
    body: String,
}

fn render_output_template(context: HtmlInMarkdownTemplateContext) -> Result<String> {
    let mut env = Environment::new();
    env.set_auto_escape_callback(|_| AutoEscape::None);
    env.add_template("html-in-md", HTML_IN_MD_LAYOUT)
        .with_context(|| anyhow!("failed to load html-in-md template"))?;
    let template = env
        .get_template("html-in-md")
        .map_err(|error| anyhow!("failed to load html-in-md layout: {error}"))?;
    template
        .render(&context)
        .map_err(|error| anyhow!("failed to render html-in-md template: {error}"))
}

fn extract_tag_content(document: &str, tag: &str) -> Result<String> {
    let open_tag = format!("<{}", tag);
    let close_tag = format!("</{}>", tag);
    let start = document
        .find(&open_tag)
        .ok_or_else(|| anyhow!("missing opening tag <{}>", tag))?;
    let open_end = start
        + document[start..]
            .find('>')
            .ok_or_else(|| anyhow!("malformed opening <{}>", tag))?
            + 1;
    let end = open_end
        .checked_add(document[open_end..].find(&close_tag).ok_or_else(|| {
            anyhow!("missing closing tag </{}>", tag)
        })?)
        .ok_or_else(|| anyhow!("invalid HTML for tag {}", tag))?;

    Ok(document[open_end..end].to_string())
}

fn extract_style_tags(head: &str) -> Vec<String> {
    const STYLE_START: &str = "<style";
    const STYLE_END: &str = "</style>";
    let mut head_cursor = head;
    let mut styles = Vec::new();

    while let Some(start_offset) = head_cursor.find(STYLE_START) {
        let style_start = start_offset;
        let style_open_end = match head_cursor[style_start..].find('>') {
            Some(offset) => style_start + offset + 1,
            None => break,
        };
        let style_close_offset = match head_cursor[style_open_end..].find(STYLE_END) {
            Some(offset) => style_open_end + offset + STYLE_END.len(),
            None => break,
        };

        let css = &head_cursor[style_open_end..(style_close_offset - STYLE_END.len())];
        styles.push(css.trim().to_string());
        head_cursor = &head_cursor[style_close_offset..];
    }

    styles
}

fn rewrite_artifact_urls(html: &str) -> String {
    html.replace(r#"src="/.calepin/"#, r#"src=".calepin/"#)
        .replace(r#"src='/.calepin/"#, r#"src='.calepin/"#)
        .replace(r#"href="/.calepin/"#, r#"href=".calepin/"#)
        .replace(r#"href='/.calepin/"#, r#"href='.calepin/"#)
}

fn resolve_setup_theme_path(root: &Path, value: &str) -> PathBuf {
    let path = Path::new(value);
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        root.join(path)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const SAMPLE_HTML: &str = "<html><head><title>Standard Title</title></head><body><h1>Standard Title</h1></body></html>";

    // Render with the builtin syntax theme against an empty themes dir, so a
    // bare name resolves to the embedded built-in theme.
    fn apply_html_theme(html: &str, html_theme: Option<&str>) -> Result<String> {
        let dir = tempfile::tempdir().unwrap();
        theme::apply_html_theme(html, html_theme, dir.path(), &HtmlSyntaxTheme::builtin())
    }

    fn write_theme(themes_dir: &Path, name: &str, layout: &str) {
        let dir = themes_dir.join(name);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("layout.html"), layout).unwrap();
    }

    #[test]
    fn pico_html_theme_preserves_title_and_wraps_body() {
        let themed = apply_html_theme(SAMPLE_HTML, Some("pico")).unwrap();

        assert!(themed.contains("<title>Standard Title</title>"));
        assert!(themed.contains("https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css"));
        assert!(themed.contains("<main class=\"container\">"));
        assert!(themed.contains(".sourceCode,"));
        assert!(themed.contains(".cell-output {"));
        assert!(themed.contains("calepin-copy-code"));
        assert!(themed.contains(r#"<nav class="calepin-theme-switcher""#));
        assert!(themed.contains("const themeOrder = [\"\", \"light\", \"dark\"]"));
        assert!(themed.contains("<h1>Standard Title</h1>"));
    }

    #[test]
    fn basic_html_theme_wraps_body_without_pico_artifacts() {
        let themed = apply_html_theme(SAMPLE_HTML, Some("basic")).unwrap();

        assert!(themed.contains("Standard Title"));
        assert!(themed.contains("sourceCode"));
        assert!(!themed.contains("cdn.jsdelivr.net/npm/@picocss/pico"));
        assert!(themed.contains("calepin-syntax-foreground"));
    }

    #[test]
    fn no_html_theme_returns_raw_typst_html_without_calepin_css_or_template() {
        let themed = apply_html_theme(SAMPLE_HTML, None).unwrap();

        assert_eq!(themed, SAMPLE_HTML);
        assert!(!themed.contains("calepin-copy-code"));
        assert!(!themed.contains("cdn.jsdelivr.net/npm/@picocss/pico"));
        assert!(!themed.contains("calepin-theme-switcher"));
    }

    #[test]
    fn html_image_inliner_embeds_root_relative_images() {
        let dir = tempfile::tempdir().unwrap();
        let image = dir.path().join(".calepin/paper/figures/fig.svg");
        std::fs::create_dir_all(image.parent().unwrap()).unwrap();
        std::fs::write(&image, "<svg></svg>").unwrap();
        let html = r#"<figure><img src="/.calepin/paper/figures/fig.svg" alt=""></figure>"#;

        let inlined = assets::inline_html_images(html, dir.path(), dir.path()).unwrap();

        assert!(inlined.contains(r#"src="data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=""#));
    }

    #[test]
    fn html_image_inliner_embeds_relative_images() {
        let dir = tempfile::tempdir().unwrap();
        let image = dir.path().join("fig.png");
        std::fs::write(&image, [0_u8, 1, 2]).unwrap();
        let html = r#"<img alt="x" src='fig.png'>"#;

        let inlined = assets::inline_html_images(html, dir.path(), dir.path()).unwrap();

        assert!(inlined.contains("src='data:image/png;base64,AAEC'"));
    }

    #[test]
    fn html_image_inliner_leaves_external_and_data_images() {
        let dir = tempfile::tempdir().unwrap();
        let html = concat!(
            r#"<img src="https://example.com/fig.png">"#,
            r#"<img src="data:image/png;base64,AA==">"#
        );

        let inlined = assets::inline_html_images(html, dir.path(), dir.path()).unwrap();

        assert_eq!(inlined, html);
    }

    #[test]
    #[test]
    fn html_custom_syntax_themes_require_html_theme() {
        let dir = tempfile::tempdir().unwrap();

        let err = prepare_html_theme(
            dir.path(),
            Some("html"),
            None,
            Some("light.tmTheme"),
            Some("dark.tmTheme"),
        )
        .unwrap_err()
        .to_string();

        assert!(err.contains("require `html-theme`"));
    }

    #[test]
    fn unknown_html_theme_errors() {
        let err = apply_html_theme(SAMPLE_HTML, Some("nope"))
            .unwrap_err()
            .to_string();

        assert!(err.contains("unknown HTML theme `nope`"));
    }

    #[test]
    fn user_theme_directory_shadows_builtin() {
        let dir = tempfile::tempdir().unwrap();
        write_theme(
            dir.path(),
            "pico",
            "<custom-shell>{{ doc.body }}</custom-shell>",
        );

        let themed = theme::apply_html_theme(
            SAMPLE_HTML,
            Some("pico"),
            dir.path(),
            &HtmlSyntaxTheme::builtin(),
        )
        .unwrap();

        assert!(themed.contains("<custom-shell>"));
        assert!(themed.contains("<h1>Standard Title</h1>"));
        // The built-in pico theme is not used when a user theme shadows it.
        assert!(!themed.contains("cdn.jsdelivr.net/npm/@picocss/pico"));
    }

    #[test]
    fn user_theme_loops_styles_scripts_and_includes_partials() {
        let dir = tempfile::tempdir().unwrap();
        let theme_dir = dir.path().join("mini");
        std::fs::create_dir_all(theme_dir.join("partials")).unwrap();
        std::fs::create_dir_all(theme_dir.join("styles")).unwrap();
        std::fs::create_dir_all(theme_dir.join("scripts")).unwrap();
        std::fs::write(
            theme_dir.join("layout.html"),
            "{{ doc.head }}{% for s in styles %}<style>{{ s.css }}</style>{% endfor %}{{ doc.body_open }}{% include \"partials/banner.html\" %}{{ doc.body }}{% for s in scripts %}<script>{{ s.content }}</script>{% endfor %}{{ doc.body_close }}",
        )
        .unwrap();
        std::fs::write(
            theme_dir.join("partials/banner.html"),
            "<header>hi</header>",
        )
        .unwrap();
        std::fs::write(theme_dir.join("styles/main.css"), "body{color:red}").unwrap();
        std::fs::write(theme_dir.join("scripts/main.js"), "console.log(1)").unwrap();

        let themed = theme::apply_html_theme(
            SAMPLE_HTML,
            Some("mini"),
            dir.path(),
            &HtmlSyntaxTheme::builtin(),
        )
        .unwrap();

        assert!(themed.contains("<header>hi</header>"));
        assert!(themed.contains("<style>body{color:red}</style>"));
        assert!(themed.contains("<script>console.log(1)</script>"));
    }

    #[test]
    fn theme_directory_missing_layout_errors() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join("bare")).unwrap();

        let err = theme::apply_html_theme(
            SAMPLE_HTML,
            Some("bare"),
            dir.path(),
            &HtmlSyntaxTheme::builtin(),
        )
        .unwrap_err()
        .to_string();

        assert!(err.contains("bare"));
        assert!(err.contains("layout.html"));
    }

    #[test]
    fn theme_template_error_names_the_theme() {
        let dir = tempfile::tempdir().unwrap();
        write_theme(
            dir.path(),
            "broken",
            "{% include \"partials/missing.html\" %}",
        );

        let err = theme::apply_html_theme(
            SAMPLE_HTML,
            Some("broken"),
            dir.path(),
            &HtmlSyntaxTheme::builtin(),
        )
        .unwrap_err()
        .to_string();

        assert!(err.contains("broken"));
    }

    #[test]
    fn title_is_not_double_escaped() {
        let dir = tempfile::tempdir().unwrap();
        write_theme(
            dir.path(),
            "title-only",
            "<h1>{{ doc.title }}</h1>{{ doc.body_open }}{{ doc.body }}{{ doc.body_close }}",
        );
        let html = "<html><head><title>Foo &amp; Bar</title></head><body><p>x</p></body></html>";

        let themed = theme::apply_html_theme(
            html,
            Some("title-only"),
            dir.path(),
            &HtmlSyntaxTheme::builtin(),
        )
        .unwrap();

        assert!(themed.contains("<h1>Foo &amp; Bar</h1>"));
        assert!(!themed.contains("&amp;amp;"));
    }
}