app: cherry-pick rune's pause and sound fixes onto the checkout
Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch ported, carrying the four commits of upstream issues 1320 (a pause while a clip is layered holds the layer's picture and time) and 1325 (a video's sound is read ahead of the clock and leads it). Both were written against eb9f1104 and ported across the refactors since. The faults are the first two and the third in docs/rune-upstream.md; the app's workarounds in review.rs stay until the fixes arrive upstream.
This commit is contained in:
1 parent
80fef698ce
commit
5bf262b82b
3795 files changed
+663463
-28
No files matched your search
+13
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env bun
|
||||
// `bun run build [--mode dev]`: typecheck, client build (Cloudflare Build Output), SSR build, then prerender every
|
||||
// route to static HTML.
|
||||
import { parseArgs } from "node:util"
|
||||
import { $ } from "bun"
|
||||
|
||||
const { values } = parseArgs({ options: { mode: { type: "string", default: "production" } } })
|
||||
const mode = values.mode
|
||||
|
||||
await $`tsc --noEmit`
|
||||
await $`vite build --mode ${mode}`
|
||||
await $`vite build --mode ${mode} --ssr src/entry-server.tsx --outDir dist-ssr`
|
||||
await $`bun scripts/prerender.ts --mode ${mode}`
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
/** A small build-time highlighter: one regex pass per language, spans with `tk-*` classes. Copied from
|
||||
* @anomalyco/site's content/highlight.ts until this site moves onto the shared package. Only scripts/snippets.ts
|
||||
* imports it, at build time; the client gets finished HTML. */
|
||||
|
||||
export type CodeLang = "rust" | "toml" | "ts" | "css" | "shell" | "plain"
|
||||
export const CODE_LANGS: readonly CodeLang[] = ["rust", "toml", "ts", "css", "shell", "plain"]
|
||||
|
||||
type Role = "k" | "s" | "n" | "t" | "f" | "a" | "c" | "p"
|
||||
type Rule = [RegExp, Role | null]
|
||||
|
||||
const escape = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """)
|
||||
const words = (list: string) => new RegExp(`\\b(?:${list.split(" ").join("|")})\\b`, "y")
|
||||
|
||||
const STRING: Rule = [/"(?:\\.|[^"\\\n])*"?/y, "s"]
|
||||
const NUMBER: Rule = [/\b\d[\d_]*(?:\.\d+)?(?:[a-z%]+\d*)?\b|(?<![\w.])\.\d+\b/y, "n"]
|
||||
const WORD: Rule = [/[A-Za-z_][\w]*/y, null]
|
||||
|
||||
const RULES: Record<Exclude<CodeLang, "plain">, Rule[]> = {
|
||||
rust: [
|
||||
[/\/\/[^\n]*/y, "c"],
|
||||
STRING,
|
||||
[/#!?\[[^\]\n]*\]/y, "a"],
|
||||
[/'[a-z_]\w*\b(?!')/y, "a"],
|
||||
[/[a-z_]\w*!/y, "f"],
|
||||
NUMBER,
|
||||
[words("as async await break const continue crate dyn else enum extern false fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait true type unsafe use where while"), "k"],
|
||||
[/[A-Z]\w*/y, "t"],
|
||||
[/[a-z_]\w*(?=\s*(?:::<[^>]*>)?\()/y, "f"],
|
||||
WORD,
|
||||
[/::|->|=>|[{}()[\];,<>&|]/y, "p"],
|
||||
],
|
||||
toml: [
|
||||
[/#[^\n]*/y, "c"],
|
||||
STRING,
|
||||
[/(?<=^|\n)\s*\[\[?[^\]\n]+\]\]?/y, "a"],
|
||||
[words("true false"), "k"],
|
||||
NUMBER,
|
||||
[/[A-Za-z_][\w.:-]*(?=\s*=)/y, null],
|
||||
WORD,
|
||||
[/[{}[\],=]/y, "p"],
|
||||
],
|
||||
ts: [
|
||||
[/\/\/[^\n]*|\/\*[\s\S]*?\*\//y, "c"],
|
||||
STRING,
|
||||
[/'(?:\\.|[^'\\\n])*'?|`(?:\\.|[^`\\])*`?/y, "s"],
|
||||
NUMBER,
|
||||
[words("as async await break case catch class const continue default else export extends false for from function if import in interface let new null of return satisfies switch this throw true try type typeof undefined var void while"), "k"],
|
||||
[/[A-Z]\w*/y, "t"],
|
||||
[/[a-z_$][\w$]*(?=\s*\()/y, "f"],
|
||||
[/[\w$]+/y, null],
|
||||
[/=>|[{}()[\];,<>=:|&?]/y, "p"],
|
||||
],
|
||||
css: [
|
||||
[/\/\*[\s\S]*?\*\//y, "c"],
|
||||
STRING,
|
||||
[/@[\w-]+/y, "k"],
|
||||
[/--[\w-]+/y, "a"],
|
||||
[/[a-z-]+(?=\s*:(?!:))/y, null],
|
||||
[/#[0-9a-fA-F]{3,8}\b/y, "n"],
|
||||
NUMBER,
|
||||
[/[a-z-]+(?=\()/y, "f"],
|
||||
[/::?[a-z-]+/y, "a"],
|
||||
[/[\w-]+/y, null],
|
||||
[/[{}()[\];,:/]/y, "p"],
|
||||
],
|
||||
shell: [
|
||||
[/#[^\n]*/y, "c"],
|
||||
STRING,
|
||||
[/'[^'\n]*'?/y, "s"],
|
||||
[/(?<=^|[|;&]\s*)[\w./+-]+/y, "f"],
|
||||
[/(?<=\s)--?[\w-]+/y, "a"],
|
||||
[/<[\w-]+>/y, "c"],
|
||||
[/[\w./:@+-]+/y, null],
|
||||
[/[|;&=<>]/y, "p"],
|
||||
],
|
||||
}
|
||||
|
||||
export function highlight(code: string, lang: CodeLang): string {
|
||||
if (lang === "plain") return escape(code)
|
||||
const rules = RULES[lang]
|
||||
const runs: { role: Role | null; text: string }[] = []
|
||||
const push = (role: Role | null, text: string) => {
|
||||
const last = runs.at(-1)
|
||||
// Whitespace joins the run before it, so `) -> (` stays one span.
|
||||
if (last && (last.role === role || (last.role && /^\s+$/.test(text)))) last.text += text
|
||||
else runs.push({ role, text })
|
||||
}
|
||||
let i = 0
|
||||
outer: while (i < code.length) {
|
||||
for (const [re, role] of rules) {
|
||||
re.lastIndex = i
|
||||
const m = re.exec(code)
|
||||
if (m && m[0].length > 0) {
|
||||
push(role, m[0])
|
||||
i += m[0].length
|
||||
continue outer
|
||||
}
|
||||
}
|
||||
push(null, code[i]!)
|
||||
i++
|
||||
}
|
||||
return runs
|
||||
.map(({ role, text }) => {
|
||||
if (!role) return escape(text)
|
||||
const body = text.trimEnd()
|
||||
return `<span class="tk-${role}">${escape(body)}</span>${escape(text.slice(body.length))}`
|
||||
})
|
||||
.join("")
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env bun
|
||||
// `bun scripts/icons.ts`: draws the brand into public/: favicon.svg and favicon.ico (16 and 32) from the 16-cell ᚱ on
|
||||
// transparent; apple-touch-icon.png (180), icon-192.png and icon-512.png from the wordmark's ᚱ on black; and og.png
|
||||
// (1200 × 630), the whole wordmark on black. Every cell is a whole number of pixels, so the PNGs are written directly,
|
||||
// with no browser.
|
||||
import { writeFileSync } from "node:fs"
|
||||
import { join, resolve } from "node:path"
|
||||
import { deflateSync } from "node:zlib"
|
||||
import { ICON16, INK, WORDMARK, oklch, runs, type Grid } from "../src/brand/pixels"
|
||||
|
||||
const out = resolve(import.meta.dirname, "..", "public")
|
||||
const ink = oklch(...INK).map(c => Math.round(c * 255)) as [number, number, number]
|
||||
const hex = `#${ink.map(c => c.toString(16).padStart(2, "0")).join("")}`
|
||||
|
||||
const crcTable = Array.from({ length: 256 }, (_, n) => {
|
||||
let c = n
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
|
||||
return c >>> 0
|
||||
})
|
||||
const crc = (bytes: Uint8Array) => {
|
||||
let c = 0xffffffff
|
||||
for (const b of bytes) c = crcTable[(c ^ b) & 0xff]! ^ (c >>> 8)
|
||||
return (c ^ 0xffffffff) >>> 0
|
||||
}
|
||||
function chunk(type: string, data: Uint8Array) {
|
||||
const body = new Uint8Array(4 + data.length)
|
||||
body.set(new TextEncoder().encode(type))
|
||||
body.set(data, 4)
|
||||
const out = new Uint8Array(12 + data.length)
|
||||
const dv = new DataView(out.buffer)
|
||||
dv.setUint32(0, data.length)
|
||||
out.set(body, 4)
|
||||
dv.setUint32(8 + data.length, crc(body))
|
||||
return out
|
||||
}
|
||||
|
||||
/** `rows` at `px` pixels a cell, centred in a `width` × `height` image on `background` (null for transparent), as an
|
||||
* RGBA PNG. */
|
||||
function png(rows: Grid, px: number, background: [number, number, number] | null, width: number, height = width) {
|
||||
const w = rows[0]!.length * px, h = rows.length * px
|
||||
const ox = Math.floor((width - w) / 2), oy = Math.floor((height - h) / 2)
|
||||
const raw = new Uint8Array(height * (width * 4 + 1))
|
||||
for (let y = 0; y < height; y++) {
|
||||
const row = y * (width * 4 + 1)
|
||||
for (let x = 0; x < width; x++) {
|
||||
const cx = Math.floor((x - ox) / px), cy = Math.floor((y - oy) / px)
|
||||
const on = x >= ox && y >= oy && rows[cy]?.[cx] === "#"
|
||||
const rgb = on ? ink : background
|
||||
if (rgb) raw.set([...rgb, 255], row + 1 + x * 4)
|
||||
}
|
||||
}
|
||||
const header = new Uint8Array(13)
|
||||
const dv = new DataView(header.buffer)
|
||||
dv.setUint32(0, width)
|
||||
dv.setUint32(4, height)
|
||||
header.set([8, 6, 0, 0, 0], 8)
|
||||
const parts = [new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", header), chunk("IDAT", deflateSync(raw)), chunk("IEND", new Uint8Array())]
|
||||
return Buffer.concat(parts)
|
||||
}
|
||||
|
||||
/** An ICO holding PNGs, one entry per size. */
|
||||
function ico(images: { png: Uint8Array; size: number }[]) {
|
||||
const header = 6 + 16 * images.length
|
||||
const out = new Uint8Array(header + images.reduce((n, i) => n + i.png.length, 0))
|
||||
const dv = new DataView(out.buffer)
|
||||
dv.setUint16(2, 1, true)
|
||||
dv.setUint16(4, images.length, true)
|
||||
let offset = header
|
||||
images.forEach(({ png, size }, k) => {
|
||||
const e = 6 + 16 * k
|
||||
out[e] = size
|
||||
out[e + 1] = size
|
||||
dv.setUint16(e + 4, 1, true)
|
||||
dv.setUint16(e + 6, 32, true)
|
||||
dv.setUint32(e + 8, png.length, true)
|
||||
dv.setUint32(e + 12, offset, true)
|
||||
out.set(png, offset)
|
||||
offset += png.length
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
const rune = WORDMARK.glyphs[0]!.rows
|
||||
const black: [number, number, number] = [0, 0, 0]
|
||||
for (const [name, size, px] of [["icon-512.png", 512, 32], ["icon-192.png", 192, 12], ["apple-touch-icon.png", 180, 12]] as const) {
|
||||
writeFileSync(join(out, name), png(rune, px, black, size))
|
||||
}
|
||||
writeFileSync(join(out, "favicon.ico"), ico([32, 16].map(size => ({ size, png: png(ICON16, size / 16, null, size) }))))
|
||||
const word = Array.from({ length: WORDMARK.height }, (_, y) =>
|
||||
Array.from({ length: WORDMARK.width }, (_, x) => (WORDMARK.glyphs.some(g => g.rows[y]?.[x - g.x] === "#") ? "#" : ".")).join(""))
|
||||
writeFileSync(join(out, "og.png"), png(word, 24, black, 1200, 630))
|
||||
const rects = runs(ICON16).map(([x, y, w, h]) => `<rect x="${x}" y="${y}" width="${w}" height="${h}"/>`).join("")
|
||||
writeFileSync(join(out, "favicon.svg"), `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" shape-rendering="crispEdges" fill="${hex}">${rects}</svg>\n`)
|
||||
console.log(`Icons in ${ink.join(",")} (${hex}) → ${out}`)
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { join, relative, resolve } from "node:path"
|
||||
import { parseArgs } from "node:util"
|
||||
import { getWorkerAssetsDir } from "@cloudflare/build-output-utils"
|
||||
import { BASE_PATH, hostForMode } from "../src/base"
|
||||
import { REPO, type Route } from "../src/routes"
|
||||
|
||||
const { values } = parseArgs({ options: { mode: { type: "string", default: "production" } } })
|
||||
const origin = `https://${hostForMode(values.mode)}${BASE_PATH}`
|
||||
|
||||
const root = resolve(import.meta.dirname, "..")
|
||||
const distDir = getWorkerAssetsDir(root)
|
||||
const distRel = relative(root, distDir)
|
||||
const ssrDir = join(root, "dist-ssr")
|
||||
const templatePath = join(distDir, "index.html")
|
||||
|
||||
if (!existsSync(templatePath)) throw new Error(`${distRel}/index.html not found; run \`vite build\` first`)
|
||||
|
||||
let template = readFileSync(templatePath, "utf8")
|
||||
if (!template.includes("<!--app-->")) throw new Error(`${distRel}/index.html is missing the <!--app--> marker`)
|
||||
|
||||
// Inline the one stylesheet so the first paint needs no extra request.
|
||||
template = template.replace(new RegExp(`<link rel="stylesheet"[^>]*href="${BASE_PATH}/(assets/[^"]+\\.css)"[^>]*>`, "g"), (full, href: string) => {
|
||||
const cssPath = join(distDir, href)
|
||||
if (!existsSync(cssPath)) return full
|
||||
return `<style>${readFileSync(cssPath, "utf8").replace(/<\/style/gi, "<\\/style")}</style>`
|
||||
})
|
||||
|
||||
const escape = (s: string) => s.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">")
|
||||
|
||||
const ssr = (await import(join(ssrDir, "entry-server.js"))) as {
|
||||
render: (pathname: string) => string
|
||||
routes: Route[]
|
||||
}
|
||||
|
||||
const page = (route: Route) =>
|
||||
template
|
||||
.replace(/<title>[\s\S]*?<\/title>/, `<title>${escape(route.title)}</title>`)
|
||||
.replace(/<meta name="description" content="[^"]*" \/>/, `<meta name="description" content="${escape(route.description)}" />`)
|
||||
.replaceAll("__URL__", `${origin}${route.path}`)
|
||||
.replaceAll("__TITLE__", escape(route.title))
|
||||
.replaceAll("__DESCRIPTION__", escape(route.description))
|
||||
.replaceAll("__ORIGIN__", origin)
|
||||
.replace("<!--app-->", ssr.render(route.path))
|
||||
|
||||
// The Worker serves this for any missing path under the base, with a 404.
|
||||
const notFound = page({ path: "/404", label: "Not found", title: "Not found · Rune", description: "There's no page here." })
|
||||
writeFileSync(join(distDir, "404.html"), notFound.replace(/\s*<link rel="canonical"[^>]*>/, ""))
|
||||
|
||||
// Every link into the repo names a file or folder that exists, so code references can't drift.
|
||||
const repoRoot = resolve(root, "..")
|
||||
const missing = new Set<string>()
|
||||
const checkRepoLinks = (html: string) => {
|
||||
for (const [, path] of html.matchAll(new RegExp(`${REPO}/(?:blob|tree)/dev/([^"#?]+)`, "g"))) {
|
||||
if (!existsSync(join(repoRoot, decodeURIComponent(path!)))) missing.add(path!)
|
||||
}
|
||||
}
|
||||
|
||||
for (const route of ssr.routes) {
|
||||
const html = page(route)
|
||||
checkRepoLinks(html)
|
||||
if (route.path === "/") {
|
||||
writeFileSync(templatePath, html)
|
||||
} else {
|
||||
// Both files, so /principles serves directly instead of redirecting to /principles/.
|
||||
const dir = join(distDir, route.path.slice(1))
|
||||
mkdirSync(dir, { recursive: true })
|
||||
writeFileSync(join(dir, "index.html"), html)
|
||||
writeFileSync(`${dir}.html`, html)
|
||||
}
|
||||
}
|
||||
|
||||
if (missing.size) throw new Error(`Links to files that aren't in the repo:\n ${[...missing].join("\n ")}`)
|
||||
|
||||
// llms.txt (llmstxt.org): what the site is and where each page lives, from the same routes.
|
||||
const home = ssr.routes.find(r => r.path === "/")!
|
||||
writeFileSync(
|
||||
join(distDir, "llms.txt"),
|
||||
[
|
||||
"# Rune",
|
||||
"",
|
||||
`> ${home.description}`,
|
||||
"",
|
||||
"## Pages",
|
||||
"",
|
||||
...ssr.routes.map(r => `- [${r.label}](${origin}${r.path}): ${r.description}`),
|
||||
"",
|
||||
"## Source",
|
||||
"",
|
||||
`- [anomalyco/rune](${REPO}): the code`,
|
||||
`- [PLAN.md](${REPO}/blob/dev/PLAN.md): the full plan, the source of truth for this site`,
|
||||
"",
|
||||
].join("\n"),
|
||||
)
|
||||
|
||||
rmSync(ssrDir, { recursive: true, force: true })
|
||||
console.log(`Prerendered ${ssr.routes.length} routes into ${distRel}/`)
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
/** Code examples on the site, cut from Rune's own source at build time and highlighted there.
|
||||
*
|
||||
* Each snippet names files in this repo and where to cut. A piece starts at the first line beginning with `from`
|
||||
* (attributes above it come along) and ends at `to`, just before `until`, after `lines` lines, or at the closing
|
||||
* brace at the starting line's indent. A missing file or marker fails the build, so an example can't drift away from the code.
|
||||
* The Vite plugin serves the result as `virtual:snippets`; the client gets HTML strings, not the highlighter. */
|
||||
import { readFileSync } from "node:fs"
|
||||
import { resolve } from "node:path"
|
||||
import type { Plugin } from "vite"
|
||||
import { highlight, type CodeLang } from "./highlight"
|
||||
|
||||
type Piece = { file: string; from?: string; to?: string; until?: string; lines?: number }
|
||||
type Spec = { lang: CodeLang; label: string; pieces: Piece[] }
|
||||
|
||||
export type Snippet = { html: string; label: string; file: string; start: number; end: number }
|
||||
|
||||
const SETTINGS = "examples/settings/src/main.rs"
|
||||
const HELLO = "examples/hello/src/main.rs"
|
||||
const TODO = "examples/todo/src/main.rs"
|
||||
|
||||
const specs: Record<string, Spec> = {
|
||||
hello: {
|
||||
lang: "rust",
|
||||
label: "Rust",
|
||||
pieces: [{ file: HELLO, from: "use rune::", until: "#[cfg(test)]" }],
|
||||
},
|
||||
"hello-test": {
|
||||
lang: "rust",
|
||||
label: "Rust",
|
||||
pieces: [{ file: HELLO, from: " fn a_tap_flips_the_switch" }],
|
||||
},
|
||||
"todo-list": {
|
||||
lang: "rust",
|
||||
label: "Rust",
|
||||
pieces: [{ file: TODO, from: "fn view(" }],
|
||||
},
|
||||
"todo-spring": {
|
||||
lang: "rust",
|
||||
label: "Rust",
|
||||
pieces: [{ file: TODO, from: "fn progress(" }],
|
||||
},
|
||||
"overlay-windows": {
|
||||
lang: "rust",
|
||||
label: "Rust",
|
||||
pieces: [{ file: "examples/overlay/src/main.rs", from: " rune::run_windows(", to: " });" }],
|
||||
},
|
||||
"app-cargo": {
|
||||
lang: "toml",
|
||||
label: "TOML",
|
||||
pieces: [{ file: "examples/settings/Cargo.toml" }],
|
||||
},
|
||||
"app-main": {
|
||||
lang: "rust",
|
||||
label: "Rust",
|
||||
pieces: [
|
||||
{ file: SETTINGS, from: "fn view(", lines: 23 },
|
||||
{ file: SETTINGS, from: "fn main() {" },
|
||||
],
|
||||
},
|
||||
toggle: {
|
||||
lang: "rust",
|
||||
label: "Rust",
|
||||
pieces: [
|
||||
{ file: SETTINGS, from: ' toggle_row(p, "login"', lines: 3 },
|
||||
{ file: SETTINGS, from: "fn toggle_row(" },
|
||||
{ file: SETTINGS, from: "fn toggle(" },
|
||||
],
|
||||
},
|
||||
"toggle-only": {
|
||||
lang: "rust",
|
||||
label: "Rust",
|
||||
pieces: [{ file: SETTINGS, from: "fn toggle(" }],
|
||||
},
|
||||
"motion-tokens": {
|
||||
lang: "rust",
|
||||
label: "Rust",
|
||||
pieces: [
|
||||
{ file: "crates/rune-motion/src/tokens.rs", from: "/// Small controls", lines: 3 },
|
||||
{ file: "crates/rune-motion/src/tokens.rs", from: "pub const SNAPPY", lines: 1 },
|
||||
],
|
||||
},
|
||||
retarget: {
|
||||
lang: "rust",
|
||||
label: "Rust",
|
||||
pieces: [
|
||||
{
|
||||
file: "crates/rune-motion/tests/integration/spring.rs",
|
||||
from: "fn animated_value_retargets_keeping_velocity",
|
||||
to: " assert!((a.sample(5.0) + 50.0)",
|
||||
},
|
||||
],
|
||||
},
|
||||
live: {
|
||||
lang: "rust",
|
||||
label: "Rust",
|
||||
pieces: [
|
||||
{ file: "crates/rune/tests/integration/live.rs", from: "fn view(" },
|
||||
{ file: "crates/rune/tests/integration/live.rs", from: "fn properties_change_without_view", to: " assert_eq!(rt.stats.shaped, 0);" },
|
||||
],
|
||||
},
|
||||
"test-segmented": {
|
||||
lang: "rust",
|
||||
label: "Rust",
|
||||
pieces: [
|
||||
{ file: "crates/rune-kit/tests/integration/segmented.rs", from: "fn fitted(" },
|
||||
{ file: "crates/rune-kit/tests/integration/segmented.rs", from: "fn fitted_segments_share" },
|
||||
],
|
||||
},
|
||||
"snap-commands": {
|
||||
lang: "shell",
|
||||
label: "Shell",
|
||||
pieces: [{ file: "examples/live-values/README.md", from: "target/release/live-values --snap", lines: 2 }],
|
||||
},
|
||||
"tap-script": {
|
||||
lang: "ts",
|
||||
label: "JSON",
|
||||
pieces: [{ file: "examples/settings/scripts/toggle-retarget.json" }],
|
||||
},
|
||||
"golden-hashes": {
|
||||
lang: "rust",
|
||||
label: "Rust",
|
||||
pieces: [{ file: "crates/rune-ref/tests/reference.rs", from: "fn canonical_hashes" }],
|
||||
},
|
||||
"rune-deps": {
|
||||
lang: "toml",
|
||||
label: "TOML",
|
||||
pieces: [{ file: "crates/rune/Cargo.toml", from: "rune-core = ", to: "parley = " }],
|
||||
},
|
||||
}
|
||||
|
||||
const indentOf = (line: string) => line.match(/^\s*/)![0]
|
||||
|
||||
function cut(root: string, id: string, piece: Piece): { text: string; start: number; end: number } {
|
||||
const where = `snippet "${id}": ${piece.file}`
|
||||
let source: string
|
||||
try {
|
||||
source = readFileSync(resolve(root, piece.file), "utf8")
|
||||
} catch {
|
||||
throw new Error(`${where} not found`)
|
||||
}
|
||||
const lines = source.replace(/\n$/, "").split("\n")
|
||||
if (!piece.from) return { text: lines.join("\n"), start: 1, end: lines.length }
|
||||
|
||||
const first = lines.findIndex(l => l.startsWith(piece.from!))
|
||||
if (first < 0) throw new Error(`${where}: no line starts with ${JSON.stringify(piece.from)}`)
|
||||
let start = first
|
||||
while (start > 0 && lines[start - 1]!.trim().startsWith("#[")) start--
|
||||
|
||||
let end: number
|
||||
if (piece.lines) {
|
||||
end = first + piece.lines - 1
|
||||
} else if (piece.until) {
|
||||
end = lines.findIndex((l, i) => i > first && l.startsWith(piece.until!)) - 1
|
||||
if (end < 0) throw new Error(`${where}: no line starts with ${JSON.stringify(piece.until)} after ${JSON.stringify(piece.from)}`)
|
||||
while (end > first && !lines[end]!.trim()) end--
|
||||
} else if (piece.to) {
|
||||
end = lines.findIndex((l, i) => i >= first && l.startsWith(piece.to!))
|
||||
if (end < 0) throw new Error(`${where}: no line starts with ${JSON.stringify(piece.to)} after ${JSON.stringify(piece.from)}`)
|
||||
} else {
|
||||
const close = `${indentOf(lines[first]!)}}`
|
||||
end = lines.findIndex((l, i) => i > first && l.trimEnd() === close)
|
||||
if (end < 0) throw new Error(`${where}: no closing brace for ${JSON.stringify(piece.from)}`)
|
||||
}
|
||||
|
||||
const taken = lines.slice(start, end + 1)
|
||||
const pad = Math.min(...taken.filter(l => l.trim()).map(l => indentOf(l).length))
|
||||
const out = taken.map(l => l.slice(pad))
|
||||
// A block cut short keeps its shape: an elision inside, then its closing brace.
|
||||
const open = (out.join("\n").match(/\{/g)?.length ?? 0) - (out.join("\n").match(/\}/g)?.length ?? 0)
|
||||
if (open > 0) {
|
||||
const indent = indentOf(lines[first]!).slice(pad)
|
||||
out.push(`${indent} // …`, `${indent}}`)
|
||||
}
|
||||
return { text: out.join("\n"), start: start + 1, end: end + 1 }
|
||||
}
|
||||
|
||||
export function buildSnippets(root: string): Record<string, Snippet> {
|
||||
const out: Record<string, Snippet> = {}
|
||||
for (const [id, spec] of Object.entries(specs)) {
|
||||
const parts = spec.pieces.map(p => cut(root, id, p))
|
||||
const gap = spec.lang === "rust" || spec.lang === "ts" ? "\n\n// …\n\n" : "\n\n# …\n\n"
|
||||
const code = parts.map(p => p.text).join(gap)
|
||||
// One cut links to its lines; several cuts or a whole file link to the file.
|
||||
const one = spec.pieces.length === 1 && spec.pieces[0]!.from ? parts[0]! : undefined
|
||||
out[id] = {
|
||||
html: highlight(code, spec.lang),
|
||||
label: spec.label,
|
||||
file: spec.pieces[0]!.file,
|
||||
start: one?.start ?? 0,
|
||||
end: one?.end ?? 0,
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const ID = "virtual:snippets"
|
||||
|
||||
/** Serves the snippets as a module and reloads the page when a cited file changes in dev. */
|
||||
export function snippets(root: string): Plugin {
|
||||
const files = new Set(Object.values(specs).flatMap(s => s.pieces.map(p => resolve(root, p.file))))
|
||||
return {
|
||||
name: "rune-snippets",
|
||||
resolveId: id => (id === ID ? `\0${ID}` : undefined),
|
||||
load(id) {
|
||||
if (id !== `\0${ID}`) return
|
||||
for (const f of files) this.addWatchFile(f)
|
||||
return `export default ${JSON.stringify(buildSnippets(root))}`
|
||||
},
|
||||
handleHotUpdate({ file, server }) {
|
||||
if (!files.has(file)) return
|
||||
const mod = server.moduleGraph.getModuleById(`\0${ID}`)
|
||||
if (mod) server.moduleGraph.invalidateModule(mod)
|
||||
server.ws.send({ type: "full-reload" })
|
||||
},
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user