docs(api): per-symbol pages, fuzzy search, deep token linking, hover cards
All checks were successful
docs / build-and-deploy (push) Successful in 2s

Rebuild the API Reference around one page per symbol and richer, verified content.

Pages & navigation
- One HTML page per symbol (kw-*, type-*, phase-*, screen-*, fn-*, annot-*, op-*)
  instead of a single scrolling page; namespace overview pages (ns-screen …
  ns-color) and a searchable index (api.html) with client-side fuzzy search.
- Sticky-header scroll offset (scroll-margin) so a jumped-to entry/param/color is
  never hidden, plus a flash highlight on the scrolled-to target.

Deep linking in every snippet & example
- Namespace members split: `Screen`→namespace page, `fill_rectangle`→method page;
  `Color`→palette page, `Charcoal`→its swatch — separately.
- Named arguments (`width:`) link to that parameter's anchor on the method page.
- Hover any token for a summary card built from the real API data (symbols.json).

Content & coverage
- Full authoritative surface documented from the compiler: every keyword, type,
  the 6 phases (Start/Input/FixedUpdate/Update/LateUpdate/Render, each its own
  page), all 22 annotations, namespace methods with parameter docs, builtins,
  the world_* reflection ABI, networking, operators — 155 symbols.
- Longer, clearer explanations; "model"/"model instance" terminology, not "entity";
  descriptive identifiers in every example (Position{column,row}, Velocity{delta_x,
  delta_y}, Health{current,maximum}, Player/Enemy) — no Pos/Seg/x/dx.
- Accuracy fixes from compiler ground-truth: world_count() takes no arg,
  world_query_next(property, cursor) arg order, event fields bind by name; dropped
  `when` and `module` (not in the self-hosted parser).

Tooling
- inventory.json + check.py: coverage guard (every symbol has a page), duplicate-
  token guard, and broken-link guard — fail CI so docs can't drift.
