Esc

Web

moduleextensionexperimentalSource
  • macOS: Everything works on macOS
  • Linux: Everything works on Linux
  • Windows: Everything works on Windows
  • Wasm: Not available on Wasm
·since 0.36.1

#import "Extensions/Web";

Compile-time HTML components and a concurrent static-site writer. Templates preserve literal bytes and escape value holes for their HTML context.

Example
out: Out;
defer deinit(*out);
title := "A & B";
html(*out, "<h1>{title}</h1>");
assert(to_string(*out) == "<h1>A &amp; B</h1>");

Procedures#

General#

resetexperimentalsince 0.36.1Source
(out: *Out)

Clears a page while retaining array capacity for the next page.

out: Out;
defer deinit(*out);
append(*out, "old");
reset(*out);
append(*out, "new");
assert(to_string(*out) == "new");
appendexperimental4 overloadssince 0.36.1Source
(out: *Out, s: string)
(out: *Out, data: *u8, count: int)
(out: *Out, data: [] u8)
(out: *Out, byte: u8)

Appends bytes verbatim; use html or the escaping helpers for untrusted text.

out: Out;
defer deinit(*out);
append(*out, "<br>");
assert(to_string(*out) == "<br>");
bytesexperimentalsince 0.36.1Source
(out: *Out) -> [] u8

A borrowed contiguous view, valid until the next append, reset or deinit.

out: Out;
defer deinit(*out);
append(*out, "abc");
assert(bytes(*out).count == 3);
to_stringexperimentalsince 0.36.1Source
(out: *Out) -> string

A borrowed string with the same lifetime as bytes.

out: Out;
defer deinit(*out);
append(*out, "abc");
assert(to_string(*out) == "abc");
escape_textexperimentalsince 0.36.1Source
(out: *Out, s: string)

Escapes ampersands and angle brackets, copying safe runs together.

