Skip to main content

ultrafast_render/
code.rs

1//! `code`: source code set in a panel, syntax-highlighted, optionally typed
2//! on with a caret, with line numbers, highlighted lines and window chrome.
3//! It expands into a component of ordinary nodes: the code is one `text`
4//! node whose colors are inline spans, so it stays editable and sharp.
5
6use crate::geom::{self, Fonts};
7use crate::markup::escape;
8use serde_json::{Value, json};
9use std::collections::BTreeMap;
10use std::path::Path;
11use ultrafast_graph::{Component, Document, Format, Node, Param};
12
13pub fn used_by(doc: &Document) -> bool {
14    doc.nodes.values().any(|n| n.op == "code")
15}
16
17/// Params a code instance keeps (the rest are consumed at expansion).
18pub const PARAMS: &[&str] = &["opacity"];
19
20pub const LANGUAGES: &[&str] = &[
21    "rust", "python", "js", "ts", "json", "bash", "go", "swift", "c", "cpp", "slang", "sql", "css", "html", "text",
22];
23
24#[derive(Clone, Copy, PartialEq, Debug)]
25enum Tok {
26    Plain,
27    Keyword,
28    Type,
29    Func,
30    Str,
31    Num,
32    Comment,
33    Punct,
34}
35
36struct Theme {
37    background: &'static str,
38    border: &'static str,
39    chrome: &'static str,
40    highlight: &'static str,
41    gutter: &'static str,
42    caret: &'static str,
43    colors: [&'static str; 8],
44}
45
46/// Plain, keyword, type, function, string, number, comment, punctuation.
47fn theme(name: &str) -> Option<Theme> {
48    Some(match name {
49        "ultrafast" => Theme {
50            background: "#121117",
51            border: "#ffffff14",
52            chrome: "#1a1920",
53            highlight: "#211f2a",
54            gutter: "#8a849c",
55            caret: "#ff5c7a",
56            colors: [
57                "#e8e3d8", "#ff7aa2", "#c49cff", "#7cc5ff", "#a8e07a", "#ffb86c", "#6e6880", "#9a94a6",
58            ],
59        },
60        "paper" => Theme {
61            background: "#f7f3ea",
62            border: "#16141a1f",
63            chrome: "#efe9dd",
64            highlight: "#f0e2d4",
65            gutter: "#8a8274",
66            caret: "#e2412b",
67            colors: [
68                "#1c1a22", "#c8153f", "#7a3fc4", "#1f5fbf", "#2f7d32", "#b35c00", "#8a8478", "#6b6577",
69            ],
70        },
71        "mono" => Theme {
72            background: "#0b0b0d",
73            border: "#ffffff1a",
74            chrome: "#141417",
75            highlight: "#18181d",
76            gutter: "#77777f",
77            caret: "#f2f2f2",
78            colors: [
79                "#d8d8dc", "#ffffff", "#ffffff", "#f2f2f2", "#a0a0a8", "#c8c8d0", "#66666e", "#8a8a92",
80            ],
81        },
82        _ => return None,
83    })
84}
85
86fn keywords(lang: &str) -> &'static [&'static str] {
87    match lang {
88        "rust" => &[
89            "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", "false",
90            "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return",
91            "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where", "while",
92        ],
93        "python" => &[
94            "and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif", "else",
95            "except", "False", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "None",
96            "nonlocal", "not", "or", "pass", "raise", "return", "True", "try", "while", "with", "yield", "self",
97        ],
98        "js" | "ts" => &[
99            "async",
100            "await",
101            "break",
102            "case",
103            "catch",
104            "class",
105            "const",
106            "continue",
107            "default",
108            "delete",
109            "do",
110            "else",
111            "export",
112            "extends",
113            "false",
114            "finally",
115            "for",
116            "from",
117            "function",
118            "if",
119            "import",
120            "in",
121            "instanceof",
122            "interface",
123            "let",
124            "new",
125            "null",
126            "of",
127            "return",
128            "static",
129            "super",
130            "switch",
131            "this",
132            "throw",
133            "true",
134            "try",
135            "type",
136            "typeof",
137            "undefined",
138            "var",
139            "void",
140            "while",
141            "yield",
142            "as",
143            "implements",
144            "enum",
145            "readonly",
146        ],
147        "go" => &[
148            "break",
149            "case",
150            "chan",
151            "const",
152            "continue",
153            "default",
154            "defer",
155            "else",
156            "fallthrough",
157            "for",
158            "func",
159            "go",
160            "goto",
161            "if",
162            "import",
163            "interface",
164            "map",
165            "package",
166            "range",
167            "return",
168            "select",
169            "struct",
170            "switch",
171            "type",
172            "var",
173            "nil",
174            "true",
175            "false",
176        ],
177        "swift" => &[
178            "actor",
179            "async",
180            "await",
181            "break",
182            "case",
183            "class",
184            "continue",
185            "default",
186            "defer",
187            "do",
188            "else",
189            "enum",
190            "extension",
191            "false",
192            "for",
193            "func",
194            "guard",
195            "if",
196            "import",
197            "in",
198            "init",
199            "let",
200            "nil",
201            "private",
202            "protocol",
203            "public",
204            "return",
205            "self",
206            "static",
207            "struct",
208            "switch",
209            "throw",
210            "throws",
211            "true",
212            "try",
213            "var",
214            "where",
215            "while",
216        ],
217        "c" | "cpp" | "slang" => &[
218            "auto",
219            "bool",
220            "break",
221            "case",
222            "char",
223            "class",
224            "const",
225            "constexpr",
226            "continue",
227            "default",
228            "do",
229            "double",
230            "else",
231            "enum",
232            "extern",
233            "false",
234            "float",
235            "float2",
236            "float3",
237            "float4",
238            "for",
239            "if",
240            "inline",
241            "int",
242            "long",
243            "namespace",
244            "nullptr",
245            "return",
246            "short",
247            "sizeof",
248            "static",
249            "struct",
250            "switch",
251            "template",
252            "this",
253            "true",
254            "typedef",
255            "uint",
256            "unsigned",
257            "using",
258            "void",
259            "while",
260            "in",
261            "out",
262            "inout",
263            "uniform",
264        ],
265        "sql" => &[
266            "select", "from", "where", "and", "or", "not", "insert", "into", "values", "update", "set", "delete",
267            "create", "table", "join", "left", "right", "inner", "on", "group", "by", "order", "limit", "as", "having",
268            "null", "distinct", "count", "SELECT", "FROM", "WHERE", "AND", "OR", "NOT", "INSERT", "INTO", "VALUES",
269            "UPDATE", "SET", "DELETE", "CREATE", "TABLE", "JOIN", "LEFT", "ON", "GROUP", "BY", "ORDER", "LIMIT", "AS",
270            "HAVING", "NULL", "DISTINCT", "COUNT",
271        ],
272        "bash" => &[
273            "if", "then", "else", "elif", "fi", "for", "while", "do", "done", "case", "esac", "function", "in",
274            "export", "local", "return", "echo", "cd", "sudo",
275        ],
276        "json" => &["true", "false", "null"],
277        _ => &[],
278    }
279}
280
281fn line_comment(lang: &str) -> Option<&'static str> {
282    match lang {
283        "python" | "bash" => Some("#"),
284        "sql" => Some("--"),
285        "json" | "text" | "html" | "css" => None,
286        _ => Some("//"),
287    }
288}
289
290/// Tokens of `src`, as (kind, text) pieces covering it exactly.
291fn tokenize(src: &str, lang: &str) -> Vec<(Tok, String)> {
292    let kw = keywords(lang);
293    let lc = line_comment(lang);
294    let block = !matches!(lang, "python" | "bash" | "json" | "text");
295    let c: Vec<char> = src.chars().collect();
296    let mut out: Vec<(Tok, String)> = Vec::new();
297    let push = |t: Tok, s: String, out: &mut Vec<(Tok, String)>| match out.last_mut() {
298        Some(last) if last.0 == t => last.1.push_str(&s),
299        _ => out.push((t, s)),
300    };
301    let starts = |i: usize, p: &str| p.chars().enumerate().all(|(k, pc)| c.get(i + k) == Some(&pc));
302    let mut i = 0;
303    while i < c.len() {
304        let ch = c[i];
305        if lang == "text" {
306            push(Tok::Plain, ch.to_string(), &mut out);
307            i += 1;
308            continue;
309        }
310        // Comments.
311        if let Some(p) = lc
312            && starts(i, p)
313        {
314            let j = (i..c.len()).find(|&j| c[j] == '\n').unwrap_or(c.len());
315            push(Tok::Comment, c[i..j].iter().collect(), &mut out);
316            i = j;
317            continue;
318        }
319        if block && starts(i, "/*") {
320            let j = (i + 2..c.len().saturating_sub(1))
321                .find(|&j| c[j] == '*' && c[j + 1] == '/')
322                .map(|j| j + 2)
323                .unwrap_or(c.len());
324            push(Tok::Comment, c[i..j].iter().collect(), &mut out);
325            i = j;
326            continue;
327        }
328        if lang == "html" && starts(i, "<!--") {
329            let j = (i + 4..c.len())
330                .find(|&j| starts(j, "-->"))
331                .map(|j| j + 3)
332                .unwrap_or(c.len());
333            push(Tok::Comment, c[i..j].iter().collect(), &mut out);
334            i = j;
335            continue;
336        }
337        // Strings.
338        if ch == '"' || ch == '\'' || (ch == '`' && matches!(lang, "js" | "ts" | "go")) {
339            // A Rust lifetime ('a) is not a string.
340            let lifetime = lang == "rust"
341                && ch == '\''
342                && c.get(i + 1).is_some_and(|n| n.is_alphabetic())
343                && c.get(i + 2) != Some(&'\'');
344            if !lifetime {
345                let mut j = i + 1;
346                while j < c.len() && c[j] != ch && !(c[j] == '\n' && ch != '`') {
347                    if c[j] == '\\' {
348                        j += 1;
349                    }
350                    j += 1;
351                }
352                let j = (j + 1).min(c.len());
353                // JSON keys read as names, not values.
354                let key = lang == "json" && (j..c.len()).find(|&k| c[k] != ' ').map(|k| c[k]) == Some(':');
355                push(
356                    if key { Tok::Func } else { Tok::Str },
357                    c[i..j].iter().collect(),
358                    &mut out,
359                );
360                i = j;
361                continue;
362            }
363        }
364        // Numbers.
365        if ch.is_ascii_digit() && (i == 0 || !(c[i - 1].is_alphanumeric() || c[i - 1] == '_')) {
366            let j = (i..c.len())
367                .find(|&j| !(c[j].is_ascii_alphanumeric() || c[j] == '.' || c[j] == '_'))
368                .unwrap_or(c.len());
369            push(Tok::Num, c[i..j].iter().collect(), &mut out);
370            i = j;
371            continue;
372        }
373        // Words.
374        if ch.is_alphabetic() || ch == '_' || (ch == '$' && lang == "bash") || (ch == '@' && lang != "text") {
375            let j = (i + 1..c.len())
376                .find(|&j| !(c[j].is_alphanumeric() || c[j] == '_' || (lang == "css" && c[j] == '-')))
377                .unwrap_or(c.len());
378            let w: String = c[i..j].iter().collect();
379            let next = (j..c.len()).find(|&k| c[k] != ' ').map(|k| c[k]);
380            let t = if kw.contains(&w.as_str()) || (lang == "rust" && next == Some('!')) {
381                Tok::Keyword
382            } else if next == Some('(') {
383                Tok::Func
384            } else if w.chars().next().is_some_and(|f| f.is_uppercase()) || ch == '@' {
385                Tok::Type
386            } else {
387                Tok::Plain
388            };
389            push(t, w, &mut out);
390            i = j;
391            continue;
392        }
393        let t = if ch.is_whitespace() { Tok::Plain } else { Tok::Punct };
394        push(t, ch.to_string(), &mut out);
395        i += 1;
396    }
397    out
398}
399
400fn text<'a>(node: &'a Node, k: &str) -> Option<&'a str> {
401    match node.params.get(k) {
402        Some(Param::Text(s)) => Some(s),
403        _ => None,
404    }
405}
406
407fn num(node: &Node, k: &str, d: f64) -> f64 {
408    node.params
409        .get(k)
410        .and_then(|p| p.eval(0.0))
411        .and_then(|v| v.first().copied())
412        .unwrap_or(d)
413}
414
415fn flag(node: &Node, k: &str, d: bool) -> bool {
416    match node.params.get(k) {
417        Some(Param::Bool(b)) => *b,
418        _ => d,
419    }
420}
421
422/// "3", "3-5", "2,4-6" as 1-based line numbers.
423fn line_set(s: &str) -> Vec<usize> {
424    let mut out = Vec::new();
425    for part in s.split(',') {
426        let part = part.trim();
427        let (a, b) = part.split_once('-').unwrap_or((part, part));
428        if let (Ok(a), Ok(b)) = (a.trim().parse::<usize>(), b.trim().parse::<usize>()) {
429            out.extend(a.min(b)..=a.max(b));
430        }
431    }
432    out
433}
434
435/// The markup of `src` colored by `kinds`, one span per token (spans do not
436/// cross lines).
437fn markup(tokens: &[(Tok, String)], th: &Theme) -> String {
438    let mut out = String::new();
439    for (t, s) in tokens {
440        for (k, piece) in s.split('\n').enumerate() {
441            if k > 0 {
442                out.push('\n');
443            }
444            if piece.is_empty() {
445                continue;
446            }
447            if *t == Tok::Plain || piece.trim().is_empty() {
448                out.push_str(&escape(piece));
449                continue;
450            }
451            let color = th.colors[*t as usize];
452            let style = if *t == Tok::Comment { " style=italic" } else { "" };
453            out.push_str(&format!("[{}]{{color={color}{style}}}", escape(piece)));
454        }
455    }
456    out
457}
458
459pub fn build(node: &Node, fmt: &Format, fonts: &mut Fonts, base: &Path) -> Result<Component, String> {
460    let src = text(node, "code").unwrap_or("").replace('\t', "    ");
461    let src = src.trim_end_matches('\n').to_string();
462    let lang = text(node, "language").unwrap_or("text");
463    if !LANGUAGES.contains(&lang) {
464        return Err(format!("unknown language `{lang}` ({})", LANGUAGES.join(", ")));
465    }
466    let th_name = text(node, "theme").unwrap_or("ultrafast");
467    let th = theme(th_name).ok_or_else(|| format!("unknown theme `{th_name}` (ultrafast, paper, mono)"))?;
468    let s = fmt.width.min(fmt.height) as f64 / 1080.0;
469    let size = num(node, "size", 30.0 * s);
470    let lh = num(node, "line_height", 1.55) * size;
471    let font = text(node, "font").unwrap_or("ultrafast:mono").to_string();
472    let pad = num(node, "padding", size * 1.4);
473    let window = flag(node, "window", true);
474    let numbers = flag(node, "line_numbers", true);
475    let lines: Vec<&str> = src.split('\n').collect();
476    let n_lines = lines.len().max(1);
477
478    // Monospace metrics: one advance for every character.
479    let probe: Node = serde_json::from_value(json!({"op": "text", "params": {
480        "text": "MMMMMMMMMM", "font": font, "size": size, "features": "liga=0,calt=0"}}))
481    .map_err(|e| e.to_string())?;
482    let m = geom::measure("code", &probe, 0.0, fonts, base).map_err(|e| e.to_string())?;
483    let adv = m.advance / 10.0;
484    let (ascent, descent) = (m.ascent, m.descent);
485    let cols = lines.iter().map(|l| l.chars().count()).max().unwrap_or(0);
486    let gutter = if numbers {
487        (n_lines.to_string().len() as f64 + 2.0) * adv
488    } else {
489        0.0
490    };
491    let bar = if window { size * 1.9 } else { 0.0 };
492    let width = num(node, "width", gutter + cols as f64 * adv + 2.0 * pad);
493    let height = bar + 2.0 * pad + lh * (n_lines as f64 - 1.0) + ascent + descent;
494    let pos = node.params.get("position").and_then(|p| p.eval(0.0));
495    let (x, y) = match pos {
496        Some(p) if p.len() >= 2 => (p[0], p[1]),
497        _ => ((fmt.width as f64 - width) / 2.0, (fmt.height as f64 - height) / 2.0),
498    };
499
500    let mut nodes: BTreeMap<String, Node> = BTreeMap::new();
501    let mut layers: Vec<String> = Vec::new();
502    let mut add = |id: &str, op: &str, params: Value, inputs: &[(&str, &str)], layer: bool| -> Result<(), String> {
503        nodes.insert(
504            id.to_string(),
505            Node {
506                op: op.into(),
507                params: serde_json::from_value(params).map_err(|e| e.to_string())?,
508                inputs: inputs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(),
509                ..Default::default()
510            },
511        );
512        if layer {
513            layers.push(id.to_string());
514        }
515        Ok(())
516    };
517
518    let radius = num(node, "radius", size * 0.55);
519    if flag(node, "background", true) {
520        add(
521            "shadow_shape",
522            "shape",
523            json!({"kind": "rect", "center": [x + width / 2.0, y + height / 2.0 + size * 0.8],
524                   "size": [width, height], "radius": radius, "color": "#00000099"}),
525            &[],
526            false,
527        )?;
528        add(
529            "shadow",
530            "blur",
531            json!({"radius": size * 1.6}),
532            &[("source", "shadow_shape")],
533            true,
534        )?;
535        add(
536            "panel",
537            "shape",
538            json!({"kind": "rect", "center": [x + width / 2.0, y + height / 2.0], "size": [width, height],
539                   "radius": radius, "color": th.background}),
540            &[],
541            true,
542        )?;
543        add(
544            "border",
545            "shape",
546            json!({"kind": "rect", "center": [x + width / 2.0, y + height / 2.0], "size": [width - 1.0, height - 1.0],
547                   "radius": radius, "stroke": 1.5 * s, "color": th.border}),
548            &[],
549            true,
550        )?;
551    }
552    if window {
553        // The title bar: rounded on top, square where it meets the code.
554        let cy = y + bar / 2.0 + size * 0.15;
555        let bh = bar + size * 0.3;
556        add(
557            "bar_top",
558            "shape",
559            json!({"kind": "rect", "center": [x + width / 2.0, y + bh / 2.0], "size": [width - 2.0, bh - 1.0],
560                   "radius": radius, "color": th.chrome}),
561            &[],
562            true,
563        )?;
564        add(
565            "bar_bottom",
566            "shape",
567            json!({"kind": "rect", "center": [x + width / 2.0, y + bh * 0.75], "size": [width - 2.0, bh * 0.5],
568                   "color": th.chrome}),
569            &[],
570            true,
571        )?;
572        add(
573            "bar_rule",
574            "shape",
575            json!({"kind": "rect", "center": [x + width / 2.0, y + bh], "size": [width - 2.0, 1.5 * s], "color": th.border}),
576            &[],
577            true,
578        )?;
579        for (k, c) in ["#ff5f57", "#febc2e", "#28c840"].iter().enumerate() {
580            add(
581                &format!("dot{k}"),
582                "shape",
583                json!({"kind": "circle", "center": [x + pad * 0.75 + k as f64 * size * 0.85, cy],
584                       "size": [size * 0.5, size * 0.5], "color": c}),
585                &[],
586                true,
587            )?;
588        }
589        if let Some(title) = text(node, "title") {
590            add(
591                "title",
592                "text",
593                json!({"text": escape(title), "font": font, "size": (size * 0.9).max(24.0 * s), "color": th.gutter,
594                       "align": "center", "valign": "middle", "position": [x + width / 2.0, cy]}),
595                &[],
596                true,
597            )?;
598        }
599    }
600    let x0 = x + pad + gutter;
601    let top = y + bar + pad;
602    // Highlighted lines: a band across the panel behind them.
603    if let Some(hl) = text(node, "highlight") {
604        let at = num(node, "highlight_at", 0.0);
605        for (k, line) in line_set(hl).into_iter().filter(|&l| l >= 1 && l <= n_lines).enumerate() {
606            let cy = top + ascent + (line as f64 - 1.0) * lh - size * 0.3;
607            let id = format!("highlight{k}");
608            add(
609                &id,
610                "shape",
611                json!({"kind": "rect", "center": [x + width / 2.0, cy], "size": [width - 2.0, lh], "color": th.highlight}),
612                &[],
613                false,
614            )?;
615            add(
616                &format!("{id}_in"),
617                "opacity",
618                json!({"opacity": {"keys": [{"t": at, "v": [0.0], "ease": "out_cubic"}, {"t": at + 0.4, "v": [1.0]}]}}),
619                &[("source", &id)],
620                true,
621            )?;
622        }
623    }
624    if numbers {
625        let nums: Vec<String> = (1..=n_lines).map(|i| i.to_string()).collect();
626        add(
627            "line_numbers",
628            "text",
629            json!({"text": nums.join("\n"), "font": font, "size": size, "line_height": lh / size,
630                   "color": th.gutter, "align": "right", "position": [x0 - adv * 1.5, top],
631                   "features": "liga=0,calt=0", "skim": true}),
632            &[],
633            true,
634        )?;
635    }
636    let tokens = tokenize(&src, lang);
637    let mut p = json!({"text": markup(&tokens, &th), "font": font, "size": size, "line_height": lh / size,
638                       "color": th.colors[0], "position": [x0, top], "features": "liga=0,calt=0", "skim": true});
639    // Typing: characters appear at `type_speed` per second from `at`.
640    let speed = num(node, "type_speed", 0.0);
641    let at = num(node, "at", 0.0);
642    let glyphs: Vec<(usize, usize)> = lines
643        .iter()
644        .enumerate()
645        .flat_map(|(row, l)| (0..l.chars().count()).map(move |col| (row, col)))
646        .collect();
647    let total = glyphs.len();
648    if speed > 0.0 {
649        let end = at + total as f64 / speed;
650        p["reveal"] = json!({"keys": [{"t": at, "v": [0.0]}, {"t": end, "v": [total as f64]}]});
651        p["reveal_softness"] = json!(0.6);
652    }
653    // Lines longer than a given `width` are clipped at the panel's edge.
654    add("code_text", "text", p, &[], false)?;
655    add(
656        "code",
657        "crop",
658        json!({"rect": [x, y + bar, width, height - bar], "softness": 0.0}),
659        &[("source", "code_text")],
660        true,
661    )?;
662    if speed > 0.0 && flag(node, "caret", true) {
663        // The caret after the last typed character, then blinking.
664        let end = at + total as f64 / speed;
665        let place = |row: usize, col: usize| {
666            json!([
667                x0 + col as f64 * adv + adv * 0.1,
668                top + ascent + row as f64 * lh - size * 0.3
669            ])
670        };
671        // The caret runs along each line as it is typed (one linear key per
672        // line, not one per character), then jumps to the next.
673        let mut keys: Vec<Value> = Vec::new();
674        let mut k = 0usize;
675        for (row, l) in lines.iter().enumerate() {
676            let n = l.chars().count();
677            if n == 0 && row > 0 {
678                continue;
679            }
680            let t0 = at + k as f64 / speed;
681            keys.push(json!({"t": t0, "v": place(row, 0), "ease": "linear"}));
682            if n > 0 {
683                keys.push(json!({"t": at + (k + n) as f64 / speed - 1e-3, "v": place(row, n), "ease": "hold"}));
684            }
685            k += n;
686        }
687        let blink = format!("1 - (t > {end:.4}) * (fract((t - {end:.4}) * 1.1) > 0.55)");
688        add(
689            "caret_shape",
690            "shape",
691            json!({"kind": "rect", "size": [adv * 0.14 + 2.0 * s, size * 1.15], "color": th.caret,
692                   "center": {"keys": keys}}),
693            &[],
694            false,
695        )?;
696        add(
697            "caret",
698            "opacity",
699            json!({"opacity": {"expr": blink}}),
700            &[("source", "caret_shape")],
701            true,
702        )?;
703    }
704
705    // Composite in order, then the instance's opacity.
706    let mut acc: Option<String> = None;
707    for (k, l) in layers.iter().enumerate() {
708        acc = Some(match acc {
709            None => l.clone(),
710            Some(prev) => {
711                let id = format!("over{k}");
712                nodes.insert(
713                    id.clone(),
714                    Node {
715                        op: "over".into(),
716                        inputs: [("fg".to_string(), l.clone()), ("bg".to_string(), prev)].into(),
717                        ..Default::default()
718                    },
719                );
720                id
721            }
722        });
723    }
724    let art = acc.ok_or("empty code block")?;
725    nodes.insert(
726        "code_out".into(),
727        Node {
728            op: "opacity".into(),
729            params: [("opacity".to_string(), Param::Text("$opacity".into()))].into(),
730            inputs: [("source".to_string(), art)].into(),
731            ..Default::default()
732        },
733    );
734    Ok(Component {
735        nodes,
736        output: "code_out".into(),
737        params: [("opacity".to_string(), Param::Number(1.0))].into(),
738        inputs: Vec::new(),
739    })
740}
741
742#[cfg(test)]
743mod tests {
744    use super::*;
745
746    #[test]
747    fn tokenizes_rust() {
748        let t = tokenize("fn main() { let x = \"hi\"; // done\n}", "rust");
749        let kinds: Vec<(Tok, &str)> = t.iter().map(|(k, s)| (*k, s.as_str())).collect();
750        assert!(kinds.contains(&(Tok::Keyword, "fn")));
751        assert!(kinds.contains(&(Tok::Func, "main")));
752        assert!(kinds.contains(&(Tok::Str, "\"hi\"")));
753        assert!(kinds.contains(&(Tok::Comment, "// done")));
754        // Tokens cover the source exactly.
755        assert_eq!(
756            t.iter().map(|(_, s)| s.as_str()).collect::<String>(),
757            "fn main() { let x = \"hi\"; // done\n}"
758        );
759    }
760
761    #[test]
762    fn markup_round_trips_to_the_source() {
763        let src = "let a = v[0] * b; /* [x] */\nprint(\"\\\\\")";
764        let th = theme("ultrafast").unwrap();
765        let (plain, spans) = crate::markup::parse(&markup(&tokenize(src, "rust"), &th));
766        assert_eq!(plain, src);
767        assert!(!spans.is_empty());
768    }
769}