- validate.py: compiles every ```ludic example against bin/ludicc (158 compile).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Orkun ÇAKILKAYA 2026-08-29 17:53:22 +03:00
parent 25f987e30d
commit 3c7ec9b016
172 changed files with 5240 additions and 895 deletions

View file

@ -7,61 +7,81 @@ source of truth, so the site can never drift from the language.
```
docs/
language/<category>/<id>.md one file per symbol — keyword, type, builtin,
namespace method, operator, annotation
language/<category>/<id>.md one file per symbol — keyword, type, phase,
builtin, namespace method, operator, annotation
language/<category>/_section.md section title + blurb + order
language/colors/palette.json the 221 named colors (generated by palette.py)
site/site.json landing-page messaging (hero, features, …)
site/snippets/*.ludic the code shown on the landing page (real programs)
tools/docgen/inventory.json the authoritative symbol set the coverage guard checks
```
### A symbol file
```markdown
---
id: kw-handler # anchor in api.html (kw-*, type-*, fn-*, <ns>-*, op-*, annot-*)
name: handler # display name / heading
category: control # which section (matches the directory)
kind: keyword # keyword | type | phase | namespace-method | builtin | annotation | operator
tokens: handler # the literal token(s) the highlighter recognizes & links
sig: handler Name phase P { … }
tip: A block that runs each frame in a given phase. # one-line hover tip
order: 3
id: screen-fill_rectangle # anchor + page name (screen-fill_rectangle.html)
name: Screen.fill_rectangle
category: screen
kind: namespace-method # keyword|type|phase|namespace-method|builtin|annotation|operator
tokens: Screen.fill_rectangle # literal token(s) the highlighter matches & links
sig: Screen.fill_rectangle(x, y, width, height, color)
tip: Draw a solid, filled rectangle. # one sentence — the hover-card summary
order: 1
ns: Screen # namespace-method only
member: fill_rectangle # namespace-method only
related: screen-clear screen-draw_rectangle
---
Full description — inline HTML (`<code>`, `<b>`) and `backtick code` both work.
Rich description — inline `<code>`/`backticks`, "model instance" language.
```ludic
handler Move phase Update { … }
```
Parameters: # for anything that takes arguments
- `x` — the left edge, in pixels
- `color` — the fill color, e.g. a `Color.*` name
​```ludic
program Example { … descriptive-named, compilable … }
​```
```
Add such a file and it appears in the API Reference, is recognized + tipped +
linked in **every** code snippet across the site, and lands in `symbols.json` —
with no other file to edit.
## What it produces
## Build
One **page per symbol** (`<id>.html`), a namespace overview page per namespace
(`ns-screen.html` … `ns-color.html`), a searchable **index** (`api.html`, fuzzy
search over every symbol), the **landing page** (`index.html`), the
`ludic-highlight.js` highlighter (all its symbol tables, tips, per-item link
targets, per-parameter anchors and hover-card data generated from the sources
above), `symbols.json`, and `.nojekyll`.
In any code sample: keywords/types/builtins/annotations link to their page;
`Screen.fill_rectangle` links `Screen` → the namespace page and `fill_rectangle`
→ the method page separately; a named argument like `width:` links to that
parameter's anchor; `Color.Charcoal` links `Color` and `Charcoal` separately;
hovering any token shows a summary card from the real API data.
## Build & check
```bash
python3 tools/docgen/gen.py --out build/pages # generate the whole site
python3 tools/docgen/check.py build/pages # sanity-check before publish
python3 tools/docgen/gen.py --out build/pages # generate the whole site
python3 tools/docgen/check.py build/pages # coverage + duplicate-token + link guard
python3 tools/docgen/validate.py # compile every ```ludic example with bin/ludicc
```
Outputs into `--out`: `index.html`, `api.html`, `ludic-highlight.js`
(its symbol tables generated from the sources above), `symbols.json`, `.nojekyll`.
`check.py` fails CI if any symbol in `inventory.json` lacks a page, if a token is
documented on two pages, or if a highlighter link points at a missing page — so
"every symbol is documented, autogenerated each time" is enforced. `validate.py`
needs a built `bin/ludicc`; the deploy CI is Python-only, so run it locally or in
a toolchain-enabled job.
No third-party dependencies — Python standard library only.
## Publish
`.forgejo/workflows/docs.yml` runs this on every push to `main` that touches
`docs/**` or `tools/docgen/**`, and force-publishes the result to the `pages`
branch root (which the pages-server serves). It needs a repo secret
`PAGES_TOKEN` with write access (or the automatic Actions token enabled for
pushes). `index.html` + `.nojekyll` always stay at the branch root.
`.forgejo/workflows/docs.yml` runs `gen.py` + `check.py` on every push to `main`
that touches `docs/**` or `tools/docgen/**`, and publishes the result to the
`pages` branch root. `index.html` + `.nojekyll` always stay at the root.
## Colors
`palette.json` is generated by `tools/docgen/palette.py` from a single `PALETTE`
table, which also generates `selfhost/emit_color.ludic`. Regenerate colors
there; never hand-edit either output.
table, which also generates `selfhost/emit_color.ludic`. Regenerate colors there.

View file

@ -0,0 +1,166 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>%(title)s</title>
<meta name="description" content="%(desc)s">
<meta property="og:title" content="%(ogt)s">
<meta property="og:description" content="%(ogd)s">
<meta property="og:type" content="website">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet">
<style>
%(css)s
</style>
</head>
<body>
<header class="nav">
<div class="wrap nav-in">
<a class="brand" href="#top"><span class="logo">L</span> %(brand)s</a>
<nav class="nav-links">%(navlinks)s
<a class="nav-cta" href="%(repo)s">Source ↗</a>
</nav>
</div>
</header>
<a id="top"></a>
<section class="hero">
<div class="wrap hero-grid">
<div>
<span class="pill"><span class="dot"></span> %(pill)s</span>
<h1>%(title_pre)s <span class="accent">%(title_accent)s</span></h1>
<p class="lead">%(lead)s</p>
<div class="cta-row">
<a class="btn btn-primary" href="%(pcta_h)s">%(pcta_l)s</a>
<a class="btn btn-ghost" href="%(scta_h)s">%(scta_l)s</a>
</div>
</div>
<div class="code-card reveal">
<div class="code-top">
<span class="tl r"></span><span class="tl y"></span><span class="tl g"></span>
<span class="code-name">%(hero_name)s</span>
</div>
<pre data-lang="ludic">%(hero_code)s</pre>
</div>
</div>
<div class="wrap" style="margin-top:52px">
<div class="pipeline reveal">%(stages)s</div>
<p style="text-align:center;color:var(--muted);font-size:13.5px;margin:14px 0 0">%(pipenote)s</p>
</div>
</section>
<section id="features">
<div class="wrap">
<div class="sec-head reveal">
<div class="kicker">%(feat_kicker)s</div>
<h2>%(feat_title)s</h2>
<p>%(feat_intro)s</p>
</div>
<div class="feat-grid">%(feats)s</div>
</div>
</section>
<section id="showcase" style="padding-top:24px">
<div class="wrap">
<div class="sec-head reveal">
<div class="kicker">%(sc_kicker)s</div>
<h2>%(sc_title)s</h2>
<p>%(sc_intro)s</p>
</div>
<div class="tabs reveal" id="tabs"></div>
<div id="panels"></div>
<div class="showcase-note reveal"><span class="b">↳</span><span id="note"></span></div>
</div>
</section>
<section style="padding-top:24px">
<div class="wrap">
<div class="banner reveal">
<div>
<div class="kicker" style="color:var(--blue)">%(phil_kicker)s</div>
<h2>%(phil_title)s</h2>
%(phil_paras)s
</div>
<div class="stat-row">%(phil_stats)s</div>
</div>
</div>
</section>
<section id="start">
<div class="wrap">
<div class="sec-head reveal">
<div class="kicker">%(start_kicker)s</div>
<h2>%(start_title)s</h2>
<p>%(start_intro)s</p>
</div>
<div class="steps">
<div>%(steps)s</div>
<div class="term reveal">
<div class="code-top">
<span class="tl r"></span><span class="tl y"></span><span class="tl g"></span>
<span class="code-name">%(term_name)s</span>
</div>
<pre>%(term)s</pre>
</div>
</div>
</div>
</section>
<section id="editors" style="padding-top:24px">
<div class="wrap">
<div class="sec-head reveal">
<div class="kicker">%(ed_kicker)s</div>
<h2>%(ed_title)s</h2>
<p>%(ed_intro)s</p>
</div>
<div class="editors reveal">%(eds)s</div>
<p style="margin-top:22px;color:var(--muted);font-size:14.5px">%(ed_note)s</p>
</div>
</section>
<footer>
<div class="wrap foot-in">
<div>
<div class="brand" style="margin-bottom:8px"><span class="logo">L</span> %(brand)s</div>
<div class="muted">%(tagline)s</div>
</div>
<nav class="foot-links">%(footlinks)s</nav>
</div>
</footer>
<script src="ludic-highlight.js"></script>
<script>
Ludic.highlightAll();
const SAMPLES = %(samples)s;
const tabsEl = document.getElementById("tabs");
const panelsEl = document.getElementById("panels");
const noteEl = document.getElementById("note");
SAMPLES.forEach((s, idx)=>{
const t = document.createElement("button");
t.className = "tab" + (idx===0 ? " active" : "");
t.textContent = s.label;
t.onclick = ()=>select(idx);
tabsEl.appendChild(t);
const card = document.createElement("div");
card.className = "code-card panel-code" + (idx===0 ? " active" : "");
card.innerHTML =
'<div class="code-top"><span class="tl r"></span><span class="tl y"></span><span class="tl g"></span><span class="code-name">'
+ s.name + '</span></div><pre>' + Ludic.highlight(s.code) + '</pre>';
panelsEl.appendChild(card);
});
function select(idx){
[...tabsEl.children].forEach((t,i)=>t.classList.toggle("active", i===idx));
[...panelsEl.children].forEach((p,i)=>p.classList.toggle("active", i===idx));
noteEl.textContent = SAMPLES[idx].note;
}
noteEl.textContent = SAMPLES[0].note;
Ludic.installCards();
const io = new IntersectionObserver((entries)=>{
entries.forEach(e=>{ if(e.isIntersecting){ e.target.classList.add("in"); io.unobserve(e.target); } });
},{threshold:.12});
document.querySelectorAll(".reveal").forEach(el=>io.observe(el));
</script>
</body>
</html>

View file

@ -0,0 +1,139 @@
:root{
--bg:#0a0d18; --bg2:#0d1122; --panel:#12172b; --panel2:#151b32;
--line:#232b47; --line2:#2c3660; --text:#c9d2ea; --head:#f2f5ff; --muted:#8290b4;
--mint:#7cf5c4; --coral:#ff5d73; --violet:#c792ea; --blue:#82aaff; --amber:#f6c177;
--c-bg:#0b0f20; --c-comment:#5b6788; --c-key:#ff7eb6; --c-type:#7cf5c4;
--c-str:#f6c177; --c-num:#a6b8ff; --c-annot:#c792ea; --c-fn:#82aaff; --c-punc:#9aa6cc; --c-arg:#f6c177;
--radius:14px; --max:900px; --hdr:64px;
}
*{box-sizing:border-box}
html{scroll-behavior:smooth}
body{margin:0;background:
radial-gradient(1100px 600px at 82% -8%, rgba(124,245,196,.07), transparent 60%),
var(--bg);color:var(--text);
font-family:"Space Grotesk",system-ui,-apple-system,Segoe UI,Roboto,sans-serif;line-height:1.65;-webkit-font-smoothing:antialiased}
a{color:inherit;text-decoration:none}
code,pre,.mono{font-family:"JetBrains Mono",ui-monospace,SFMono-Regular,Menlo,monospace}
.wrap{max-width:var(--max);margin:0 auto;padding:0 24px}
header.nav{position:sticky;top:0;z-index:50;backdrop-filter:blur(10px);
background:rgba(10,13,24,.82);border-bottom:1px solid var(--line);height:var(--hdr)}
.nav-in{display:flex;align-items:center;gap:22px;height:var(--hdr)}
.brand{display:flex;align-items:center;gap:10px;font-weight:700;color:var(--head);font-size:18px}
.logo{width:26px;height:26px;border-radius:7px;display:grid;place-items:center;
background:linear-gradient(135deg,var(--mint),#3fd7a6);color:#06231a;font-weight:700;font-size:15px}
.nav-links{display:flex;gap:22px;margin-left:auto;align-items:center}
.nav-links a{color:var(--muted);font-size:14.5px;font-weight:500}
.nav-links a:hover{color:var(--head)}
.nav-cta{border:1px solid var(--line2);padding:8px 15px;border-radius:9px;color:var(--head)!important;background:var(--panel)}
.nav-cta:hover{border-color:var(--mint)}
@media(max-width:760px){.nav-links a:not(.nav-cta){display:none}}
/* code token colors + snippet links */
pre{margin:12px 0 0;padding:16px 18px;overflow:auto;font-size:13.5px;line-height:1.72;tab-size:2;
background:var(--c-bg);border:1px solid var(--line);border-radius:12px}
pre::-webkit-scrollbar{height:8px}
pre::-webkit-scrollbar-thumb{background:var(--line2);border-radius:6px}
.t-com{color:var(--c-comment);font-style:italic}
.t-key{color:var(--c-key)}.t-type{color:var(--c-type)}.t-str{color:var(--c-str)}
.t-num{color:var(--c-num)}.t-annot{color:var(--c-annot)}.t-fn{color:var(--c-fn)}
.t-punc{color:var(--c-punc)}.t-arg{color:var(--c-arg)}
a.tok{border-radius:3px;transition:background .12s,outline-color .12s}
a.tok:hover{background:rgba(124,245,196,.15);outline:1px solid rgba(124,245,196,.4)}
/* ---- item page ---- */
main.item{padding:30px 24px 90px;max-width:var(--max)}
.crumbs{font-size:13px;color:var(--muted);margin-bottom:20px}
.crumbs a:hover{color:var(--mint)}
.crumbs span{opacity:.6;margin:0 2px}
.crumbs .here{color:var(--text);opacity:1}
.item-head{display:flex;align-items:center;gap:12px;flex-wrap:wrap;scroll-margin-top:calc(var(--hdr) + 20px)}
.item-head h1{margin:0;font-size:clamp(26px,4vw,38px);color:var(--head);letter-spacing:-.5px;
font-family:"JetBrains Mono",monospace;font-weight:700}
.kind-badge{font-size:11px;font-weight:600;letter-spacing:1px;text-transform:uppercase;
padding:4px 9px;border-radius:7px;border:1px solid var(--line2);color:var(--muted);background:var(--panel)}
.kind-keyword{color:var(--c-key);border-color:rgba(255,126,182,.4)}
.kind-type{color:var(--c-type);border-color:rgba(124,245,196,.4)}
.kind-phase{color:var(--blue);border-color:rgba(130,170,255,.4)}
.kind-method,.kind-builtin{color:var(--c-fn);border-color:rgba(130,170,255,.4)}
.kind-annotation{color:var(--c-annot);border-color:rgba(199,146,234,.4)}
.kind-namespace{color:var(--amber);border-color:rgba(246,193,119,.4)}
.kind-operator{color:var(--muted)}
.sig{display:inline-block;margin:18px 0 4px;color:var(--c-fn);background:var(--c-bg);
border:1px solid var(--line);border-radius:9px;padding:9px 13px;font-size:14px}
.desc{margin-top:14px}
.desc p{margin:0 0 12px;font-size:16px;color:var(--text);max-width:720px}
.desc code{color:var(--amber);background:var(--panel);padding:1px 5px;border-radius:5px;font-size:13px}
.desc b{color:var(--head)}
.params,.examples,.related{margin-top:30px}
.params h2,.examples h2,.related h2{font-size:15px;text-transform:uppercase;letter-spacing:1.5px;
color:var(--muted);font-weight:600;margin:0 0 12px}
.param{display:flex;gap:14px;align-items:baseline;padding:10px 12px;border:1px solid var(--line);
border-radius:10px;background:var(--panel);margin-bottom:8px;scroll-margin-top:calc(var(--hdr) + 20px)}
.param .pname{color:var(--c-arg);font-size:13.5px;min-width:110px;flex:none}
.param .pdesc{color:var(--text);font-size:14.5px}
.param code{color:var(--amber);background:var(--c-bg);padding:1px 5px;border-radius:5px;font-size:12.5px}
.rel-row{display:flex;flex-wrap:wrap;gap:10px}
a.rel{font-family:"JetBrains Mono",monospace;font-size:13px;color:var(--text);background:var(--panel);
border:1px solid var(--line);border-radius:9px;padding:7px 12px}
a.rel:hover{border-color:var(--mint);color:var(--mint)}
a.back{display:inline-block;margin-top:34px;color:var(--muted);font-size:14px}
a.back:hover{color:var(--mint)}
/* namespace overview */
.ns-blurb{color:var(--muted);font-size:16px;max-width:720px;margin:14px 0 22px}
.ns-blurb code{color:var(--mint);background:rgba(124,245,196,.08);padding:1px 5px;border-radius:5px;font-size:13px}
.ns-methods{display:flex;flex-direction:column;gap:8px}
a.ns-method{display:flex;flex-direction:column;gap:4px;padding:12px 14px;border:1px solid var(--line);
border-radius:11px;background:var(--panel);transition:border-color .14s,transform .14s}
a.ns-method:hover{border-color:var(--mint);transform:translateX(2px)}
.nm-sig{color:var(--c-fn);font-size:13.5px}
.nm-tip{color:var(--muted);font-size:13.5px}
/* swatches (Color page) */
.swatch-group{margin-bottom:22px}
.swatch-group h3{margin:0 0 12px;font-size:13px;letter-spacing:1.5px;text-transform:uppercase;color:var(--muted)}
.swatch-row{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:10px}
.swatch{display:flex;align-items:center;gap:10px;background:var(--panel);border:1px solid var(--line);
border-radius:9px;padding:8px 10px;scroll-margin-top:calc(var(--hdr) + 20px)}
.chip{width:24px;height:24px;border-radius:6px;flex:none;box-shadow:inset 0 0 0 1px rgba(255,255,255,.12)}
.cname{font-family:"JetBrains Mono",monospace;font-size:12px;color:var(--head);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.chex{margin-left:auto;font-family:"JetBrains Mono",monospace;font-size:11px;color:var(--muted)}
/* ---- api index + search ---- */
main.ref{padding:34px 24px 90px}
.ref-intro{margin-bottom:30px}
.ref-intro .kicker{font-size:13px;font-weight:600;letter-spacing:2px;text-transform:uppercase;color:var(--mint);margin-bottom:12px}
.ref-intro h1{font-size:clamp(30px,5vw,46px);margin:0 0 12px;color:var(--head);letter-spacing:-1px}
.ref-intro p{font-size:16px;color:var(--muted);max-width:720px;margin:0 0 20px}
.search{width:100%;max-width:560px;font-family:"JetBrains Mono",monospace;font-size:15px;color:var(--head);
background:var(--panel);border:1px solid var(--line2);border-radius:11px;padding:13px 16px;outline:none}
.search:focus{border-color:var(--mint);box-shadow:0 0 0 3px rgba(124,245,196,.12)}
.noresults{color:var(--muted);margin-top:16px}
.idx-sec{margin-top:40px;scroll-margin-top:calc(var(--hdr) + 20px)}
.idx-sec h2{font-size:22px;color:var(--head);margin:0 0 4px;letter-spacing:-.3px}
.sec-blurb{color:var(--muted);font-size:14.5px;margin:0 0 16px;max-width:720px}
.sec-blurb code{color:var(--mint);background:rgba(124,245,196,.08);padding:1px 5px;border-radius:5px;font-size:12.5px}
.idx-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:10px}
a.idx-item{display:flex;flex-direction:column;gap:3px;padding:11px 13px;border:1px solid var(--line);
border-radius:10px;background:var(--panel);transition:border-color .14s,transform .14s}
a.idx-item:hover{border-color:var(--mint);transform:translateY(-2px)}
a.idx-item code{color:var(--c-fn);font-size:13.5px}
a.idx-item span{color:var(--muted);font-size:13px;line-height:1.5}
/* ---- hover card ---- */
.hovercard{position:fixed;z-index:100;max-width:340px;background:var(--panel2);border:1px solid var(--line2);
border-radius:12px;padding:12px 14px;box-shadow:0 20px 50px -18px rgba(0,0,0,.8);pointer-events:none}
.hc-top{display:flex;align-items:center;gap:9px;margin-bottom:8px}
.hc-name{font-family:"JetBrains Mono",monospace;color:var(--head);font-weight:700;font-size:14px}
.hc-sig{display:block;color:var(--c-fn);background:var(--c-bg);border:1px solid var(--line);border-radius:7px;
padding:6px 9px;font-size:12px;margin-bottom:8px;white-space:pre-wrap}
.hc-tip{color:var(--text);font-size:13.5px;line-height:1.5}
.hc-foot{color:var(--muted);font-size:11.5px;margin-top:9px;letter-spacing:.3px}
/* ---- target flash ---- */
@keyframes ludicflash{0%{background:rgba(124,245,196,.28);box-shadow:0 0 0 3px rgba(124,245,196,.28)}
100%{background:transparent;box-shadow:0 0 0 3px transparent}}
.flash{animation:ludicflash 1.4s ease-out}
.item-head.flash h1{color:var(--mint)}