out: Out;
defer deinit(*out);
escape_text(*out, "<&>");
assert(to_string(*out) == "&lt;&amp;&gt;");
htmlexperimentalsince 0.36.1Source
(destination: *Out, $t: string, loc := #caller_code)

Compiles a constant template in the caller's scope. The first argument must be an identifier or *identifier; its name need not be out. Components start with uppercase. Control branches must finish in the same HTML state; loops preserve their entry state.

Card :: (dest: *Out, title: string) {
    html(dest, "<p>{title}</p>");
}
out: Out;
defer deinit(*out);
html(*out, "<main>{Card(\"Hi\")}</main>");
assert(to_string(*out) == "<main><p>Hi</p></main>");

Writer#

writer_initexperimentalsince 0.36.1Source
(out_dir: string, base_url: string, dry_run := false) -> Writer

Initializes a writer. Dry runs retain paths and links, without retaining page bodies.

w := writer_init("unused", "/", true);
defer deinit(*w);
assert(w.dry_run);
write_pageexperimentalsince 0.36.1Source
(w: *Writer, path: string, out: *Out) -> bool

Writes a page as <path>.html (the root page, with an empty path, as index.html) and copies its unescaped links into writer-owned storage. Paths are relative and have no trailing / or .html, so a page is served at its path without an extension; each page path has one producer.

w := writer_init("unused", "/", true);
defer deinit(*w);
out: Out;
defer deinit(*out);
html(*out, "<p>Hi</p>");
assert(write_page(*w, "api", *out));
write_fileexperimental2 overloadssince 0.36.1Source
(w: *Writer, path: string, data: string) -> bool
(w: *Writer, path: string, data: [] u8) -> bool

Writes an asset, which also counts as a link target. Returns false and collects any error.

w := writer_init("unused", "/", true);
defer deinit(*w);
assert(write_file(*w, "assets/a.js", "let a = 1;"));

Parallel#

render_parallelexperimentalsince 0.36.1Source
(jobs: [] $T, render: (out: *Out, job: *T, data: *$D), data: *D, threads := 0)

Renders jobs on a Thread_Group. Each worker reuses one Out and resets temporary storage after each job. Shared results belong in data behind a mutex (Writer already does this). Zero threads chooses CPU count minus one, with a minimum of one.

render :: (out: *Out, job: *int, count: *int) {
    html(out, "<p>{job.*}</p>");
}
jobs := int.[1, 2, 3];
count := 0;
render_parallel(jobs, render, *count, threads = 2);

Assets#

content_stampexperimental2 overloadssince 0.36.1Source
(data: string) -> string
(data: [] u8) -> string

Eight lowercase hex digits: the high half of FNV-1a 64, matching API-site asset URLs. The result is in temporary storage.

assert(content_stamp("") == "cbf29ce4");
compact_cssexperimentalsince 0.36.1Source
(text: string) -> string

Removes CSS block comments and blank/edge whitespace, preserving quoted strings. The result is in temporary storage; comments become spaces to keep tokens separate.

assert(compact_css("  a { color: red; } /* note */\n") == "a { color: red; }\n");
compact_jsexperimentalsince 0.36.1Source
(text: string) -> string

Drops indentation, blank lines and whole-line // comments, preserving other JS bytes. Multiline strings, template literals and block comments are kept verbatim internally.

assert(compact_js("  // note\n  let url = 'https://x';\n") == "let url = 'https://x';\n");

Types#

Htmltypeexperimentalsince 0.36.1Source
:: #type,distinct string

Markup that the caller has checked is safe for its insertion context.

safe := cast(Html) ("<br>");
assert(cast(string) safe == "<br>");
Outstructexperimentalsince 0.36.1Source

Reusable page storage. Do not copy it after use; each rendering thread owns one. Borrow link strings until the next append; the link list expires at reset. Disable record_links to skip recording.

Out :: struct {
    data: [..] u8;
    links: [..] string;
    record_links := true;
    link: [..] u8;
    link_start: int;
    offsets: [..] Link_Offset;
}
out: Out;
defer deinit(*out);
append(*out, "hello");
reset(*out);
assert(bytes(*out).count == 0);
Templatestructexperimentalsince 0.36.1Source

Implementation entry points used by generated templates.

Template :: struct {
    // Starts recording one link; used by generated templates.
    // ```jai
    // out: Out;
    // defer deinit(*out);
    // Template.begin(*out);
    // Template.piece(*out, "/");
    // Template.finish(*out);
    // assert(out.links[0] == "/");
    // ```
    begin :: (out: *Out) {
        out.link_start = out.link.count;
    }
    // Records unescaped link bytes when recording is enabled.
    // ```jai
    // out: Out;
    // defer deinit(*out);
    // Template.begin(*out);
    // Template.piece(*out, "/");
    // Template.finish(*out);
    // assert(out.links[0] == "/");
    // ```
    piece :: (out: *Out, s: string) {
        if !out.record_links return;

        before := out.link.data;

        array_add(*out.link, ..(cast([] u8) s));

        if before != out.link.data {
            for offset, i: out.offsets out.links[i] = string.{ offset.count, out.link.data + offset.start };
        }
    }
    // Saves an offset into the page's link bytes; earlier links survive growth.
    // ```jai
    // out: Out;
    // defer deinit(*out);
    // Template.begin(*out);
    // Template.piece(*out, "/");
    // Template.finish(*out);
    // assert(out.links[0] == "/");
    // ```
    finish :: (out: *Out) {
        if !out.record_links return;
        count := out.link.count - out.link_start;
        array_add(*out.offsets, .{ out.link_start, count });
        array_add(*out.links, string.{ count, out.link.data + out.link_start });
    }
    // Appends a typed template hole; unsupported types report at location.
    // ```jai
    // out: Out;
    // defer deinit(*out);
    // Template.value(*out, "<&", false, false, false, "text");
    // assert(to_string(*out) == "&lt;&amp;");
    // ```
    value :: (out: *Out, v: $T, $attribute: bool, $raw: bool, $link: bool, $hole: string, $location: Source_Code_Location = #caller_location) {
        #if T == Html {
            append_html(out, v);
            #if link piece(out, cast(string) v);
        } else #if raw {
            #run compiler_report(tprint("Web: hole `{%}` has type %; script/style holes require Html", hole, T), location);
        } else #if T == string {
            #if attribute escape_attribute(out, v);
            else escape_text(out, v);
            #if link piece(out, v);
        } else #if type_info(T).type == .INTEGER {
            text := tprint("%", v);
            append(out, text);
            #if link piece(out, text);
        } else {
            #run compiler_report(tprint("Web: hole `{%}` has unsupported type %", hole, T), location);
        }
    }
}
out: Out;
defer deinit(*out);
Template.value(*out, 12, false, false, false, "12");
assert(to_string(*out) == "12");
Writerstructexperimentalsince 0.36.1Source

Concurrent output-tree metadata and collected errors. Use writer_init, then deinit after all render threads join. Read errors and check_links only after the writes finish.

Writer :: struct {
    out_dir: string;
    base_url: string;
    dry_run: bool;
    errors: [..] string;
    files: Maps.Map(string, [] string);
    folders: Maps.Map(string, bool);
    mutex: Threads.Mutex;
    pool: Arena.Pool;
}
w := writer_init("unused", "/docs/", dry_run = true);
defer deinit(*w);
assert(write_file(*w, "site.css", "body {}"));
assert(w.errors.count == 0);