View file

@ -1,132 +1,186 @@
/* ============================================================================
* ludic-highlight.js — the Ludic syntax highlighter for the docs site.
* ludic-highlight.js — the Ludic syntax highlighter + docs interactions.
*
* GENERATED FILE — do not edit by hand. The symbol tables below (keywords,
* types, phases, namespace methods, builtins, annotations and their one-line
* tips + anchors) are produced by tools/docgen/gen.py from the per-symbol
* source files in docs/language/**. Add a symbol there and it is recognized,
* colored, tipped and linked here automatically — nothing to maintain twice.
* types, phases, namespace methods + their parameter labels, builtins,
* annotations, namespaces, one-line tips, per-item page targets and hover-card
* data) are produced by tools/docgen/gen.py from the per-symbol source files in
* docs/language/**. Add a symbol there and it is recognized, colored, tipped,
* linked and card-previewed here automatically.
*
* Beyond coloring, every token the language defines becomes a link into the API
* Reference (api.html): hover a keyword, a Screen.* call, a named color, a
* builtin or a type and it points at the entry that explains it. Your own
* symbols (functions, entities, fields) stay plain.
* In any code sample: every keyword/type/builtin/annotation links to its own
* page; `Screen.fill_rectangle` links `Screen` → the namespace page and
* `fill_rectangle` → the method page, separately; a named argument like
* `width:` links to that parameter on the method's page; `Color.Charcoal`
* links `Color` and `Charcoal` separately. Hovering any of them shows a summary
* card pulled from the real API data.
* ========================================================================== */
(function (global) {
"use strict";
const SYMBOLS = /*__SYMBOLS__*/{};
const KEYWORDS = SYMBOLS.keywords || {};
const TYPES = SYMBOLS.types || {};
const PHASES = SYMBOLS.phases || {};
const BUILTINS = SYMBOLS.builtins || {};
const NSMETHODS = SYMBOLS.nsmethods || {};
const ANNOTS = SYMBOLS.annotations || {};
const TIPS = SYMBOLS.tips || {};
const NAMESPACES = new Set(SYMBOLS.namespaces || []);
const COLORS_ANCHOR = SYMBOLS.colors_anchor || "colors";
const ANNOT_ANCHOR = SYMBOLS.annotations_anchor || "annotations";
const S = /*__SYMBOLS__*/{};
const KEYWORDS = S.keywords || {}, TYPES = S.types || {}, PHASES = S.phases || {};
const BUILTINS = S.builtins || {}, NSMETHODS = S.nsmethods || {}, ANNOTS = S.annotations || {};
const NAMESPACES = S.namespaces || {}, TIPS = S.tips || {}, CARDS = S.cards || {};
function esc(s) {
return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
function esc(s){ return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); }
const isIdStart = c => /[A-Za-z_]/.test(c);
const isId = c => /[A-Za-z0-9_]/.test(c);
function link(href, tip, inner) {
const t = tip ? ' title="' + esc(tip) + '"' : "";
return '<a class="tok" href="' + href + '"' + t + ">" + inner + "</a>";
function link(href, id, tip, inner){
const t = tip ? ' title="'+esc(tip).replace(/"/g,"&quot;")+'"' : "";
const d = id ? ' data-id="'+id+'"' : "";
return '<a class="tok" href="'+href+'"'+d+t+'>'+inner+'</a>';
}
function highlight(src) {
let out = "", i = 0;
const n = src.length;
while (i < n) {
const c = src[i];
// comment
if (c === "#") {
let j = i; while (j < n && src[j] !== "\n") j++;
out += '<span class="t-com">' + esc(src.slice(i, j)) + "</span>";
i = j; continue;
}
// string / char / interpolation (backtick)
if (c === '"' || c === "'" || c === "`") {
const q = c; let j = i + 1;
while (j < n && src[j] !== q) { if (src[j] === "\\") j++; j++; }
j = Math.min(j + 1, n);
out += '<span class="t-str">' + esc(src.slice(i, j)) + "</span>";
i = j; continue;
}
// annotation @Name
if (c === "@") {
let j = i + 1; while (j < n && isId(src[j])) j++;
const at = src.slice(i, j);
const anchor = ANNOTS[at] || ANNOT_ANCHOR;
const tip = TIPS[at] || "A compile-time annotation.";
out += link("api.html#" + anchor, tip,
'<span class="t-annot">' + esc(at) + "</span>");
i = j; continue;
}
// number (incl 0x hex)
if (/[0-9]/.test(c)) {
let j = i; while (j < n && /[0-9a-fA-FxX._]/.test(src[j])) j++;
out += '<span class="t-num">' + esc(src.slice(i, j)) + "</span>";
i = j; continue;
}
// identifier / keyword / type / namespace.member / builtin
if (isIdStart(c)) {
let j = i; while (j < n && isId(src[j])) j++;
const word = src.slice(i, j);
function highlight(src){
let out = "", i = 0; const n = src.length;
const stack = []; // call-context stack for named-parameter linking
let pending = null; // ctx to push at the next "("
const nextNonSpace = j => { while (j < n && src[j] === " ") j++; return j; };
// Namespace.member (Screen.fill_rectangle, Color.Crimson, …)
if (NAMESPACES.has(word) && src[j] === "." && j + 1 < n && isIdStart(src[j + 1])) {
let k = j + 1; while (k < n && isId(src[k])) k++;
const member = src.slice(j + 1, k);
const key = word + "." + member;
let href, tip;
if (word === "Color") {
href = "api.html#" + COLORS_ANCHOR; tip = "Named color " + key + ".";
while (i < n){
const c = src[i];
if (c === "#"){ let j=i; while(j<n && src[j]!=="\n") j++; out+='<span class="t-com">'+esc(src.slice(i,j))+'</span>'; i=j; continue; }
if (c === '"' || c === "'" || c === "`"){ const q=c; let j=i+1; while(j<n && src[j]!==q){ if(src[j]==="\\") j++; j++; } j=Math.min(j+1,n); out+='<span class="t-str">'+esc(src.slice(i,j))+'</span>'; i=j; continue; }
if (c === "@"){ let j=i+1; while(j<n && isId(src[j])) j++; const at=src.slice(i,j); const id=ANNOTS[at];
if (id) out += link(id+".html", id, TIPS[at]||"A compile-time annotation.", '<span class="t-annot">'+esc(at)+'</span>');
else out += '<span class="t-annot">'+esc(at)+'</span>';
i=j; continue; }
if (/[0-9]/.test(c)){ let j=i; while(j<n && /[0-9a-fA-FxX._]/.test(src[j])) j++; out+='<span class="t-num">'+esc(src.slice(i,j))+'</span>'; i=j; continue; }
if (isIdStart(c)){
let j=i; while(j<n && isId(src[j])) j++; const word=src.slice(i,j);
// Namespace.member — link the two halves separately
if (NAMESPACES[word] && src[j]==="." && j+1<n && isIdStart(src[j+1])){
let k=j+1; while(k<n && isId(src[k])) k++; const member=src.slice(j+1,k);
const nsId=NAMESPACES[word];
out += link(nsId+".html", nsId, TIPS[word]||(word+" namespace"), '<span class="t-type">'+word+'</span>');
out += '<span class="t-punc">.</span>';
if (word === "Color"){
out += link("ns-color.html#"+member.toLowerCase(), "", "Named color "+word+"."+member+".", '<span class="t-fn">'+esc(member)+'</span>');
} else {
href = "api.html#" + (NSMETHODS[key] || (word.toLowerCase() + "-" + member));
tip = TIPS[key] || key;
const key=word+"."+member, m=NSMETHODS[key];
if (m){
out += link(m.id+".html", m.id, TIPS[key]||key, '<span class="t-fn">'+esc(member)+'</span>');
if (src[nextNonSpace(k)]==="(") pending = {page:m.id, params:new Set(m.params||[])};
} else out += '<span class="t-fn">'+esc(member)+'</span>';
}
const inner = '<span class="t-type">' + word + '</span><span class="t-punc">.</span><span class="t-fn">' + esc(member) + "</span>";
out += link(href, tip, inner);
i = k; continue;
i=k; continue;
}
let k2 = j; while (k2 < n && src[k2] === " ") k2++;
const callish = src[k2] === "(";
if (KEYWORDS[word]) {
out += link("api.html#" + KEYWORDS[word], TIPS[word], '<span class="t-key">' + word + "</span>");
} else if (BUILTINS[word] && callish) {
out += link("api.html#" + BUILTINS[word], TIPS[word], '<span class="t-fn">' + word + "</span>");
} else if (TYPES[word]) {
out += link("api.html#" + TYPES[word], TIPS[word] || ("The " + word + " type."), '<span class="t-type">' + word + "</span>");
} else if (PHASES[word]) {
out += link("api.html#" + PHASES[word], "The " + word + " phase.", '<span class="t-type">' + word + "</span>");
} else if (callish) {
out += '<span class="t-fn">' + esc(word) + "</span>";
const ns = nextNonSpace(j);
const callish = src[ns] === "(";
const labelish = src[ns] === ":";
const top = stack.length ? stack[stack.length-1] : null;
if (KEYWORDS[word]){
out += link(KEYWORDS[word]+".html", KEYWORDS[word], TIPS[word], '<span class="t-key">'+word+'</span>');
} else if (BUILTINS[word] && callish){
const b=BUILTINS[word];
out += link(b.id+".html", b.id, TIPS[word], '<span class="t-fn">'+word+'</span>');
pending = {page:b.id, params:new Set(b.params||[])};
} else if (labelish && top && top.params.has(word)){
out += link(top.page+".html#param-"+word, "", "parameter: "+word, '<span class="t-arg">'+word+'</span>');
} else if (TYPES[word]){
out += link(TYPES[word]+".html", TYPES[word], TIPS[word]||("The "+word+" type."), '<span class="t-type">'+word+'</span>');
} else if (PHASES[word]){
out += link(PHASES[word]+".html", PHASES[word], TIPS[word]||("The "+word+" phase."), '<span class="t-type">'+word+'</span>');
} else if (callish){
out += '<span class="t-fn">'+esc(word)+'</span>';
} else {
out += esc(word);
}
i = j; continue;
}
// punctuation
if (/[{}\[\]()=<>+\-*\/%,.:;!&|~]/.test(c)) {
out += '<span class="t-punc">' + esc(c) + "</span>";
i++; continue;
i=j; continue;
}
if (c === "("){ stack.push(pending); pending=null; out+='<span class="t-punc">(</span>'; i++; continue; }
if (c === ")"){ stack.pop(); out+='<span class="t-punc">)</span>'; i++; continue; }
if (/[{}\[\]=<>+\-*\/%,.:;!&|~]/.test(c)){ out+='<span class="t-punc">'+esc(c)+'</span>'; i++; continue; }
out += esc(c); i++;
}
return out;
}
function highlightAll() {
document.querySelectorAll('pre[data-lang="ludic"]').forEach(pre => {
pre.innerHTML = highlight(pre.textContent);
});
function highlightAll(){
document.querySelectorAll('pre[data-lang="ludic"]').forEach(pre => { pre.innerHTML = highlight(pre.textContent); });
}
global.Ludic = { highlight, highlightAll, SYMBOLS };
/* ---- hover cards ------------------------------------------------------- */
let cardEl = null, cardTimer = null;
function ensureCard(){
if (cardEl) return cardEl;
cardEl = document.createElement("div"); cardEl.className = "hovercard"; cardEl.hidden = true;
document.body.appendChild(cardEl); return cardEl;
}
function showCard(a){
const id = a.getAttribute("data-id"); if (!id) return;
const c = CARDS[id]; if (!c) return;
const el = ensureCard();
el.innerHTML = '<div class="hc-top"><span class="kind-badge kind-'+(c.kind||"").replace("namespace-method","method")+'">'
+ (c.kind||"").replace("namespace-method","method") + '</span><span class="hc-name">'+esc(c.name||"")+'</span></div>'
+ (c.sig ? '<code class="hc-sig">'+esc(c.sig)+'</code>' : "")
+ '<div class="hc-tip">'+esc(c.tip||"")+'</div>'
+ '<div class="hc-foot">'+esc(c.section||"")+' · click to open</div>';
el.hidden = false;
const r = a.getBoundingClientRect();
const cw = el.offsetWidth, ch = el.offsetHeight;
let left = r.left, top = r.bottom + 8;
if (left + cw > window.innerWidth - 12) left = window.innerWidth - cw - 12;
if (left < 12) left = 12;
if (top + ch > window.innerHeight - 12) top = r.top - ch - 8;
el.style.left = Math.max(12,left) + "px"; el.style.top = Math.max(12,top) + "px";
}
function hideCard(){ if (cardEl) cardEl.hidden = true; }
function installCards(){
document.addEventListener("mouseover", e => {
const a = e.target.closest && e.target.closest("a.tok[data-id]");
if (!a) return;
clearTimeout(cardTimer); cardTimer = setTimeout(()=>showCard(a), 130);
});
document.addEventListener("mouseout", e => {
const a = e.target.closest && e.target.closest("a.tok[data-id]");
if (a){ clearTimeout(cardTimer); hideCard(); }
});
window.addEventListener("scroll", hideCard, {passive:true});
}
/* ---- flash the scrolled-to target ------------------------------------- */
function flash(el){ if (!el) return; el.classList.remove("flash"); void el.offsetWidth; el.classList.add("flash"); }
function flashTarget(){
const go = () => {
const h = location.hash ? decodeURIComponent(location.hash.slice(1)) : "";
let el = h ? document.getElementById(h) : null;
if (!el) el = document.querySelector(".item-head") || document.getElementById("top");
flash(el);
};
if (document.readyState !== "loading") go(); else document.addEventListener("DOMContentLoaded", go);
window.addEventListener("hashchange", () => { const el = document.getElementById(decodeURIComponent(location.hash.slice(1))); flash(el); });
}
/* ---- fuzzy search on the API index ------------------------------------ */
function subseq(q, s){ let i=0; for (let k=0;k<s.length && i<q.length;k++) if (s[k]===q[i]) i++; return i===q.length; }
function installSearch(){
const box = document.getElementById("search"); if (!box) return;
const items = [...document.querySelectorAll(".idx-item")];
const secs = [...document.querySelectorAll(".idx-sec")];
const none = document.getElementById("noresults");
const run = () => {
const q = box.value.trim().toLowerCase();
let shown = 0;
items.forEach(it => {
const name = (it.getAttribute("data-name")||"").toLowerCase();
const tip = (it.getAttribute("data-tip")||"").toLowerCase();
const hit = !q || name.includes(q) || tip.includes(q) || subseq(q, name);
it.style.display = hit ? "" : "none"; if (hit) shown++;
});
secs.forEach(sec => { const any = [...sec.querySelectorAll(".idx-item")].some(i=>i.style.display!=="none"); sec.style.display = any ? "" : "none"; });
if (none) none.hidden = shown !== 0;
};
box.addEventListener("input", run);
box.addEventListener("keydown", e => { if (e.key === "Enter"){ const first = items.find(i=>i.style.display!=="none"); if (first) location.href = first.getAttribute("href"); } });
}
global.Ludic = { highlight, highlightAll, installCards, flashTarget, installSearch, SYMBOLS: S };
})(window);

View file

@ -192,3 +192,18 @@
.reveal{opacity:0;transform:translateY(16px);transition:opacity .6s ease, transform .6s ease}
.reveal.in{opacity:1;transform:none}
/* hover-card + named-arg token (shared with the reference) */
.t-arg{color:var(--amber)}
.hovercard{position:fixed;z-index:100;max-width:340px;background:var(--panel2);border:1px solid var(--line2);
border-radius:12px;padding:12px 14px;box-shadow:0 20px 50px -18px rgba(0,0,0,.8);pointer-events:none}
.hc-top{display:flex;align-items:center;gap:9px;margin-bottom:8px}
.hc-name{font-family:"JetBrains Mono",monospace;color:var(--head);font-weight:700;font-size:14px}
.hc-sig{display:block;color:var(--c-fn);background:var(--c-bg);border:1px solid var(--line);border-radius:7px;
padding:6px 9px;font-size:12px;margin-bottom:8px;white-space:pre-wrap}
.hc-tip{color:var(--text);font-size:13.5px;line-height:1.5}
.hc-foot{color:var(--muted);font-size:11.5px;margin-top:9px;letter-spacing:.3px}
.kind-badge{font-size:11px;font-weight:600;letter-spacing:1px;text-transform:uppercase;padding:3px 7px;
border-radius:6px;border:1px solid var(--line2);color:var(--muted);background:var(--panel)}
.kind-keyword{color:var(--c-key)}.kind-type{color:var(--c-type)}.kind-phase{color:var(--blue)}
.kind-method,.kind-builtin{color:var(--c-fn)}.kind-annotation{color:var(--c-annot)}.kind-namespace{color:var(--amber)}

View file

@ -1,41 +1,116 @@
#!/usr/bin/env python3
"""check.py — sanity-check a generated docs site before it is published.
"""check.py — coverage + integrity guard for the generated docs site.
Verifies:
* the pages-server contract: index.html + .nojekyll exist at the root;
* api.html and ludic-highlight.js are present;
* every anchor the highlighter links to actually exists in api.html
(so no code-snippet token points at a missing entry).
Fails (exit 1) if:
* the pages contract is broken (index.html / api.html / .nojekyll missing);
* any symbol in tools/docgen/inventory.json lacks a source file AND a page;
* any per-symbol source file still carries only its one-line seed (i.e. was
scaffolded but never written up) — so "every symbol is really documented";
* a highlighter link target (page) does not exist in the output.
Usage: python3 tools/docgen/check.py <site-dir>
Exit code 1 on any failure.
Usage: python3 tools/docgen/check.py [site-dir] (default build/pages)
"""
import json, os, re, sys
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
LANG = os.path.join(ROOT, "docs", "language")
DOCGEN = os.path.join(ROOT, "tools", "docgen")
def parse_front(path):
t = open(path, encoding="utf-8").read()
meta = {}
if t.startswith("---"):
end = t.find("\n---", 3)
if end != -1:
for line in t[3:end].strip("\n").split("\n"):
if line.strip() and ":" in line:
k, v = line.split(":", 1); meta[k.strip()] = v.strip()
body = t[end+4:].strip()
else:
body = t
else:
body = t
return meta, body
def main(site):
problems = []
need = ["index.html", "api.html", "ludic-highlight.js", ".nojekyll", "symbols.json"]
for f in need:
problems, warnings = [], []
# 1) pages contract
for f in ("index.html", "api.html", ".nojekyll"):
if not os.path.exists(os.path.join(site, f)):
problems.append(f"missing required file: {f}")
if os.path.exists(os.path.join(site, "symbols.json")) and os.path.exists(os.path.join(site, "api.html")):
sym = json.load(open(os.path.join(site, "symbols.json")))
ids = set(re.findall(r'id="([^"]+)"', open(os.path.join(site, "api.html")).read()))
anchors = set()
for grp in ("keywords", "types", "phases", "builtins", "nsmethods", "annotations"):
anchors |= set(sym.get(grp, {}).values())
anchors.add(sym.get("colors_anchor", "colors"))
anchors.add(sym.get("annotations_anchor", "annotations"))
for a in sorted(anchors):
if a not in ids:
problems.append(f"highlighter links to #{a} but api.html has no such anchor")
problems.append("missing required file: " + f)
# 2) coverage against the authoritative inventory
inv = json.load(open(os.path.join(DOCGEN, "inventory.json")))
# map id -> source path
id2src = {}
thin = []
for cat in sorted(os.listdir(LANG)):
cdir = os.path.join(LANG, cat)
if not os.path.isdir(cdir):
continue
for fn in os.listdir(cdir):
if not fn.endswith(".md") or fn == "_section.md":
continue
meta, body = parse_front(os.path.join(cdir, fn))
sid = meta.get("id", fn[:-3]); id2src[sid] = os.path.join(cdir, fn)
# a "thin" file = body (minus a Parameters block and its tip line) too short
tipline = meta.get("tip", "")
btext = re.sub(r"(?is)parameters:.*", "", body).strip()
btext = btext.replace(tipline, "").strip()
if len(btext) < 40:
thin.append(sid)
for cat, ids in inv.items():
for sid in ids:
if sid not in id2src:
problems.append("no source file for inventory symbol: %s (%s)" % (sid, cat))
elif site and not os.path.exists(os.path.join(site, sid + ".html")):
problems.append("no generated page for symbol: %s.html" % sid)
# 2b) duplicate token → symbol conflicts (same token documented on two pages)
tok2ids = {}
for cat in sorted(os.listdir(LANG)):
cdir = os.path.join(LANG, cat)
if not os.path.isdir(cdir):
continue
for fn in os.listdir(cdir):
if not fn.endswith(".md") or fn == "_section.md":
continue
meta, _ = parse_front(os.path.join(cdir, fn))
for tok in meta.get("tokens", "").split():
tok2ids.setdefault((meta.get("kind",""), tok), set()).add(meta.get("id",""))
for (kind, tok), ids in sorted(tok2ids.items()):
if len(ids) > 1:
problems.append("token %r (%s) documented on multiple pages: %s" % (tok, kind, ", ".join(sorted(ids))))
# 3) thin (un-expanded) symbols — warn, not fail (lets infra land before prose)
if thin:
warnings.append("%d symbols still have only seed text: %s%s"
% (len(thin), ", ".join(sorted(thin)[:12]), " …" if len(thin) > 12 else ""))
# 4) highlighter targets exist
sj = os.path.join(site, "symbols.json")
if os.path.exists(sj):
h = json.load(open(sj))["highlight"]
targets = set()
for grp in ("keywords", "types", "phases", "annotations"):
targets |= set(h.get(grp, {}).values())
for grp in ("builtins", "nsmethods"):
targets |= set(v["id"] for v in h.get(grp, {}).values())
targets |= set(h.get("namespaces", {}).values())
for tgt in sorted(targets):
if not os.path.exists(os.path.join(site, tgt + ".html")):
problems.append("highlighter links to %s.html but it was not generated" % tgt)
for w in warnings:
print(" warning:", w)
if problems:
print("docs check FAILED:")
for p in problems:
print(" -", p)
return 1
print("docs check OK:", site)
print("docs check OK: %s (%d symbols documented)" % (site, len(id2src)))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else "build/pages"))
sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else os.path.join(ROOT, "build", "pages")))

View file

@ -1,78 +1,87 @@
#!/usr/bin/env python3
"""gen.py — the Ludic documentation generator.
"""gen.py — the Ludic documentation generator (v2).
Single source of truth:
docs/language/<category>/<id>.md one file per keyword / type / builtin /
namespace method / operator / annotation
docs/language/<category>/_section.md section title + blurb + order
docs/language/colors/palette.json the named-color palette (from palette.py)
docs/site/site.json landing-page messaging (hero, features, …)
docs/site/snippets/*.ludic the code snippets shown on the landing page
docs/language/<category>/<id>.md one file per symbol (front-matter + body)
docs/language/<category>/_section.md section title/blurb/order
docs/language/colors/palette.json the named-color palette
docs/site/site.json landing-page messaging
docs/site/snippets/*.ludic real programs shown on the landing page
Outputs (into --out, default build/pages) — the whole pages-branch payload:
api.html the full API Reference, one entry per symbol
index.html the landing page (hero + showcase from real .ludic files)
ludic-highlight.js the highlighter, its symbol tables generated from the above
symbols.json the machine-readable symbol index (also useful to editors)
index.html the landing page
api.html the reference index, with fuzzy search
<id>.html ONE page per symbol (kw-handler.html, screen-clear.html…)
ns-<name>.html one overview page per namespace (Screen/Color/Input/…)
ludic-highlight.js the highlighter — its symbol tables, tips, per-item link
targets, per-parameter anchors and hover-card data all
generated from the sources above
symbols.json the machine-readable index (drives search + hover cards)
.nojekyll
Nothing here is hand-maintained twice: add a symbol file and it appears in the
reference, is recognized + tipped + linked in every snippet, and lands in
symbols.json — automatically. Zero third-party dependencies (stdlib only).
Every keyword/type/phase/builtin/namespace-method/annotation/operator/color is
addressable by its own page; named parameters and named colors are addressable
by anchor. Python standard library only.
"""
import json, os, html, re, sys, argparse
import json, os, html, re, argparse
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
ASSETS = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets")
LANG = os.path.join(ROOT, "docs", "language")
SITE = os.path.join(ROOT, "docs", "site")
HEADER_OFFSET = 84 # sticky nav height; used for scroll-margin
def esc(s): return html.escape(s, quote=False)
def esc(s): return html.escape(s or "", quote=False)
def escattr(s): return html.escape(s or "", quote=True)
def fill(tmpl, mapping):
"""Placeholder substitution that never collides with % or { } in CSS/JS."""
for k, v in mapping.items():
tmpl = tmpl.replace("@@" + k + "@@", str(v))
return tmpl
def pct(tmpl, mapping):
"""Substitute only %(name)s markers; leave bare % (CSS 100%, code % 2) alone.
Replacement values are inserted literally and never re-scanned."""
return re.sub(r"%\((\w+)\)s", lambda m: mapping[m.group(1)], tmpl)
# ---------------------------------------------------------------------------
# parsing
# ---------------------------------------------------------------------------
FENCE = re.compile(r"```ludic\n(.*?)\n```", re.S)
PARAM = re.compile(r"^-\s*`?(\w+)`?\s*[—-]+\s*(.*)$")
# ---------------------------------------------------------------------------
# front-matter + body parsing (no yaml dependency)
# ---------------------------------------------------------------------------
def parse_doc(path):
text = open(path, encoding="utf-8").read()
meta, body = {}, text
if text.startswith("---"):
end = text.find("\n---", 3)
if end != -1:
fm = text[3:end].strip("\n")
for line in text[3:end].strip("\n").split("\n"):
if line.strip() and ":" in line:
k, v = line.split(":", 1)
meta[k.strip()] = v.strip()
body = text[end + 4:].lstrip("\n")
for line in fm.split("\n"):
if not line.strip() or ":" not in line:
continue
k, v = line.split(":", 1)
meta[k.strip()] = v.strip()
return meta, body
FENCE = re.compile(r"```ludic\n(.*?)\n```", re.S)
def codeify(s):
return re.sub(r"`([^`]+)`", r"<code>\1</code>", s)
def split_body(body):
"""Return (description_html, [examples]) — fences pulled out as examples."""
examples = FENCE.findall(body)
desc = FENCE.sub("", body).strip()
# author convenience: `code` -> <code>code</code> (leaves existing tags alone)
desc = re.sub(r"`([^`]+)`", r"<code>\1</code>", desc)
paras = [p.strip() for p in re.split(r"\n\s*\n", desc) if p.strip()]
desc_html = "</p><p>".join(paras)
return desc_html, examples
body = FENCE.sub("", body)
# pull out a "Parameters:" block
params, keep = [], []
lines = body.split("\n")
i, n = 0, len(lines)
while i < n:
if lines[i].strip().lower().startswith("parameters:"):
i += 1
while i < n and lines[i].strip():
m = PARAM.match(lines[i].strip())
if m:
params.append({"name": m.group(1), "desc": codeify(m.group(2).strip())})
i += 1
else:
keep.append(lines[i]); i += 1
desc = "\n".join(keep).strip()
paras = [codeify(p.strip()) for p in re.split(r"\n\s*\n", desc) if p.strip()]
return "</p><p>".join(paras), examples, params
# ---------------------------------------------------------------------------
# load the symbol model
# ---------------------------------------------------------------------------
def load_sections():
sections = []
for cat in sorted(os.listdir(LANG)):
@ -80,416 +89,304 @@ def load_sections():
if not os.path.isdir(cdir):
continue
smeta, sblurb = {}, ""
secpath = os.path.join(cdir, "_section.md")
if os.path.exists(secpath):
smeta, sbody = parse_doc(secpath)
sblurb = re.sub(r"`([^`]+)`", r"<code>\1</code>", sbody.strip())
sp = os.path.join(cdir, "_section.md")
if os.path.exists(sp):
smeta, sbody = parse_doc(sp)
sblurb = codeify(sbody.strip())
entries = []
for fn in os.listdir(cdir):
for fn in sorted(os.listdir(cdir)):
if not fn.endswith(".md") or fn == "_section.md":
continue
meta, body = parse_doc(os.path.join(cdir, fn))
desc, examples = split_body(body)
desc, examples, params = split_body(body)
meta["desc_html"] = desc
meta["examples"] = examples
meta["tokens_list"] = meta.get("tokens", "").split() if meta.get("tokens") else []
meta["params"] = params
meta["tokens_list"] = meta.get("tokens", "").split()
meta["related_list"] = meta.get("related", "").split()
entries.append(meta)
entries.sort(key=lambda e: (int(e.get("order", 999)), e.get("name", "")))
sections.append({
"id": smeta.get("id", cat),
"title": smeta.get("title", cat.title()),
"order": int(smeta.get("order", 999)),
"blurb": sblurb,
"entries": entries,
})
sections.append({"id": smeta.get("id", cat), "title": smeta.get("title", cat.title()),
"order": int(smeta.get("order", 999)), "blurb": sblurb,
"cat": cat, "entries": entries})
sections.sort(key=lambda s: (s["order"], s["title"]))
return sections
# ---------------------------------------------------------------------------
# build the highlighter symbol tables from the model
# symbol model for the highlighter + search + cards
# ---------------------------------------------------------------------------
def build_symbols(sections):
def ns_page(nsname): return "ns-" + nsname.lower()
def build_symbols(sections, palette):
sym = {"keywords": {}, "types": {}, "phases": {}, "builtins": {},
"nsmethods": {}, "annotations": {}, "tips": {},
"namespaces": [], "colors_anchor": "colors", "annotations_anchor": "annotations"}
namespaces = set()
"nsmethods": {}, "annotations": {}, "namespaces": {}, "tips": {},
"cards": {}, "colors_page": "ns-color"}
items = {} # id -> full record for search
for s in sections:
for e in s["entries"]:
kind = e.get("kind", "")
anchor = e["id"]
tip = e.get("tip", "")
eid = e["id"]; kind = e.get("kind", ""); tip = e.get("tip", "")
page = eid + ".html"
items[eid] = {"id": eid, "name": e.get("name", ""), "sig": e.get("sig", ""),
"kind": kind, "category": s["id"], "section": s["title"],
"tip": tip, "page": page}
sym["cards"][eid] = {"name": e.get("name",""), "sig": e.get("sig",""),
"tip": tip, "kind": kind, "page": page, "section": s["title"]}
for tok in e["tokens_list"]:
if kind == "keyword":
sym["keywords"][tok] = anchor
elif kind == "type":
sym["types"][tok] = anchor
elif kind == "phase":
sym["phases"][tok] = anchor
if kind == "keyword": sym["keywords"][tok] = eid
elif kind == "type": sym["types"][tok] = eid
elif kind == "phase": sym["phases"][tok] = eid
elif kind == "builtin":
sym["builtins"][tok] = anchor
sym["builtins"][tok] = {"id": eid, "params": [p["name"] for p in e["params"]]}
elif kind == "namespace-method":
sym["nsmethods"][tok] = anchor
if "." in tok:
namespaces.add(tok.split(".", 1)[0])
sym["nsmethods"][tok] = {"id": eid, "params": [p["name"] for p in e["params"]]}
elif kind == "annotation":
sym["annotations"][tok] = anchor
if tip:
sym["tips"][tok] = tip
if s["id"] == "colors":
sym["colors_anchor"] = "colors"
if s["id"] == "annotations":
sym["annotations_anchor"] = "annotations"
namespaces.add("Color") # Color.* is recognized and linked to the palette
sym["namespaces"] = sorted(namespaces)
return sym
sym["annotations"][tok] = eid
if tip: sym["tips"][tok] = tip
# namespaces: Screen/Input/Random/Map from ns methods, plus Color
nsnames = set()
for tok in sym["nsmethods"]:
if "." in tok: nsnames.add(tok.split(".", 1)[0])
nsnames.add("Color")
for nn in sorted(nsnames):
sym["namespaces"][nn] = ns_page(nn)
sym["cards"][ns_page(nn)] = {"name": nn, "sig": nn + ".*", "kind": "namespace",
"tip": NS_TIP.get(nn, ""), "page": ns_page(nn) + ".html",
"section": "Namespaces"}
return sym, items
NS_TIP = {"Screen": "The 2D drawing surface.", "Color": "The named color palette.",
"Input": "Reading the keyboard.", "Random": "The seeded, deterministic RNG.",
"Map": "The character-grid tilemap."}
# ---------------------------------------------------------------------------
# render the API Reference
# shared chrome
# ---------------------------------------------------------------------------
def render_entry(e):
ex = ""
for code in e.get("examples", []):
ex += '<pre data-lang="ludic" class="ex">' + esc(code) + "</pre>"
desc = e.get("desc_html", "")
return (
'<div class="entry" id="{id}">'
'<div class="entry-head"><h3>{name}</h3><a class="anchor" href="#{id}">#</a></div>'
'<code class="sig">{sig}</code>'
'<p>{desc}</p>{ex}</div>'
).format(id=e["id"], name=esc(e.get("name", "")), sig=esc(e.get("sig", "")),
desc=desc, ex=ex)
def nav_html(cfg, active=None):
out = []
for n in cfg["nav_links"]:
cls = 'class="nav-cta" ' if n.get("href") == "api.html" else ""
out.append('<a %shref="%s">%s</a>' % (cls, n["href"], esc(n["label"])))
return "".join(out)
def render_palette(palette):
out = ['<div class="swatches">']
for grp in palette["groups"]:
out.append('<div class="swatch-group"><h4>' + esc(grp["name"]) + '</h4><div class="swatch-row">')
for col in grp["colors"]:
h = col["hex"]
out.append(
'<div class="swatch"><span class="chip" style="background:#{h}"></span>'
'<span class="cname">Color.{n}</span><span class="chex">#{h}</span></div>'
.format(h=h, n=esc(col["name"])))
out.append("</div></div>")
out.append("</div>")
return "\n".join(out)
def render_section(s, palette):
if s["id"] == "colors":
body = render_palette(palette)
else:
body = "\n".join(render_entry(e) for e in s["entries"])
return ('<section class="ref-sec" id="{id}"><h2>{title}</h2>'
'<p class="sec-blurb">{blurb}</p>{body}</section>').format(
id=s["id"], title=esc(s["title"]), blurb=s["blurb"], body=body)
def render_api(sections, palette, cfg):
css = open(os.path.join(ASSETS, "api.css")).read()
nav = '<nav class="side">' + "".join(
'<a href="#{i}">{t}</a>'.format(i=s["id"], t=esc(s["title"])) for s in sections) + "</nav>"
content = "\n".join(render_section(s, palette) for s in sections)
navlinks = "".join(
'<a {cls}href="{h}">{l}</a>'.format(
h=n["href"], l=esc(n["label"]),
cls='class="nav-cta" ' if n.get("href") == "api.html" else "")
for n in cfg["nav_links"])
tmpl = """<!doctype html>
def head_html(title, desc, css_file):
css = open(os.path.join(ASSETS, css_file)).read()
return fill("""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ludic — API Reference</title>
<meta name="description" content="The complete Ludic API Reference: every keyword, type, builtin, the Screen/Color/Input/Random/Map namespaces, and the full named-color palette.">
<title>@@TITLE@@</title>
<meta name="description" content="@@DESC@@">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet">
<style>
@@CSS@@
</style>
</head>
<body>
<header class="nav">
<div class="wrap nav-in">
<a class="brand" href="index.html"><span class="logo">L</span> @@BRAND@@</a>
<nav class="nav-links">@@NAVLINKS@@</nav>
</div>
</header>
<div class="wrap ref-layout">
@@NAV@@
<main class="ref-main">
<div class="ref-intro">
<div class="kicker">Reference</div>
<h1>API Reference</h1>
<p>Every keyword, type, builtin, namespace and color in Ludic. In any code sample across this site, hover a token and click to jump straight to its entry here.</p>
</div>
@@CONTENT@@
</main>
</div>
<script src="ludic-highlight.js"></script>
<script>
Ludic.highlightAll();
const secs = [...document.querySelectorAll('.ref-sec')];
const navlinks = [...document.querySelectorAll('.side a')];
const spy = new IntersectionObserver((entries)=>{
entries.forEach(e=>{ if(e.isIntersecting){
navlinks.forEach(a=>a.classList.toggle('active', a.getAttribute('href')==='#'+e.target.id));
}});
},{rootMargin:'-10% 0px -80% 0px'});
secs.forEach(s=>spy.observe(s));
</script>
</body>
</html>
"""
return fill(tmpl, dict(CSS=css, BRAND=esc(cfg["brand"]), NAVLINKS=navlinks, NAV=nav, CONTENT=content))
</head>""", {"TITLE": esc(title), "DESC": escattr(desc), "CSS": css})
def topbar(cfg):
return ('<header class="nav"><div class="wrap nav-in">'
'<a class="brand" href="index.html"><span class="logo">L</span> %s</a>'
'<nav class="nav-links">%s</nav></div></header>') % (esc(cfg["brand"]), nav_html(cfg))
# ---------------------------------------------------------------------------
# render the landing page
# per-item page
# ---------------------------------------------------------------------------
def read_snippet(rel):
return open(os.path.join(ROOT, rel), encoding="utf-8").read().rstrip("\n")
def render_params(e):
if not e["params"]:
return ""
rows = "".join(
'<div class="param" id="param-%s"><code class="pname">%s</code>'
'<span class="pdesc">%s</span></div>' % (p["name"], esc(p["name"]), p["desc"])
for p in e["params"])
return '<div class="params"><h2>Parameters</h2>%s</div>' % rows
def render_examples(e):
if not e["examples"]:
return ""
blocks = "".join('<pre data-lang="ludic">%s</pre>' % esc(code) for code in e["examples"])
return '<div class="examples"><h2>Example</h2>%s</div>' % blocks
def render_related(e, items):
rel = [r for r in e["related_list"] if r in items]
if not rel:
return ""
links = "".join('<a class="rel" href="%s.html">%s</a>' % (r, esc(items[r]["name"])) for r in rel)
return '<div class="related"><h2>Related</h2><div class="rel-row">%s</div></div>' % links
def item_page(e, section, cfg, items):
kindlabel = {"namespace-method": "method", "builtin": "function"}.get(e.get("kind",""), e.get("kind",""))
body = fill("""@@TOPBAR@@
<main class="wrap item">
<div class="crumbs"><a href="api.html">API Reference</a> <span>›</span> <a href="@@SECHREF@@">@@SECTION@@</a> <span>›</span> <span class="here">@@NAME@@</span></div>
<div class="item-head">
<span class="kind-badge kind-@@KIND@@">@@KINDLABEL@@</span>
<h1 id="top">@@NAME@@</h1>
</div>
<code class="sig">@@SIG@@</code>
<div class="desc"><p>@@DESC@@</p></div>
@@PARAMS@@
@@EXAMPLES@@
@@RELATED@@
<a class="back" href="api.html">← All symbols</a>
</main>
<script src="ludic-highlight.js"></script>
<script>Ludic.highlightAll(); Ludic.installCards(); Ludic.flashTarget();</script>
</body></html>""", {
"TOPBAR": topbar(cfg),
"SECHREF": "ns-" + section["cat"] + ".html" if section["cat"] in ("screen","input","random","map") else "api.html#" + section["id"],
"SECTION": esc(section["title"]),
"NAME": esc(e.get("name","")),
"KIND": e.get("kind","").replace("namespace-method","method"),
"KINDLABEL": esc(kindlabel),
"SIG": esc(e.get("sig","")),
"DESC": e.get("desc_html","") or esc(e.get("tip","")),
"PARAMS": render_params(e),
"EXAMPLES": render_examples(e),
"RELATED": render_related(e, items),
})
return head_html(e.get("name","") + " — Ludic", e.get("tip",""), "item.css") + "\n<body>\n" + body
# ---------------------------------------------------------------------------
# namespace overview pages
# ---------------------------------------------------------------------------
def ns_overview_page(nsname, section, cfg):
rows = ""
for e in section["entries"]:
rows += ('<a class="ns-method" href="%s.html"><code class="nm-sig">%s</code>'
'<span class="nm-tip">%s</span></a>') % (e["id"], esc(e.get("sig","")), esc(e.get("tip","")))
body = fill("""@@TOPBAR@@
<main class="wrap item">
<div class="crumbs"><a href="api.html">API Reference</a> <span>›</span> <span class="here">@@NAME@@</span></div>
<div class="item-head"><span class="kind-badge kind-namespace">namespace</span><h1 id="top">@@NAME@@</h1></div>
<p class="ns-blurb">@@BLURB@@</p>
<div class="ns-methods">@@ROWS@@</div>
<a class="back" href="api.html">← All symbols</a>
</main>
<script src="ludic-highlight.js"></script>
<script>Ludic.installCards(); Ludic.flashTarget();</script>
</body></html>""", {"TOPBAR": topbar(cfg), "NAME": esc(nsname), "BLURB": section["blurb"], "ROWS": rows})
return head_html(nsname + " — Ludic", NS_TIP.get(nsname,""), "item.css") + "\n<body>\n" + body
def color_page(palette, cfg):
groups = ""
for grp in palette["groups"]:
sw = ""
for col in grp["colors"]:
h = col["hex"]; nm = col["name"]; aid = nm.lower()
sw += ('<div class="swatch" id="%s"><span class="chip" style="background:#%s"></span>'
'<span class="cname">Color.%s</span><span class="chex">#%s</span></div>'
) % (aid, h, esc(nm), h)
groups += '<div class="swatch-group"><h3>%s</h3><div class="swatch-row">%s</div></div>' % (esc(grp["name"]), sw)
body = fill("""@@TOPBAR@@
<main class="wrap item">
<div class="crumbs"><a href="api.html">API Reference</a> <span>›</span> <span class="here">Color</span></div>
<div class="item-head"><span class="kind-badge kind-namespace">namespace</span><h1 id="top">Color</h1></div>
<p class="ns-blurb">@@BLURB@@ Every <code>Color.Name</code> lowers to a plain <code>0xRRGGBB</code> integer at compile time — no runtime cost. @@COUNT@@ names are built in.</p>
@@GROUPS@@
<a class="back" href="api.html">← All symbols</a>
</main>
<script src="ludic-highlight.js"></script>
<script>Ludic.installCards(); Ludic.flashTarget();</script>
</body></html>""", {"TOPBAR": topbar(cfg), "BLURB": "The named color palette.",
"COUNT": palette["count"], "GROUPS": groups})
return head_html("Color — Ludic", "The Ludic named-color palette.", "item.css") + "\n<body>\n" + body
# ---------------------------------------------------------------------------
# api index with fuzzy search
# ---------------------------------------------------------------------------
def api_index(sections, cfg):
cards = ""
for s in sections:
if s["cat"] == "colors":
cards += ('<section class="idx-sec" data-sec="%s"><h2 id="%s">%s</h2>'
'<p class="sec-blurb">%s</p><div class="idx-grid">'
'<a class="idx-item" href="ns-color.html" data-name="Color" data-tip="The named color palette.">'
'<code>Color</code><span>The named color palette (221 names).</span></a></div></section>'
) % (s["id"], s["id"], esc(s["title"]), s["blurb"])
continue
rows = ""
for e in s["entries"]:
rows += ('<a class="idx-item" href="%s.html" data-name="%s" data-tip="%s"><code>%s</code><span>%s</span></a>'
) % (e["id"], escattr(e.get("name","")), escattr(e.get("tip","")),
esc(e.get("name","")), esc(e.get("tip","")))
cards += ('<section class="idx-sec" data-sec="%s"><h2 id="%s">%s</h2>'
'<p class="sec-blurb">%s</p><div class="idx-grid">%s</div></section>'
) % (s["id"], s["id"], esc(s["title"]), s["blurb"], rows)
body = fill("""@@TOPBAR@@
<main class="wrap ref">
<div class="ref-intro">
<div class="kicker">Reference</div>
<h1>API Reference</h1>
<p>Every keyword, type, phase, builtin, namespace method, annotation and color in Ludic — each on its own page. Search, or browse by section. In any code sample across this site, hover a token for a summary and click to jump to its page.</p>
<input id="search" class="search" type="search" placeholder="Search symbols… (e.g. handler, fill_rectangle, @Sync)" autocomplete="off" autofocus>
<div id="noresults" class="noresults" hidden>No symbols match.</div>
</div>
@@CARDS@@
</main>
<script src="ludic-highlight.js"></script>
<script>Ludic.installCards(); Ludic.installSearch();</script>
</body></html>""", {"TOPBAR": topbar(cfg), "CARDS": cards})
return head_html("Ludic — API Reference", "The complete Ludic API Reference: every keyword, type, builtin, namespace, annotation and color, each on its own page, with fuzzy search.", "item.css") + "\n<body>\n" + body
# ---------------------------------------------------------------------------
# landing page (data-driven, unchanged structure; highlighter now deep-links)
# ---------------------------------------------------------------------------
def read_snippet(rel): return open(os.path.join(ROOT, rel), encoding="utf-8").read().rstrip("\n")
def render_index(cfg):
css = open(os.path.join(ASSETS, "site.css")).read()
hero = cfg["hero"]
navlinks = "".join(
'<a {cls}href="{h}">{l}</a>'.format(
h=n["href"], l=esc(n["label"]),
cls='class="nav-cta" ' if n.get("href") == "api.html" else "")
for n in cfg["nav_links"])
# hero snippet
navlinks = nav_html(cfg)
hero_code = esc(read_snippet(hero["snippet"]))
# pipeline
stages = ""
for st in hero["pipeline"]:
hl = " hl" if st == "ludicc" else ""
stages += '<span class="stage%s">%s</span>' % (hl, esc(st))
if st != hero["pipeline"][-1]:
stages += '<span class="arrow">→</span>'
# features
feats = ""
for c in cfg["features"]["cards"]:
feats += ('<div class="feat reveal"><div class="ico">%s</div>'
'<h3>%s</h3><p>%s</p></div>') % (c["icon"], c["title"], c["html"])
# philosophy
if st != hero["pipeline"][-1]: stages += '<span class="arrow">→</span>'
feats = "".join('<div class="feat reveal"><div class="ico">%s</div><h3>%s</h3><p>%s</p></div>'
% (c["icon"], c["title"], c["html"]) for c in cfg["features"]["cards"])
phil = cfg["philosophy"]
phil_paras = "".join("<p>%s</p>" % p for p in phil["paras"])
phil_stats = "".join('<div class="stat"><div class="big">%s</div><div class="lbl">%s</div></div>'
% (s["big"], esc(s["lbl"])) for s in phil["stats"])
# get-started steps + terminal
start = cfg["start"]
steps = ""
for i, s in enumerate(start["steps"], 1):
steps += ('<div class="step reveal"><div class="n">%d</div>'
'<div><h4>%s</h4><p>%s</p></div></div>') % (i, s["title"], s["html"])
steps = "".join('<div class="step reveal"><div class="n">%d</div><div><h4>%s</h4><p>%s</p></div></div>'
% (i, s["title"], s["html"]) for i, s in enumerate(start["steps"], 1))
term = ""
for t in start["terminal"]:
if t.get("blank"):
term += "\n"
elif "comment" in t:
term += '<span class="t-com"># %s</span>\n' % esc(t["comment"])
elif "cmd" in t:
term += '<span class="prompt">$</span> %s\n' % esc(t["cmd"])
elif "out" in t:
term += '<span class="out">%s</span>\n' % esc(t["out"])
# editors
if t.get("blank"): term += "\n"
elif "comment" in t: term += '<span class="t-com"># %s</span>\n' % esc(t["comment"])
elif "cmd" in t: term += '<span class="prompt">$</span> %s\n' % esc(t["cmd"])
elif "out" in t: term += '<span class="out">%s</span>\n' % esc(t["out"])
ed = cfg["editors"]
eds = "".join('<div class="ed"><span class="k">◆</span> %s</div>' % esc(x) for x in ed["list"])
# showcase samples -> JS array, code read from real files
samples = []
for s in cfg["showcase"]["samples"]:
samples.append({"name": s["name"], "label": s["label"],
"note": s["note"], "code": read_snippet(s["file"])})
samples_json = json.dumps(samples)
# footer links
samples = [{"name": s["name"], "label": s["label"], "note": s["note"], "code": read_snippet(s["file"])}
for s in cfg["showcase"]["samples"]]
footlinks = "".join('<a href="%s">%s</a>' % (n["href"], esc(n["label"])) for n in cfg["nav_links"])
footlinks += '<a href="%s">Source ↗</a>' % cfg["repo_url"]
m = cfg["meta"]
tmpl = """<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>%(title)s</title>
<meta name="description" content="%(desc)s">
<meta property="og:title" content="%(ogt)s">
<meta property="og:description" content="%(ogd)s">
<meta property="og:type" content="website">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet">
<style>
%(css)s
</style>
</head>
<body>
<header class="nav">
<div class="wrap nav-in">
<a class="brand" href="#top"><span class="logo">L</span> %(brand)s</a>
<nav class="nav-links">%(navlinks)s
<a class="nav-cta" href="%(repo)s">Source ↗</a>
</nav>
</div>
</header>
<a id="top"></a>
<section class="hero">
<div class="wrap hero-grid">
<div>
<span class="pill"><span class="dot"></span> %(pill)s</span>
<h1>%(title_pre)s <span class="accent">%(title_accent)s</span></h1>
<p class="lead">%(lead)s</p>
<div class="cta-row">
<a class="btn btn-primary" href="%(pcta_h)s">%(pcta_l)s</a>
<a class="btn btn-ghost" href="%(scta_h)s">%(scta_l)s</a>
</div>
</div>
<div class="code-card reveal">
<div class="code-top">
<span class="tl r"></span><span class="tl y"></span><span class="tl g"></span>
<span class="code-name">%(hero_name)s</span>
</div>
<pre data-lang="ludic">%(hero_code)s</pre>
</div>
</div>
<div class="wrap" style="margin-top:52px">
<div class="pipeline reveal">%(stages)s</div>
<p style="text-align:center;color:var(--muted);font-size:13.5px;margin:14px 0 0">%(pipenote)s</p>
</div>
</section>
<section id="features">
<div class="wrap">
<div class="sec-head reveal">
<div class="kicker">%(feat_kicker)s</div>
<h2>%(feat_title)s</h2>
<p>%(feat_intro)s</p>
</div>
<div class="feat-grid">%(feats)s</div>
</div>
</section>
<section id="showcase" style="padding-top:24px">
<div class="wrap">
<div class="sec-head reveal">
<div class="kicker">%(sc_kicker)s</div>
<h2>%(sc_title)s</h2>
<p>%(sc_intro)s</p>
</div>
<div class="tabs reveal" id="tabs"></div>
<div id="panels"></div>
<div class="showcase-note reveal"><span class="b">↳</span><span id="note"></span></div>
</div>
</section>
<section style="padding-top:24px">
<div class="wrap">
<div class="banner reveal">
<div>
<div class="kicker" style="color:var(--blue)">%(phil_kicker)s</div>
<h2>%(phil_title)s</h2>
%(phil_paras)s
</div>
<div class="stat-row">%(phil_stats)s</div>
</div>
</div>
</section>
<section id="start">
<div class="wrap">
<div class="sec-head reveal">
<div class="kicker">%(start_kicker)s</div>
<h2>%(start_title)s</h2>
<p>%(start_intro)s</p>
</div>
<div class="steps">
<div>%(steps)s</div>
<div class="term reveal">
<div class="code-top">
<span class="tl r"></span><span class="tl y"></span><span class="tl g"></span>
<span class="code-name">%(term_name)s</span>
</div>
<pre>%(term)s</pre>
</div>
</div>
</div>
</section>
<section id="editors" style="padding-top:24px">
<div class="wrap">
<div class="sec-head reveal">
<div class="kicker">%(ed_kicker)s</div>
<h2>%(ed_title)s</h2>
<p>%(ed_intro)s</p>
</div>
<div class="editors reveal">%(eds)s</div>
<p style="margin-top:22px;color:var(--muted);font-size:14.5px">%(ed_note)s</p>
</div>
</section>
<footer>
<div class="wrap foot-in">
<div>
<div class="brand" style="margin-bottom:8px"><span class="logo">L</span> %(brand)s</div>
<div class="muted">%(tagline)s</div>
</div>
<nav class="foot-links">%(footlinks)s</nav>
</div>
</footer>
<script src="ludic-highlight.js"></script>
<script>
Ludic.highlightAll();
const SAMPLES = %(samples)s;
const tabsEl = document.getElementById("tabs");
const panelsEl = document.getElementById("panels");
const noteEl = document.getElementById("note");
SAMPLES.forEach((s, idx)=>{
const t = document.createElement("button");
t.className = "tab" + (idx===0 ? " active" : "");
t.textContent = s.label;
t.onclick = ()=>select(idx);
tabsEl.appendChild(t);
const card = document.createElement("div");
card.className = "code-card panel-code" + (idx===0 ? " active" : "");
card.innerHTML =
'<div class="code-top"><span class="tl r"></span><span class="tl y"></span><span class="tl g"></span><span class="code-name">'
+ s.name + '</span></div><pre>' + Ludic.highlight(s.code) + '</pre>';
panelsEl.appendChild(card);
});
function select(idx){
[...tabsEl.children].forEach((t,i)=>t.classList.toggle("active", i===idx));
[...panelsEl.children].forEach((p,i)=>p.classList.toggle("active", i===idx));
noteEl.textContent = SAMPLES[idx].note;
}
noteEl.textContent = SAMPLES[0].note;
const io = new IntersectionObserver((entries)=>{
entries.forEach(e=>{ if(e.isIntersecting){ e.target.classList.add("in"); io.unobserve(e.target); } });
},{threshold:.12});
document.querySelectorAll(".reveal").forEach(el=>io.observe(el));
</script>
</body>
</html>
"""
tmpl = open(os.path.join(ASSETS, "index.tmpl.html")).read()
return pct(tmpl, dict(
css=css, brand=esc(cfg["brand"]), tagline=esc(cfg["tagline"]), repo=cfg["repo_url"],
title=esc(m["title"]), desc=esc(m["description"]), ogt=esc(m["og_title"]), ogd=esc(m["og_description"]),
navlinks=navlinks,
pill=esc(hero["pill"]), title_pre=esc(hero["title_pre"]), title_accent=esc(hero["title_accent"]),
title=esc(m["title"]), desc=escattr(m["description"]), ogt=esc(m["og_title"]), ogd=escattr(m["og_description"]),
navlinks=navlinks, pill=esc(hero["pill"]), title_pre=esc(hero["title_pre"]), title_accent=esc(hero["title_accent"]),
lead=hero["lead"], pcta_h=hero["primary_cta"]["href"], pcta_l=esc(hero["primary_cta"]["label"]),
scta_h=hero["secondary_cta"]["href"], scta_l=esc(hero["secondary_cta"]["label"]),
hero_name=esc(hero["snippet_name"]), hero_code=hero_code, stages=stages, pipenote=hero["pipeline_note"],
feat_kicker=esc(cfg["features"]["kicker"]), feat_title=esc(cfg["features"]["title"]),
feat_intro=cfg["features"]["intro"], feats=feats,
sc_kicker=esc(cfg["showcase"]["kicker"]), sc_title=esc(cfg["showcase"]["title"]),
sc_intro=cfg["showcase"]["intro"],
feat_kicker=esc(cfg["features"]["kicker"]), feat_title=esc(cfg["features"]["title"]), feat_intro=cfg["features"]["intro"], feats=feats,
sc_kicker=esc(cfg["showcase"]["kicker"]), sc_title=esc(cfg["showcase"]["title"]), sc_intro=cfg["showcase"]["intro"],
phil_kicker=esc(phil["kicker"]), phil_title=esc(phil["title"]), phil_paras=phil_paras, phil_stats=phil_stats,
start_kicker=esc(start["kicker"]), start_title=esc(start["title"]), start_intro=esc(start["intro"]),
steps=steps, term_name=esc(start["terminal_name"]), term=term,
ed_kicker=esc(cfg["editors"]["kicker"]), ed_title=esc(cfg["editors"]["title"]),
ed_intro=cfg["editors"]["intro"], eds=eds, ed_note=cfg["editors"]["note"],
footlinks=footlinks, samples=samples_json,
ed_kicker=esc(ed["kicker"]), ed_title=esc(ed["title"]), ed_intro=ed["intro"], eds=eds, ed_note=ed["note"],
footlinks=footlinks, samples=json.dumps(samples),
))
def pct(tmpl, mapping):
return re.sub(r"%\((\w+)\)s", lambda mm: mapping[mm.group(1)], tmpl)
# ---------------------------------------------------------------------------
def render_highlighter(symbols):
tmpl = open(os.path.join(ASSETS, "ludic-highlight.tmpl.js")).read()
@ -504,22 +401,39 @@ def main():
sections = load_sections()
palette = json.load(open(os.path.join(LANG, "colors", "palette.json")))
symbols = build_symbols(sections)
symbols, items = build_symbols(sections, palette)
cfg = json.load(open(os.path.join(SITE, "site.json")))
open(os.path.join(out, "api.html"), "w").write(render_api(sections, palette, cfg))
open(os.path.join(out, "index.html"), "w").write(render_index(cfg))
open(os.path.join(out, "ludic-highlight.js"), "w").write(render_highlighter(symbols))
open(os.path.join(out, "symbols.json"), "w").write(json.dumps(symbols, indent=2, ensure_ascii=False))
open(os.path.join(out, ".nojekyll"), "w").write("")
W = lambda name, content: open(os.path.join(out, name), "w").write(content)
# per-item pages
npages = 0
for s in sections:
if s["cat"] == "colors":
continue
for e in s["entries"]:
W(e["id"] + ".html", item_page(e, s, cfg, items)); npages += 1
# namespace overview pages
by_cat = {s["cat"]: s for s in sections}
for nsname, cat in (("Screen","screen"),("Input","input"),("Random","random"),("Map","map")):
if cat in by_cat:
W(ns_page(nsname) + ".html", ns_overview_page(nsname, by_cat[cat], cfg)); npages += 1
W("ns-color.html", color_page(palette, cfg)); npages += 1
# index + landing + assets
W("api.html", api_index(sections, cfg))
W("index.html", render_index(cfg))
W("ludic-highlight.js", render_highlighter(symbols))
W("symbols.json", json.dumps({"items": items, "highlight": symbols}, indent=2, ensure_ascii=False))
W(".nojekyll", "")
n_entries = sum(len(s["entries"]) for s in sections)
print("docs generated -> %s" % out)
print(" sections: %d symbols: %d colors: %d"
% (len(sections), n_entries, palette["count"]))
print(" highlighter tokens: %d kw / %d type / %d builtin / %d ns-method / %d annot"
% (len(symbols["keywords"]), len(symbols["types"]), len(symbols["builtins"]),
len(symbols["nsmethods"]), len(symbols["annotations"])))
print(" sections: %d symbols: %d colors: %d item pages: %d"
% (len(sections), n_entries, palette["count"], npages))
print(" highlighter: %d kw / %d type / %d phase / %d builtin / %d ns-method / %d annot / %d ns"
% (len(symbols["keywords"]), len(symbols["types"]), len(symbols["phases"]),
len(symbols["builtins"]), len(symbols["nsmethods"]), len(symbols["annotations"]),
len(symbols["namespaces"])))
if __name__ == "__main__":
main()

187
tools/docgen/inventory.json Normal file
View file

@ -0,0 +1,187 @@
{
"annotations": [
"annot-queries",
"annot-computed",
"annot-onstart",
"annot-onquit",
"annot-onspawn",
"annot-ondespawn",
"annot-onattach",
"annot-ondetach",
"annot-onenable",
"annot-ondisable",
"annot-on",
"annot-public",
"annot-handles",
"annot-export",
"annot-reads",
"annot-writes",
"annot-sync",
"annot-owned",
"annot-server",
"annot-predicted",
"annot-toserver",
"annot-toclients"
],
"builtins": [
"fn-print",
"fn-str",
"fn-quit",
"fn-save",
"fn-load",
"fn-len",
"fn-push",
"fn-min",
"fn-max",
"fn-abs",
"fn-clamp",
"fn-fx",
"fn-flr",
"fn-bytes",
"fn-words",
"fn-ui_build",
"fn-arg_count",
"fn-arg",
"fn-exit",
"fn-run",
"fn-getenv",
"fn-read_char",
"fn-file_write",
"fn-file_stdout",
"fn-file_stderr"
],
"control": [
"kw-if",
"kw-while",
"kw-for",
"kw-in",
"kw-match",
"kw-machine",
"kw-state",
"kw-become"
],
"ecs": [
"kw-spawn",
"kw-despawn",
"kw-query",
"kw-self",
"kw-enable",
"kw-disable",
"kw-attach",
"kw-detach",
"fn-world_get",
"fn-world_set",
"fn-world_has",
"fn-world_count",
"fn-world_spawn",
"fn-world_size",
"fn-world_save",
"fn-world_load",
"fn-world_field_id",
"fn-world_prop_id",
"fn-world_model_id",
"fn-world_kind",
"fn-world_register_prop",
"fn-world_attach_dyn",
"fn-world_detach_dyn",
"fn-world_query_next"
],
"events": [
"kw-event",
"kw-emit",
"kw-cancel",
"kw-cancellable"
],
"input": [
"input-key"
],
"map": [
"map-size",
"map-row",
"map-tile"
],
"networking": [
"fn-net_send",
"fn-net_poll",
"fn-owner",
"fn-set_owner",
"fn-is_server",
"fn-is_owner",
"fn-local_id",
"fn-serialize",
"fn-apply"
],
"operators": [
"op-arith",
"op-compare",
"op-logical",
"op-bitwise",
"op-range",
"op-assign",
"op-access",
"op-interp",
"op-literals",
"op-comment"
],
"phases": [
"phase-fixedupdate",
"phase-input",
"phase-lateupdate",
"phase-render",
"phase-start",
"phase-update"
],
"random": [
"random-range",
"random-chance",
"random-seed"
],
"scenes": [
"kw-scene",
"kw-layer",
"kw-on",
"kw-enter",
"kw-exit",
"kw-start"
],
"screen": [
"screen-clear",
"screen-fill_rectangle",
"screen-draw_rectangle",
"screen-put_pixel",
"screen-draw_text",
"screen-draw_number",
"screen-show",
"screen-width",
"screen-height",
"screen-status"
],
"structure": [
"kw-program",
"kw-property",
"kw-model",
"kw-handler",
"kw-phase",
"kw-const",
"kw-var",
"kw-let",
"kw-fn",
"kw-return",
"kw-import",
"kw-extern",
"kw-ui",
"kw-enum"
],
"types": [
"type-int",
"type-fixed",
"type-bool",
"type-str",
"type-entity",
"type-ptr",
"type-words",
"type-byte",
"type-void",
"type-slices"
]
}

55
tools/docgen/validate.py Normal file
View file

@ -0,0 +1,55 @@
#!/usr/bin/env python3
"""Compile-validate every ```ludic example in the docs against the real ludicc.
Full programs (start with program/module) compile directly; fragments are wrapped
(as declarations, then as statements) like tools/check-docs.py. Reports failures."""
import os, re, subprocess, tempfile, sys
REPO=os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))); LC=os.path.join(REPO,"bin","ludicc")
FENCE=re.compile(r"```ludic\n(.*?)\n```", re.S)
DECL=("program","property","model","handler","enum","fn","extern","const","var","ui","event","module","import","scene","machine")
def first_kw(body):
for l in body.split("\n"):
s=l.strip()
if s and not s.startswith("#"): return s.split("(")[0].split()[0].split("{")[0]
return ""
def candidates(body):
kw=first_kw(body)
if kw in ("program","module"): return [body]
d="program DocCheck {\n"+body+"\n}\n"
s="program DocCheck {\n handler DocS phase Start {\n"+body+"\n }\n}\n"
return [d,s] if kw in DECL else [s,d]
def compiles(src, full):
with tempfile.NamedTemporaryFile("w",suffix=".ludic",delete=False) as f:
f.write(src); tmp=f.name
flag=["--emit-llvm","-o",tmp+".ll"] if full else ["--fmt"]
r=subprocess.run([LC,tmp]+flag,capture_output=True)
os.unlink(tmp)
try: os.unlink(tmp+".ll")
except OSError: pass
return r.returncode==0, (r.stderr or b"").decode("utf-8","replace").strip().split("\n")[0]
def files():
for base in ("docs/language","docs/site/snippets"):
for root,_,fs in os.walk(os.path.join(REPO,base)):
for fn in fs:
if fn.endswith(".md") or fn.endswith(".ludic"): yield os.path.join(root,fn)
ok=fail=skip=0; fails=[]
for p in files():
t=open(p).read()
blocks=FENCE.findall(t) if p.endswith(".md") else [t]
for b in blocks:
if 'import "' in b: skip+=1; continue
good=False; err=""
full = first_kw(b) in ("program","module")
for cand in candidates(b):
c,e=compiles(cand, full)
if c: good=True; break
if not err: err=e
if good: ok+=1
else: fail+=1; fails.append((os.path.relpath(p,REPO),err))
print(f"examples: {ok} compile, {fail} fail, {skip} skipped (import)")
for p,e in fails: print(f" FAIL {p}: {e[:100]}")
sys.exit(1 if fail else 0)