3D engine that AI agents drive
Add a Start here path with live examples to the docs (part of #508)
Nguyen Xuan An915c302cd1ce
diff --git a/changes/508-start-here.md b/changes/508-start-here.mdnew file mode 100644index 00000000..ab77dd4e--- /dev/null+++ b/changes/508-start-here.md@@ -0,0 +1 @@+- Docs: add a Start here path (part of #508). Introduction, Install and Your first scene take a reader from an empty folder to an animated scene in six steps. Each step shows the expected result. Code blocks marked `live` run in the page on the site's own engine build. A reader can edit, run, reset and copy them. The pictures come from those examples through `npm run docs:media`. The docs page gains headings, lists, figures, callouts and cards. It also gains package manager tabs and an outline of the page. Every guide section now shows in the navigation. `/guide.md` is built from the start pages and the guide in navigation order. Old `#overview` and `#getting-started` links still open the new pages.diff --git a/docs.html b/docs.htmlindex 5c5c806c..84aceb65 100644--- a/docs.html+++ b/docs.html@@ -1,6 +1,6 @@<!doctype html><html lang="en" data-theme="afterimage">-<head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><meta name="description" content="67js documentation: scenes, materials, cameras, animation, GLB assets, CPU/GPU media export and AI agent workflows."/><title>Documentation · 67js</title><link rel="icon" href="/favicon.svg"/></head>+<head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><meta name="description" content="Learn 67js from an empty folder to a rendered scene: install, a first scene with live examples, materials, cameras, animation, GLB assets, media export and AI agent workflows."/><title>Documentation · 67js</title><link rel="icon" href="/favicon.svg"/></head><body class="site documentation"><a class="skip-link" href="#content">Skip to content</a><header class="navigation">@@ -11,7 +11,7 @@</header><main id="content" class="docs docs-page"><aside class="docs-sidebar" aria-label="Documentation navigation">- <a class="docs-title" href="#install">Documentation</a>+ <a class="docs-title" href="#introduction">Documentation</a><label class="docs-search" for="doc-search"><span>Search documentation</span><input id="doc-search" type="search" placeholder="Search topics and code…" autocomplete="off"/></label><p id="doc-results" role="status" aria-live="polite"></p><details id="doc-topic-menu"><summary>Topics <span id="doc-topic-name">Install</span><span aria-hidden="true">⌄</span></summary><nav id="doc-toc" aria-label="Documentation topics"></nav></details>@@ -22,6 +22,7 @@<article id="doc-article" tabindex="-1" aria-label="Documentation article"></article><noscript><p>Read the <a href="/guide.md">complete plain-text guide</a> with JavaScript disabled.</p></noscript></div>+ <nav id="doc-outline" class="doc-outline" aria-label="On this page" hidden></nav></main><footer class="site-footer" aria-label="Site footer"><p><a class="brand" href="/" aria-label="67js home">67js</a> by <a href="https://codepawl.com">CodePawl</a></p>diff --git a/docs/guide.md b/docs/guide.mdindex 4aa94c06..a0976f83 100644--- a/docs/guide.md+++ b/docs/guide.md@@ -4,72 +4,6 @@ Build a scene once. Make it interactive. Export the frame or film.67js is a WebGL2 graphics toolkit with shared geometry, deterministic animation and a bounded media pipeline. It is not API-compatible with Three.js and does not provide a Blender-style modeling editor.-## Install--```sh-npm install 67js@npm:@codepawlhq/67js-```--The alias lets your application import `67js`. Without the alias, import `@codepawlhq/67js`. Use a package-aware development server such as Vite. The homepage's release command pins the published version.--Its browser module is a bundled ES module served with CORS headers. A local checkout can be newer than the published package. Check `VERSION` and `release.json` before using a feature.--## Getting started--1. Create `index.html` with the canvas below.-2. Save the JavaScript example as `main.js` in the same directory.-3. Run a development server that resolves npm imports, such as Vite.--```html-<canvas id="scene" style="width:100%;height:70vh;display:block"></canvas>-<script type="module" src="./main.js"></script>-```--```js-import { Renderer67, box } from '67js';--const canvas = document.querySelector('#scene');-const parts = [{- name: 'My first cube',- geometry: box(0.08, 4),- matrix: new Float32Array([- 1, 0, 0, 0,- 0, 1, 0, 0,- 0, 0, 1, 0,- 0, 0, 0, 1,- ]),- material: {- color: [0.2, 0.55, 0.38],- metallic: 0,- roughness: 0.55,- emission: 0,- tag: 'surface',- },-}];-const renderer = new Renderer67(canvas, parts, {- ground: false,- pixelRatio: 1.25,- samples: 4,- memoryBudgetMiB: 256,-});-const draw = () => renderer.render({ eye: [3, 2, 4], target: [0, 0, 0] });-const observer = new ResizeObserver(() => {- renderer.resize();- draw();-});-observer.observe(canvas);-draw();-window.addEventListener('pagehide', () => {- observer.disconnect();- renderer.dispose();-}, { once: true });-```--The page displays a rounded green cube in a WebGL2 browser. The observer redraws when its canvas changes size.--For a browser import without npm, use the exact `module` URL from [release metadata](/release.json) instead of `67js`.-The bundled ES module includes its dependencies. Serve the HTML over HTTP. Release metadata provides its URL for browser-only imports.-## Render a PNG from a script without MCPA coding agent that has no MCP client can still produce an image from the installed package.diff --git a/docs/learn/first-scene.md b/docs/learn/first-scene.mdnew file mode 100644index 00000000..a2a2560a--- /dev/null+++ b/docs/learn/first-scene.md@@ -0,0 +1,294 @@+# Your first scene++In this tutorial, you build the scene below: three shapes on a floor, with a turning cube. Each step adds one idea and shows the result. Every example runs on this page, so you can change the code before you copy it.++++You learn how to:++- give a scene a canvas to draw on+- describe a part with a geometry, a matrix and a material+- change the color and the surface of a material+- place and size shapes+- animate a part and draw frames in a loop++Start with the project from [Install](#install). It has Vite and the `67js` package.++## 1. Add a canvas++67js draws into an HTML `<canvas>` element. Replace the contents of `index.html` with this page:++```html file=index.html+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>My first 67js scene</title>+ <style>+ html, body { margin: 0; height: 100%; background: #101014; }+ #scene { display: block; width: 100%; height: 100%; }+ </style>+ </head>+ <body>+ <canvas id="scene"></canvas>+ <script type="module" src="/src/main.js"></script>+ </body>+</html>+```++The canvas fills the window. The renderer reads the size of the canvas on the page, so the canvas must have a width and a height in CSS.++Start the development server:++```sh+npm run dev+```++It prints a local address:++```text+ VITE v8.3.6 ready in 329 ms++ ➜ Local: http://localhost:5173/+ ➜ Network: use --host to expose+```++Open the `Local` address. The page is dark and empty, because `main.js` does not draw yet.++## 2. Draw a cube++Replace the contents of `src/main.js` with this code. You can delete `src/counter.js` and `src/style.css`, because this tutorial does not use them.++```js live poster=first-scene-cube+import { Renderer67, box } from '67js';++const canvas = document.querySelector('#scene');+const cube = {+ name: 'Cube',+ geometry: box(),+ matrix: new Float32Array([+ 1, 0, 0, 0,+ 0, 1, 0, 0,+ 0, 0, 1, 0,+ 0, 0.5, 0, 1,+ ]),+ material: { color: [0.2, 0.55, 0.38], metallic: 0, roughness: 0.55 },+};+const renderer = new Renderer67(canvas, [cube]);++function draw() {+ renderer.render({ eye: [2.5, 1.8, 3.5], target: [0, 0.5, 0] });+}++new ResizeObserver(() => {+ renderer.resize();+ draw();+}).observe(canvas);+```++The browser shows a green cube on a dark floor. The code has four parts:++- **The part.** `cube` is a part. Each part has a unique `name`, a `geometry`, a `matrix` and a `material`.+- **The geometry.** `box()` makes a cube with rounded edges. Each side is 1 unit long, and its center is at the origin.+- **The matrix.** The 16 numbers place the part in the world. The last row moves the cube up by 0.5, so it stands on the floor. The [next step](#first-scene/place-more-shapes) shows a shorter way to write it.+- **The renderer.** `new Renderer67(canvas, parts)` uploads the parts. `renderer.render()` draws one picture from a camera at `eye` that looks at `target`.++`ResizeObserver` calls `resize()` and draws again when the canvas changes size. It also runs one time at the start, so it draws the first frame.++> **Tip:** The renderer adds a floor by default. For a scene with its own ground, pass `{ ground: false }` as the third argument of `Renderer67`.++## 3. Change the material++A material sets how light hits the surface. Change the material of the cube to gold:++```js live poster=first-scene-material+import { Renderer67, box } from '67js';++const canvas = document.querySelector('#scene');+const cube = {+ name: 'Cube',+ geometry: box(0.2),+ matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0.5, 0, 1]),+ material: { color: [1, 0.72, 0.3], metallic: 1, roughness: 0.25 },+};+const renderer = new Renderer67(canvas, [cube]);++function draw() {+ renderer.render({ eye: [2.5, 1.8, 3.5], target: [0, 0.5, 0] });+}++new ResizeObserver(() => {+ renderer.resize();+ draw();+}).observe(canvas);+```++The cube is now shiny gold with rounder edges. `box(0.2)` sets the edge radius. The default is `0.08`.++| Field | Values | Effect |+| --- | --- | --- |+| `color` | three numbers from 0 to 1 | Red, green and blue in linear light. `[1, 1, 1]` is white. |+| `metallic` | 0 to 1 | 0 is paint or plastic. 1 is metal, which reflects its own color. |+| `roughness` | 0 to 1 | 0 is a mirror. 1 is chalk. |+| `emission` | 0 or more | Light that the surface gives off. Optional, the default is 0. |++Try `roughness: 0.6` for brushed metal, or `metallic: 0` with `roughness: 0.9` for clay. [Materials and color](#materials-and-color) lists the textures and the special tags.++## 4. Place more shapes++Writing 16 numbers for every part is slow. A small function can make the matrix from a position and a size:++```js live poster=first-scene-shapes+import { Renderer67, box, sphere, torus } from '67js';++// Column-major 4x4 matrix: scale by `size`, then move to x, y, z.+function placeAt(x, y, z, size = 1) {+ return new Float32Array([+ size, 0, 0, 0,+ 0, size, 0, 0,+ 0, 0, size, 0,+ x, y, z, 1,+ ]);+}++const canvas = document.querySelector('#scene');+const parts = [+ {+ name: 'Cube',+ geometry: box(),+ matrix: placeAt(0, 0.5, 0),+ material: { color: [0.2, 0.55, 0.38], metallic: 0, roughness: 0.55 },+ },+ {+ name: 'Ball',+ geometry: sphere(),+ matrix: placeAt(-1.5, 0.45, 0.3, 0.45),+ material: { color: [1, 0.72, 0.3], metallic: 1, roughness: 0.25 },+ },+ {+ name: 'Ring',+ geometry: torus(0.25),+ matrix: placeAt(1.5, 0.55, 0.3, 0.45),+ material: { color: [0.75, 0.18, 0.28], metallic: 0, roughness: 0.4 },+ },+];+const renderer = new Renderer67(canvas, parts);++function draw() {+ renderer.render({ eye: [0, 2, 5], target: [0, 0.4, 0] });+}++new ResizeObserver(() => {+ renderer.resize();+ draw();+}).observe(canvas);+```++The scene has a ball on the left, the cube in the middle and a ring on the right. The camera moved to the front, so all three are in view.++Each shape has a known size at scale 1. Use the `size` argument to make it smaller or larger.++| Function | Shape at scale 1 |+| --- | --- |+| `box(edge)` | A cube with sides of 1 |+| `sphere(segments, rings)` | A ball with a radius of 1 |+| `torus(tube)` | A ring with a radius of 1 in the XY plane, and a tube radius of `tube` |+| `cylinder(segments)` | A radius of 1 and a height of 1 |++The Y axis points up. One unit is one meter for the lights and the fog. [Parts and geometry](#parts-and-geometry) explains matrices and shared geometry.++## 5. Animate the cube++To animate a part, change its matrix, upload the change, and draw again in each frame. This version turns the cube about the Y axis:++```js live poster=first-scene-animate loop=1.9635+import { Renderer67, box, sphere, torus } from '67js';++// Scale by `size`, turn by `angle` radians about the Y axis, then move to x, y, z.+function placeAt(x, y, z, size = 1, angle = 0) {+ const cos = Math.cos(angle) * size;+ const sin = Math.sin(angle) * size;+ return new Float32Array([+ cos, 0, -sin, 0,+ 0, size, 0, 0,+ sin, 0, cos, 0,+ x, y, z, 1,+ ]);+}++const canvas = document.querySelector('#scene');+const cube = {+ name: 'Cube',+ geometry: box(),+ matrix: placeAt(0, 0.5, 0),+ material: { color: [0.2, 0.55, 0.38], metallic: 0, roughness: 0.55 },+};+const parts = [+ cube,+ {+ name: 'Ball',+ geometry: sphere(),+ matrix: placeAt(-1.5, 0.45, 0.3, 0.45),+ material: { color: [1, 0.72, 0.3], metallic: 1, roughness: 0.25 },+ },+ {+ name: 'Ring',+ geometry: torus(0.25),+ matrix: placeAt(1.5, 0.55, 0.3, 0.45),+ material: { color: [0.75, 0.18, 0.28], metallic: 0, roughness: 0.4 },+ },+];+const renderer = new Renderer67(canvas, parts);++function frame(milliseconds) {+ const seconds = milliseconds / 1000;+ cube.matrix = placeAt(0, 0.5, 0, 1, seconds * 0.8);+ renderer.updateParts(parts);+ renderer.render({ eye: [0, 2, 5], target: [0, 0.4, 0] });+ requestAnimationFrame(frame);+}++new ResizeObserver(() => renderer.resize()).observe(canvas);+requestAnimationFrame(frame);+```++The cube turns at 0.8 radians per second. The loop works like this:++1. `requestAnimationFrame` calls `frame` before the browser paints, about 60 times each second.+2. `frame` sets a new matrix on the cube from the time.+3. `renderer.updateParts(parts)` uploads the changed matrices. It does not upload the geometry again.+4. `renderer.render()` draws the frame.++The angle comes from the time, not from a counter. So a slow computer shows the same position at the same second, and an export can ask for any time. [Deterministic animation](#deterministic-animation) does the same with keyframes.++> **Warning:** `updateParts` changes matrices and materials only. To add or remove parts, make a new renderer and call `dispose()` on the old one.++## 6. Clean up++A renderer holds memory on the graphics card. When your page or component goes away, stop the loop and release the renderer:++```js+let frameRequest = requestAnimationFrame(frame);+const observer = new ResizeObserver(() => renderer.resize());+observer.observe(canvas);++window.addEventListener('pagehide', () => {+ cancelAnimationFrame(frameRequest);+ observer.disconnect();+ renderer.dispose();+}, { once: true });+```++Store the request from each `requestAnimationFrame` call in `frameRequest`, so `cancelAnimationFrame` stops the latest one. In React, Vue or Svelte, put this code in the cleanup function of the component.++## What you built++You made a scene with three parts, gave them materials, placed them with matrices and animated one of them. Most 67js programs follow the same pattern.++```cards+Parts and geometry | #parts-and-geometry | Matrices, shared geometry and your own meshes.+Cameras and framing | #cameras-and-framing | Field of view, axis views and orthographic cameras.+Effects and lighting | #effects-and-lighting | Exposure, bloom, sky, sun and fog.+Import and export models | #import-and-export-models | Load GLB files and save your scene.+```diff --git a/docs/learn/install.md b/docs/learn/install.mdnew file mode 100644index 00000000..842d4e0d--- /dev/null+++ b/docs/learn/install.md@@ -0,0 +1,82 @@+# Install++This page makes a new web project and adds 67js to it. At the end, you have a project that the first-scene tutorial builds on.++## Before you start++You need these two things:++- **Node.js 20.19 or later.** Run `node --version` to see your version. Get Node.js from [nodejs.org](https://nodejs.org/).+- **A browser with WebGL2.** Current Chrome, Edge, Firefox and Safari have it.++```check webgl2+```++## 1. Make a project++Make a new project with Vite. Vite is a development server that loads npm packages in the browser.++```sh install+npm create vite@latest my-scene -- --template vanilla+```++Go into the folder and install its packages:++```sh+cd my-scene+npm install+```++The `my-scene` folder now has `index.html`, `package.json` and a `src` folder.++## 2. Add 67js++Install the package with the name `67js`:++```sh install+npm install 67js@npm:@codepawlhq/67js+```++The package on npm is `@codepawlhq/67js`. The `67js@npm:` part gives it the shorter name `67js`, so your code writes `import { Renderer67 } from '67js'`. If you install it without that part, import from `@codepawlhq/67js` instead.++## 3. Check the install++Run this command in the project folder:++```sh+npm ls 67js+```++It prints the installed version:++```text+`-- 67js@npm:@codepawlhq/[email protected]+```++Your version can be newer. The [changelog](/changelog.html) lists what each version adds.++## Use 67js without npm++A plain HTML page can import 67js from this site. Use the exact `module` URL from the [release metadata](/release.json). The URL contains the version, so a release does not change your page.++```html+<script type="importmap">+ { "imports": { "67js": "https://67js.codepawl.com/releases/0.15.0/67.module.js" } }+</script>+<script type="module">+ import { Renderer67, box } from '67js';+</script>+```++Serve the page over HTTP, for example with `npx serve`. A page opened from a `file://` path cannot import modules. This file has the core only. Addons such as `67js/addons/gltf` need the npm package.++## Good to know++> **Note:** 67js is plain JavaScript and has no TypeScript types. In a strict TypeScript project, add the line `declare module '67js';` to a `.d.ts` file. The imports then have the type `any`.++> **Tip:** Addons are separate imports, such as `67js/addons/gltf` for GLB models. You only download the addons that you import.++```cards+Next: your first scene | #first-scene | Draw, color, place and animate shapes step by step.+```diff --git a/docs/learn/introduction.md b/docs/learn/introduction.mdnew file mode 100644index 00000000..f13843c1--- /dev/null+++ b/docs/learn/introduction.md@@ -0,0 +1,64 @@+# Introduction++67js is a 3D engine for the browser. It draws with WebGL2 and runs in every current desktop and phone browser. You describe a scene as a list of parts, and the renderer draws a frame from a camera.++The program below is a complete 67js scene. It runs on this page. Change a number in the code, and the picture changes.++```js live poster=introduction-cube+import { Renderer67, box } from '67js';++const canvas = document.querySelector('#scene');+const cube = {+ name: 'Cube',+ geometry: box(),+ matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0.5, 0, 1]),+ material: { color: [0.85, 0.45, 0.2], metallic: 0, roughness: 0.4 },+};+const renderer = new Renderer67(canvas, [cube]);+new ResizeObserver(() => {+ renderer.resize();+ renderer.render({ eye: [2.5, 1.8, 3.5], target: [0, 0.5, 0] });+}).observe(canvas);+```++## What you can build++Each demo on this site is a 67js scene. Open one to see what the engine does, then read its topic in these docs.++```cards+Object studio | /object.html | A robot model with orbit controls, lighting looks and an exploded view. | /previews/wall-e.webp+Procedural modeling | /modeling.html | A lantern made from lathe, extrude and tube geometry. | /previews/modeling.webp+Nature | /nature.html | Terrain, trees and grass with wind and a sun you can move. | /previews/grass.webp+Assets | /assets.html | GLB models loaded, lit and animated. | /previews/assets.webp+Showcase | /showcase.html | Large scenes: an airport, a data center and a port. | /previews/showcase-airport.webp+2D | /view2d.html | Flat posters drawn with an orthographic camera. | /previews/view2d.webp+```++## How a scene works++A 67js scene has three pieces. You make them in this order.++++1. **Parts.** Each part has a name, a geometry, a position matrix and a material.+2. **Renderer.** `new Renderer67(canvas, parts)` uploads the parts to the graphics card one time.+3. **Frames.** `renderer.render({ eye, target })` draws one picture from a camera at `eye` that looks at `target`.++To move something, change the part and call `renderer.updateParts(parts)`. Then draw the next frame. The renderer keeps the uploaded geometry, so a frame costs little.++## What 67js is not++67js does not copy the three.js API. Code for three.js does not run in 67js without changes. 67js also has no mouse editor like Blender. You build scenes in code, or an AI agent builds them through the MCP server.++## How these docs are organized++- **Start here** takes you from an empty folder to an animated scene. Read these three pages in order.+- **Build a scene**, **Worlds** and **Animate and interact** explain one subject each, with the options and limits.+- **Reference and workflows** lists the renderer options, the exports, the memory rules and the work with AI agents.++You need to know some JavaScript and how to run a command in a terminal. You do not need to know WebGL or 3D math.++```cards+Install 67js | #install | Make a project and add the package. Five minutes.+Your first scene | #first-scene | Draw, color, place and animate shapes step by step.+```diff --git a/package.json b/package.jsonindex 8ae0c09c..f91b355f 100644--- a/package.json+++ b/package.json@@ -127,6 +127,7 @@"smoke:vegetation-impostors": "node scripts/smoke-vegetation-impostors.mjs","smoke:transport": "node scripts/smoke-film-transport.mjs","render": "node scripts/render-media.mjs",+ "docs:media": "node scripts/render-doc-media.mjs","score": "node scripts/score.mjs","export:model": "node scripts/export-model.mjs","smoke:package": "node scripts/smoke-package.mjs",diff --git a/public/docs-media/first-scene-animate.webm b/public/docs-media/first-scene-animate.webmnew file mode 100644index 00000000..66946612Binary files /dev/null and b/public/docs-media/first-scene-animate.webm differdiff --git a/public/docs-media/first-scene-animate.webp b/public/docs-media/first-scene-animate.webpnew file mode 100644index 00000000..e7d468c1Binary files /dev/null and b/public/docs-media/first-scene-animate.webp differdiff --git a/public/docs-media/first-scene-cube.webp b/public/docs-media/first-scene-cube.webpnew file mode 100644index 00000000..0465a87aBinary files /dev/null and b/public/docs-media/first-scene-cube.webp differdiff --git a/public/docs-media/first-scene-material.webp b/public/docs-media/first-scene-material.webpnew file mode 100644index 00000000..cb87e025Binary files /dev/null and b/public/docs-media/first-scene-material.webp differdiff --git a/public/docs-media/first-scene-shapes.webp b/public/docs-media/first-scene-shapes.webpnew file mode 100644index 00000000..1cf009f5Binary files /dev/null and b/public/docs-media/first-scene-shapes.webp differdiff --git a/public/docs-media/introduction-cube.webp b/public/docs-media/introduction-cube.webpnew file mode 100644index 00000000..480c9afdBinary files /dev/null and b/public/docs-media/introduction-cube.webp differdiff --git a/public/docs-media/scene-flow.svg b/public/docs-media/scene-flow.svgnew file mode 100644index 00000000..1f8db8c1--- /dev/null+++ b/public/docs-media/scene-flow.svg@@ -0,0 +1,45 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 960 300" font-family="Inter, system-ui, sans-serif">+ <title>Parts go into the renderer one time. Each frame draws a picture from a camera.</title>+ <rect width="960" height="300" rx="24" fill="#101014"/>+ <defs>+ <marker id="arrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse">+ <path d="M0 0 10 5 0 10z" fill="#8a8a93"/>+ </marker>+ </defs>+ <g>+ <rect x="40" y="56" width="250" height="188" rx="18" fill="#212121"/>+ <text x="66" y="96" fill="#ececec" font-size="22" font-weight="600">Parts</text>+ <g font-family="ui-monospace, Consolas, monospace" font-size="15" fill="#b4b4b4">+ <text x="66" y="134">name</text>+ <text x="66" y="162">geometry</text>+ <text x="66" y="190">matrix</text>+ <text x="66" y="218">material</text>+ </g>+ <path d="m212 128 26 -14 26 14v30l-26 14-26-14z" fill="#3e8f63"/>+ <path d="m212 128 26 14 26-14M238 142v30" fill="none" stroke="#2c6a49" stroke-width="2"/>+ </g>+ <path d="M302 150h80" stroke="#8a8a93" stroke-width="2.5" marker-end="url(#arrow)"/>+ <text x="342" y="136" fill="#8a8a93" font-size="14" text-anchor="middle">one time</text>+ <g>+ <rect x="394" y="56" width="220" height="188" rx="18" fill="#212121"/>+ <text x="420" y="96" fill="#ececec" font-size="22" font-weight="600">Renderer67</text>+ <g font-size="15" fill="#b4b4b4">+ <text x="420" y="134">uploads geometry</text>+ <text x="420" y="162">and textures</text>+ <text x="420" y="198" font-family="ui-monospace, Consolas, monospace" fill="#a6c1ff">updateParts()</text>+ <text x="420" y="222">moves and recolors</text>+ </g>+ </g>+ <path d="M626 150h80" stroke="#8a8a93" stroke-width="2.5" marker-end="url(#arrow)"/>+ <text x="666" y="136" fill="#8a8a93" font-size="14" text-anchor="middle">each frame</text>+ <g>+ <rect x="718" y="56" width="202" height="188" rx="18" fill="#212121"/>+ <text x="744" y="96" fill="#ececec" font-size="22" font-weight="600">Picture</text>+ <text x="744" y="134" font-family="ui-monospace, Consolas, monospace" font-size="15" fill="#a6c1ff">render({ eye,</text>+ <text x="744" y="158" font-family="ui-monospace, Consolas, monospace" font-size="15" fill="#a6c1ff"> target })</text>+ <rect x="744" y="176" width="150" height="48" rx="8" fill="#2f2f2f"/>+ <circle cx="772" cy="200" r="12" fill="#e0a548"/>+ <rect x="800" y="190" width="22" height="22" rx="4" fill="#3e8f63"/>+ <circle cx="858" cy="200" r="13" fill="none" stroke="#bf3b4f" stroke-width="5"/>+ </g>+</svg>diff --git a/scripts/plain-guide.mjs b/scripts/plain-guide.mjsnew file mode 100644index 00000000..61500772--- /dev/null+++ b/scripts/plain-guide.mjs@@ -0,0 +1,26 @@+// Build the plain-text guide (`/guide.md`) for agents and readers without JavaScript: the start pages, then the guide,+// in the order of the site navigation. Learn page headings move down one level so the file keeps one `#` title.+import { readFile, readdir } from 'node:fs/promises';+import { resolve } from 'node:path';+import { guideTopics, learnTopics, orderTopics, topicAliases } from '../src/documentation-topics.js';++function demoteHeadings(markdown) {+ const parts = markdown.split(/(```[^\n]*\n[\s\S]*?```)/g);+ return parts.map(part => part.startsWith('```') ? part : part.replace(/^(#{1,5}) /gm, '#$1 ')).join('');+}++/** Return the complete plain-text guide for a checkout at `root`. */+export async function plainGuide(root) {+ const guide = (await readFile(resolve(root, 'docs/guide.md'), 'utf8')).replace(/\r\n/g, '\n');+ const learnFolder = resolve(root, 'docs/learn');+ const sources = {};+ for (const file of (await readdir(learnFolder)).filter(name => name.endsWith('.md'))) {+ sources[file] = await readFile(resolve(learnFolder, file), 'utf8');+ }+ const learnIds = new Set(Object.keys(sources).map(file => file.slice(0, -3)));+ const topics = [...guideTopics(guide), ...learnTopics(sources)].filter(topic => !(topic.id in topicAliases));+ const { topics: ordered } = orderTopics(topics);+ const introduction = guide.slice(0, guide.search(/^## /m)).trimEnd();+ const body = ordered.map(topic => (learnIds.has(topic.id) ? demoteHeadings(topic.raw) : topic.raw).trim());+ return `${introduction}\n\n${body.join('\n\n')}\n`;+}diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjsindex b7713c99..4a4dfe16 100644--- a/scripts/prepare-release.mjs+++ b/scripts/prepare-release.mjs@@ -5,6 +5,7 @@ import { createHash } from 'node:crypto';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { changelogWithUnreleased, readChangelogData } from './changelog-fragments.mjs';+import { plainGuide } from './plain-guide.mjs';const root = fileURLToPath(new URL('..', import.meta.url));const metadata = JSON.parse(await readFile(resolve(root, 'package.json'), 'utf8'));@@ -38,7 +39,7 @@ const changelogText = await readFile(resolve(root, 'CHANGELOG.md'), 'utf8');await writeFile(resolve(root, 'public/changelog.md'), await changelogWithUnreleased(changelogText));await writeFile(resolve(root, 'public/changelog.json'), `${JSON.stringify(await readChangelogData({ changelogText, version: metadata.version }), null, 2)}`);-await copyFile(resolve(root, 'docs/guide.md'), resolve(root, 'public/guide.md'));+await writeFile(resolve(root, 'public/guide.md'), await plainGuide(root));await copyFile(resolve(root, 'docs/gltf.md'), resolve(root, 'public/gltf.md'));const sourceDocuments = ['scene-graph.md', 'modeling.md', 'animation-curves.md', 'animation-mixer.md',diff --git a/scripts/render-doc-media.mjs b/scripts/render-doc-media.mjsnew file mode 100644index 00000000..a1e9b66c--- /dev/null+++ b/scripts/render-doc-media.mjs@@ -0,0 +1,120 @@+// Render the pictures and loops of the documentation from its own live examples, so they always match the code.+// Usage: node scripts/render-doc-media.mjs [page-id ...]+// Each live example with `poster=<name>` becomes public/docs-media/<name>.webp. When the page also shows+// /docs-media/<name>.webm and the example has `loop=<seconds>`, the example is stepped frame by frame into that WebM.+// Needs Google Chrome and FFmpeg on the PATH (or ~/.local/bin/ffmpeg.exe on Windows).+import { readFile, readdir, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import { tmpdir, homedir } from 'node:os';+import { join, resolve } from 'node:path';+import { spawnSync } from 'node:child_process';+import { createServer } from 'vite';+import { chromium } from 'playwright-core';+import sharp from 'sharp';++const root = resolve(import.meta.dirname, '..');+const outputFolder = join(root, 'public', 'docs-media');+const framesPerSecond = 30;++function ffmpegPath() {+ const local = join(homedir(), '.local', 'bin', 'ffmpeg.exe');+ return existsSync(local) ? local : 'ffmpeg';+}++async function pagesToRender() {+ const requested = process.argv.slice(2);+ const files = await readdir(join(root, 'docs', 'learn'));+ const pages = files.filter(file => file.endsWith('.md')).map(file => file.slice(0, -3));+ return requested.length ? pages.filter(page => requested.includes(page)) : pages;+}++async function examplesOf(page) {+ const text = await readFile(join(root, 'docs', 'learn', `${page}.md`), 'utf8');+ const examples = [];+ for (const match of text.matchAll(/^```js live([^\n]*)$/gm)) {+ const options = Object.fromEntries(match[1].trim().split(/\s+/).filter(Boolean).map(flag => flag.split('=')));+ if (!options.poster) continue;+ const wantsLoop = text.includes(`/docs-media/${options.poster}.webm`);+ examples.push({ poster: options.poster, loopSeconds: wantsLoop ? Number(options.loop) : 0 });+ }+ return examples;+}++async function stagePicture(stage) {+ return stage.screenshot({ type: 'png' });+}++async function writeStill(stage, name) {+ const picture = await stagePicture(stage);+ await sharp(picture).webp({ quality: 82 }).toFile(join(outputFolder, `${name}.webp`));+}++async function writeLoop(stage, frame, name, seconds) {+ const frameCount = Math.round(seconds * framesPerSecond);+ const step = seconds * 1000 / frameCount;+ const folder = await mkdtemp(join(tmpdir(), 'docs-loop-'));+ try {+ for (let index = 0; index < frameCount; index++) {+ await frame.evaluate(milliseconds => window.__advance(milliseconds), step);+ await writeFile(join(folder, `${String(index).padStart(4, '0')}.png`), await stagePicture(stage));+ }+ const result = spawnSync(ffmpegPath(), [+ '-y', '-loglevel', 'error', '-framerate', String(framesPerSecond), '-i', join(folder, '%04d.png'),+ '-c:v', 'libvpx-vp9', '-b:v', '0', '-crf', '38', '-pix_fmt', 'yuv420p', '-row-mt', '1',+ join(outputFolder, `${name}.webm`),+ ], { stdio: 'inherit' });+ if (result.status !== 0) throw new Error(`FFmpeg failed for ${name}.`);+ } finally {+ await rm(folder, { recursive: true, force: true });+ }+}++async function renderPage(browserPage, origin, page) {+ const examples = await examplesOf(page);+ if (!examples.length) return [];+ await browserPage.goto(`${origin}/docs.html?capture#${page}`);+ await browserPage.waitForSelector('.live-example');+ const written = [];+ for (const example of examples) {+ const root = browserPage.locator(`.live-example[data-media="${example.poster}"]`);+ await root.scrollIntoViewIfNeeded();+ await root.evaluate(element => element.liveExample.run());+ await browserPage.waitForFunction(name => document.querySelector(`.live-example[data-media="${name}"]`)?.dataset.ready === 'true', example.poster, { timeout: 30000 });+ const error = await root.locator('.live-status[data-kind=error]').count();+ if (error) throw new Error(`${page}/${example.poster}: ${await root.locator('.live-status').textContent()}`);+ const frame = await (await root.locator('iframe').elementHandle()).contentFrame();+ const stage = root.locator('.live-stage');+ // Let the first frames reach the screen. A loop draws only when the virtual clock advances.+ await frame.evaluate(() => window.__advance(0));+ await browserPage.waitForTimeout(400);+ if (example.loopSeconds) {+ await writeLoop(stage, frame, example.poster, example.loopSeconds);+ written.push(`${example.poster}.webm`);+ }+ await writeStill(stage, example.poster);+ written.push(`${example.poster}.webp`);+ await root.evaluate(element => element.liveExample.stop());+ }+ return written;+}++await mkdir(outputFolder, { recursive: true });+const server = await createServer({ root, configFile: join(root, 'vite.config.js'), logLevel: 'error', server: { port: 0, host: '127.0.0.1', watch: null } });+await server.listen();+const origin = server.resolvedUrls.local[0].replace(/\/$/, '');+const browser = await chromium.launch({+ channel: 'chrome',+ args: ['--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist', '--enable-unsafe-swiftshader'],+});+try {+ const context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, deviceScaleFactor: 2, reducedMotion: 'reduce' });+ const browserPage = await context.newPage();+ browserPage.on('pageerror', error => console.error(`Page error: ${error.message}`));+ for (const page of await pagesToRender()) {+ const written = await renderPage(browserPage, origin, page);+ if (written.length) console.log(`${page}: ${written.join(', ')}`);+ }+} finally {+ await browser.close();+ await server.close();+}diff --git a/scripts/smoke-site.mjs b/scripts/smoke-site.mjsindex b86510af..11de1a18 100644--- a/scripts/smoke-site.mjs+++ b/scripts/smoke-site.mjs@@ -120,8 +120,15 @@ try {await page.locator('#doc-search').fill('');await page.locator('#doc-toc a[href="#models-and-ai-agents"]').click();assert.match(page.url(),/models-and-ai-agents/);- await page.locator('#doc-toc a[href="#getting-started"]').click();- assert.equal(await page.locator('#getting-started ol li').count(), 3);+ await page.locator('#doc-toc a[href="#first-scene"]').click();+ assert.ok(await page.locator('#first-scene .doc-step').count() >= 5);+ assert.ok(await page.locator('#first-scene .live-example').count() >= 3);+ const firstExample = page.locator('.live-example').first();+ await firstExample.locator('.live-run').click();+ await page.waitForFunction(() => document.querySelector('.live-example')?.dataset.ready === 'true');+ assert.equal(await firstExample.locator('.live-status[data-kind=error]').count(), 0);+ await page.evaluate(() => { location.hash = '#getting-started'; });+ await page.waitForURL(/#first-scene$/);const headerBounds = await page.locator('.navigation').boundingBox();const copyBounds = await page.locator('#copy-doc-page').boundingBox();assert.ok(copyBounds.y >= headerBounds.y + headerBounds.height, 'Sticky header covers Copy page');@@ -129,12 +136,12 @@ try {assert.ok(await page.locator('.code-block').count() >= 2);assert.equal(await page.locator('#copy-doc-page').count(), 1);await page.locator('#copy-doc-page').click();- assert.match(await page.evaluate(() => window.__copiedText), /^## Getting started/);+ assert.match(await page.evaluate(() => window.__copiedText), /^# Your first scene/);assert.ok(!(await page.evaluate(() => window.__copiedText)).includes('## Parts and geometry'));const firstCode = page.locator('.code-block').first();await firstCode.locator('.copy-code').click();assert.equal(await page.evaluate(() => window.__copiedText), await firstCode.locator('code').textContent());- report.interactions.push('Grouped docs, selected articles, search, deep links and labeled syntax highlighting');+ report.interactions.push('Grouped docs, start pages, a running live example, old-link aliases, search, deep links and labeled syntax highlighting');}if (route === '/object.html') {await page.locator('[data-view="face"]').click();diff --git a/src/docs-live.js b/src/docs-live.jsnew file mode 100644index 00000000..c5a1e153--- /dev/null+++ b/src/docs-live.js@@ -0,0 +1,276 @@+// Live examples for the documentation: the code beside a small canvas that runs it.+// Each run gets a fresh same-origin iframe, so a loop, a listener or a WebGL context of the last run cannot leak into the+// next one. The iframe imports `67js` through an import map whose entries are small modules that re-export the engine+// this page already loaded, so the docs run the same build as the site and need no published package.+import { highlightCode } from './code-highlight.js';++const addonLoaders = import.meta.glob([+ './gltf.js',+ './modeling.js',+ './hdri.js',+ './canvas2d.js',+ './camera-effects.js',+ './world-material-shader.js',+]);+const moduleCache = new Map();+// One message listener for all examples: each iframe reports by its example id.+const messageHandlers = new Map();+addEventListener('message', event => {+ if (event.origin !== location.origin) return;+ messageHandlers.get(event.data?.docsLive)?.(event.data);+});+const liveModules = {};+window.__docsLiveModules = liveModules;+let nextExampleNumber = 0;++const iconPaths = {+ run: '<path d="m8 5 11 7-11 7V5Z"/>',+ reset: '<path d="M4 12a8 8 0 1 0 2.4-5.7M4 4v4h4"/>',+ copy: '<rect x="8" y="8" width="12" height="13" rx="2"/><path d="M15 8V3H3v12h5"/>',+ check: '<path d="m5 12 5 5 9-10"/>',+ warning: '<path d="M12 3 2 21h20L12 3Zm0 7v5m0 3v.01"/>',+ pause: '<path d="M8 5v14M16 5v14"/>',+};++function icon(name) {+ return `<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" stroke-linecap="round" aria-hidden="true">${iconPaths[name]}</svg>`;+}++function importSpecifiers(source) {+ const specifiers = new Set();+ for (const match of source.matchAll(/\bfrom\s*['"]([^'"]+)['"]/g)) specifiers.add(match[1]);+ for (const match of source.matchAll(/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g)) specifiers.add(match[1]);+ return [...specifiers];+}++function sourceFileFor(specifier) {+ if (specifier === '67js' || specifier === '@codepawlhq/67js') return 'core';+ const addon = specifier.match(/^(?:67js|@codepawlhq\/67js)\/addons\/([\w-]+)$/);+ return addon ? `./${addon[1]}.js` : null;+}++async function loadNamespace(sourceFile) {+ if (!moduleCache.has(sourceFile)) {+ const loader = sourceFile === 'core' ? () => import('./index.js') : addonLoaders[sourceFile];+ if (!loader) throw new Error(`The live example cannot load ${sourceFile.slice(2, -3)}. Copy the code into a local project to use that addon.`);+ moduleCache.set(sourceFile, loader());+ }+ return moduleCache.get(sourceFile);+}++// One re-export module per specifier. Blob URLs are same-origin, so they pass the site's cross-origin isolation headers.+async function importMapFor(source) {+ const imports = {};+ for (const specifier of importSpecifiers(source)) {+ const sourceFile = sourceFileFor(specifier);+ if (!sourceFile) continue;+ const namespace = await loadNamespace(sourceFile);+ liveModules[sourceFile] = namespace;+ const names = Object.keys(namespace).filter(name => name !== 'default' && /^[A-Za-z_$][\w$]*$/.test(name));+ const lines = names.map(name => `export const ${name} = modules[${JSON.stringify(sourceFile)}].${name};`);+ const text = `const modules = window.parent.__docsLiveModules;\n${lines.join('\n')}\n`;+ imports[specifier] = URL.createObjectURL(new Blob([text], { type: 'text/javascript' }));+ }+ return imports;+}++// Capture mode replaces the clock, so the media script can step a loop frame by frame and get the same picture every time.+const captureClock = `+ let virtualTime = 0;+ let queued = [];+ performance.now = () => virtualTime;+ window.requestAnimationFrame = callback => { queued.push(callback); return queued.length; };+ window.cancelAnimationFrame = () => {};+ window.__advance = milliseconds => {+ virtualTime += milliseconds;+ const callbacks = queued;+ queued = [];+ for (const callback of callbacks) callback(virtualTime);+ };`;++function frameDocument(source, imports, exampleId, capture) {+ const importMap = JSON.stringify({ imports }).replace(/</g, '\\u003c');+ const code = source.replace(/<\/script/gi, '<\\/script');+ return `<!doctype html><html><head><meta charset="utf-8">+<style>html,body{margin:0;height:100%;overflow:hidden;background:#101014}#scene{display:block;width:100%;height:100%}</style>+<script type="importmap">${importMap}</script>+<script>+ const report = message => parent.postMessage({ docsLive: ${JSON.stringify(exampleId)}, ...message }, parent.location.origin);+ addEventListener('error', event => report({ error: event.message || 'The example failed.' }));+ addEventListener('unhandledrejection', event => report({ error: String(event.reason?.message ?? event.reason) }));+ ${capture ? captureClock : ''}+</script></head><body><canvas id="scene"></canvas>+<script type="module">${code}</script>+<script type="module">report({ ready: true });</script>+</body></html>`;+}++function releaseFrame(frame) {+ if (!frame) return;+ try {+ frame.contentWindow?.dispatchEvent(new Event('pagehide'));+ const canvas = frame.contentDocument?.querySelector('#scene');+ canvas?.getContext('webgl2')?.getExtension('WEBGL_lose_context')?.loseContext();+ } catch {+ // A frame that never loaded has nothing to release.+ }+ frame.remove();+}++function lineCount(text) {+ return text.split('\n').length;+}++/** Build a live example: a stage with the running scene, a toolbar, and an editor with the highlighted source. */+export function createLiveExample({ source, title, poster, file = 'main.js', aspect = '16 / 9' }) {+ const exampleId = `live-${nextExampleNumber++}`;+ const capture = new URLSearchParams(location.search).has('capture');+ const root = document.createElement('figure');+ root.className = 'live-example';+ root.dataset.example = exampleId;+ if (poster) root.dataset.media = poster;+ root.innerHTML = `+ <div class="live-stage" style="aspect-ratio:${aspect}">+ ${poster ? `<img class="live-poster" src="/docs-media/${poster}.webp" alt="" loading="lazy" decoding="async" onerror="this.remove()">` : ''}+ <button class="live-start" type="button">${icon('run')}Run example</button>+ </div>+ <div class="live-toolbar">+ <span class="live-file">${file}</span>+ <p class="live-status" role="status" aria-live="polite"></p>+ <button class="live-run" type="button" title="Run (Ctrl+Enter)">${icon('run')}Run</button>+ <button class="live-reset" type="button" disabled>${icon('reset')}Reset</button>+ <button class="live-copy" type="button">${icon('copy')}Copy</button>+ </div>+ <div class="live-editor">+ <pre aria-hidden="true"><code class="hljs language-javascript"></code></pre>+ <textarea spellcheck="false" autocapitalize="off" autocomplete="off" aria-label="Editable code for ${title}"></textarea>+ </div>`;+ const stage = root.querySelector('.live-stage');+ const startButton = root.querySelector('.live-start');+ const status = root.querySelector('.live-status');+ const resetButton = root.querySelector('.live-reset');+ const copyButton = root.querySelector('.live-copy');+ const editor = root.querySelector('textarea');+ const highlighted = root.querySelector('.live-editor code');+ editor.value = source;+ let frame = null;+ let running = false;+ let runTimer = 0;+ let runNumber = 0;++ function paintSource() {+ highlighted.innerHTML = `${highlightCode(editor.value, 'javascript')}\n`;+ editor.rows = lineCount(editor.value);+ resetButton.disabled = editor.value === source;+ }++ function setStatus(kind, text) {+ status.dataset.kind = kind;+ status.innerHTML = text ? `${icon(kind === 'error' ? 'warning' : 'check')}<span>${text}</span>` : '';+ }++ async function run() {+ const thisRun = ++runNumber;+ running = true;+ root.classList.add('is-running');+ setStatus('busy', '');+ let imports;+ try {+ imports = await importMapFor(editor.value);+ } catch (error) {+ setStatus('error', error.message);+ return;+ }+ if (thisRun !== runNumber) return;+ releaseFrame(frame);+ for (const url of Object.values(root.dataset.imports ? JSON.parse(root.dataset.imports) : {})) URL.revokeObjectURL(url);+ root.dataset.imports = JSON.stringify(imports);+ frame = document.createElement('iframe');+ frame.className = 'live-frame';+ frame.title = `Result of ${title}`;+ frame.srcdoc = frameDocument(editor.value, imports, exampleId, capture);+ stage.append(frame);+ }++ function stop() {+ runNumber++;+ releaseFrame(frame);+ frame = null;+ running = false;+ root.classList.remove('is-running');+ delete root.dataset.ready;+ setStatus('idle', '');+ }++ messageHandlers.set(exampleId, message => {+ if (message.error) setStatus('error', message.error);+ else if (message.ready && status.dataset.kind !== 'error') {+ setStatus('ok', 'Running');+ root.dataset.ready = 'true';+ }+ });++ startButton.addEventListener('click', run);+ root.querySelector('.live-run').addEventListener('click', run);+ resetButton.addEventListener('click', () => {+ editor.value = source;+ paintSource();+ run();+ });+ copyButton.addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText(editor.value);+ copyButton.innerHTML = `${icon('check')}Copied`;+ } catch {+ editor.focus();+ editor.select();+ copyButton.innerHTML = `${icon('warning')}Select and copy`;+ }+ setTimeout(() => { copyButton.innerHTML = `${icon('copy')}Copy`; }, 2000);+ });+ editor.addEventListener('input', () => {+ paintSource();+ clearTimeout(runTimer);+ if (running) runTimer = setTimeout(run, 700);+ });+ editor.addEventListener('keydown', event => {+ if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {+ event.preventDefault();+ run();+ } else if (event.key === 'Tab' && !event.shiftKey && !event.altKey) {+ event.preventDefault();+ editor.setRangeText(' ', editor.selectionStart, editor.selectionEnd, 'end');+ paintSource();+ }+ });++ // Browsers allow a few WebGL contexts per page, so only examples near the screen keep one.+ const visibility = new IntersectionObserver(entries => {+ for (const entry of entries) {+ if (!entry.isIntersecting && running) stop();+ }+ }, { rootMargin: '400px 0px' });+ visibility.observe(root);+ function dispose() {+ stop();+ visibility.disconnect();+ messageHandlers.delete(exampleId);+ }+ root.liveExample = { run, stop, dispose };+ paintSource();+ return root;+}++/** Start the examples that show on screen, when the reader has not asked for reduced data or motion. */+export function autoRunVisibleExamples(container) {+ if (matchMedia('(prefers-reduced-motion: reduce)').matches || navigator.connection?.saveData) return;+ const starter = new IntersectionObserver(entries => {+ for (const entry of entries) {+ if (!entry.isIntersecting) continue;+ const example = entry.target;+ if (!example.classList.contains('is-running')) example.liveExample.run();+ }+ }, { threshold: 0.35 });+ for (const example of container.querySelectorAll('.live-example')) starter.observe(example);+ return starter;+}diff --git a/src/documentation-topics.js b/src/documentation-topics.jsnew file mode 100644index 00000000..fe546b1f--- /dev/null+++ b/src/documentation-topics.js@@ -0,0 +1,45 @@+// The order of the documentation. The site navigation and the plain-text guide (`/guide.md`) both read it.+// Ids are file names in docs/learn, or slugs of the `## ` headings in docs/guide.md.+export const documentationGroups = [+ { title: 'Start here', icon: 'start', ids: ['introduction', 'install', 'first-scene'] },+ { title: 'Build a scene', icon: 'cube', ids: ['parts-and-geometry', 'materials-and-color', 'cameras-and-framing', 'effects-and-lighting', 'local-lights-and-volume-fog', 'hdr-environment-lighting', 'renderer-reference'] },+ { title: 'Model and fit surfaces', icon: 'cube', ids: ['procedural-modeling', 'sculpt-brushes', 'contact-detection', 'shrinkwrap-and-surface-patches', 'retained-surface-attachments'] },+ { title: 'Worlds', icon: 'world', ids: ['terrain-and-ground-textures', 'trees-and-grass', 'grass-fields', 'wheeled-vehicles', 'baked-liquid'] },+ { title: 'Animate and interact', icon: 'motion', ids: ['deterministic-animation', 'animation-curves-and-mixing', 'skeletal-and-morph-animation', 'humanoid-retargeting-and-crowds', 'recorded-physics', 'assemblies-and-interaction'] },+ { title: 'Assets and media', icon: 'image', ids: ['import-and-export-models', 'images-and-films', 'render-a-png-from-a-script-without-mcp'] },+ { title: 'Reference and workflows', icon: 'book', ids: ['performance-and-memory', 'lifecycle-and-troubleshooting', 'models-and-ai-agents', 'addons-and-limits', 'release-and-source-availability'] },+];++// Old links keep working after the start pages replaced the first sections of the guide.+export const topicAliases = { overview: 'introduction', 'getting-started': 'first-scene' };++export function topicSlug(text) {+ return text.trim().toLowerCase().replace(/`/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');+}++/** Split the guide at its `## ` headings into topics with their exact Markdown. */+export function guideTopics(guide) {+ const headings = [...guide.matchAll(/^## (.+)\r?$/gm)];+ return headings.map((heading, index) => ({+ id: topicSlug(heading[1]),+ title: heading[1].trim(),+ raw: guide.slice(heading.index, headings[index + 1]?.index ?? guide.length),+ }));+}++/** Turn `{ 'path/name.md': text }` into topics, one per learn page. */+export function learnTopics(sources) {+ return Object.entries(sources).map(([path, raw]) => {+ const text = raw.replace(/\r\n/g, '\n');+ return { id: path.match(/([\w-]+)\.md$/)[1], title: text.match(/^# (.+)$/m)[1].trim(), raw: text };+ });+}++/** Every topic in navigation order. A topic that no group lists goes to a "More guides" group, so none is hidden. */+export function orderTopics(topics, groups = documentationGroups) {+ const byId = new Map(topics.map(topic => [topic.id, topic]));+ const listed = new Set(groups.flatMap(group => group.ids));+ const unlisted = [...byId.keys()].filter(id => !listed.has(id));+ const allGroups = unlisted.length ? [...groups, { title: 'More guides', icon: 'book', ids: unlisted }] : groups;+ return { groups: allGroups, topics: allGroups.flatMap(group => group.ids.map(id => byId.get(id)).filter(Boolean)) };+}diff --git a/src/documentation.css b/src/documentation.cssindex 5f7097e8..eead04f2 100644--- a/src/documentation.css+++ b/src/documentation.css@@ -1,5 +1,5 @@.doc-install-link { display:inline-flex; align-items:center; gap:8px; }-.documentation .docs-page { display:grid; grid-template-columns:244px minmax(0,780px); justify-content:center; gap:52px; max-width:1440px; margin-inline:auto; padding:36px 40px 64px; }+.documentation .docs-page { --docs-ok:#7bd88f; --docs-warning:#f2b84b; --docs-tip:#a6c1ff; display:grid; grid-template-columns:244px minmax(0,760px) 196px; justify-content:center; gap:48px; max-width:1440px; margin-inline:auto; padding:36px 40px 64px; }.docs-sidebar { position:sticky; top:calc(var(--navigation-height,80px) + 24px); align-self:start; max-height:calc(100vh - var(--navigation-height,80px) - 48px); overflow-y:auto; padding:0 5px 12px; }.docs-title { display:block; font-size:21px; font-weight:600; letter-spacing:-.5px; margin:5px 0 25px; }.documentation .docs-search { display:block; margin:0; }@@ -24,6 +24,7 @@.documentation .doc-copy-status { margin:0 0 12px; font-size:12px; color:var(--muted); }.doc-copy-status:empty { display:none; }.doc-copy-fallback { width:100%; min-height:160px; margin-bottom:24px; padding:14px; background:var(--bg); color:var(--text); border:1px solid var(--border); border-radius:var(--radius); font:13px/1.6 ui-monospace,Consolas,monospace; }+.documentation #doc-article:focus { outline:none; }.documentation #doc-article section { margin:0; scroll-margin-top:calc(var(--navigation-height,80px) + 72px); }.documentation #doc-article h1 { font-size:clamp(30px,3vw,42px); font-weight:600; letter-spacing:-1.2px; margin:0 0 28px; line-height:1.15; }.documentation #doc-article p { color:var(--text); font-size:15px; line-height:1.8; margin:0 0 23px; }@@ -47,6 +48,7 @@.doc-pagination span { color:var(--muted); font-size:12px; }.doc-pagination strong { font-size:14px; font-weight:500; }.docs-sidebar, .doc-actions, .doc-pagination, .navigation { user-select:none; }+@media (max-width:1279px) { .documentation .docs-page { grid-template-columns:244px minmax(0,780px); } .doc-outline { display:none; } }@media (max-width:1200px) and (min-width:1051px) { .documentation .docs-page { gap:30px; grid-template-columns:220px minmax(0,1fr); padding:30px; } }@media (max-width:1050px) {.documentation .docs-page { display:block; padding:28px 30px 50px; }@@ -84,3 +86,88 @@@media (max-width:760px) {.documentation #doc-article .change-entry { grid-template-columns:minmax(0,1fr); row-gap:2px; padding:11px 0; }}++/* Teaching pages: headings, steps, lists, pictures, callouts, cards and the outline. */+.documentation #doc-article h2 { font-size:24px; font-weight:600; letter-spacing:-.4px; line-height:1.3; margin:52px 0 16px; scroll-margin-top:calc(var(--navigation-height,80px) + 24px); }+.documentation #doc-article h3 { font-size:18px; font-weight:600; margin:36px 0 12px; scroll-margin-top:calc(var(--navigation-height,80px) + 24px); }+.documentation #doc-article h2.doc-step { display:flex; align-items:center; gap:14px; }+.doc-step-number { display:inline-grid; place-items:center; flex:none; width:34px; height:34px; border-radius:10px; background:var(--surface); font-size:15px; font-weight:600; font-variant-numeric:tabular-nums; }+.documentation #doc-article ul { color:var(--text); margin:0 0 26px; padding-left:22px; font-size:15px; line-height:1.75; }+.documentation #doc-article ul li { margin:6px 0; }+.documentation #doc-article li strong, .documentation #doc-article p strong { font-weight:600; }+.doc-figure { margin:28px 0; }+.doc-figure img, .doc-figure video { display:block; width:100%; height:auto; border-radius:var(--panel-radius); background:#101014; }+.doc-figure video { aspect-ratio:16 / 9; object-fit:cover; }+.doc-figure figcaption { margin-top:10px; font-size:13px; color:var(--muted); text-align:center; }+.doc-callout { display:grid; grid-template-columns:20px minmax(0,1fr); gap:12px; align-items:start; margin:24px 0; padding:16px 18px; border-radius:var(--radius); background:var(--bg); }+.doc-callout .icon { width:20px; height:20px; margin-top:3px; }+.doc-callout-tip .icon { color:var(--docs-tip); }+.doc-callout-note .icon { color:var(--muted); }+.doc-callout-warning .icon { color:var(--docs-warning); }+.documentation #doc-article .doc-callout p { margin:0; font-size:14px; line-height:1.7; }+.doc-check { display:flex; align-items:center; gap:10px; margin:0 0 24px; padding:12px 16px; border-radius:var(--radius); background:var(--bg); font-size:14px; }+.doc-check .icon { flex:none; width:20px; height:20px; }+.doc-check-ok .icon { color:var(--docs-ok); }+.doc-check-failed .icon { color:var(--docs-warning); }+.code-language { display:inline-flex; align-items:center; gap:7px; }+.code-language .icon { width:15px; height:15px; }+.code-output pre code { color:var(--muted) !important; }+.install-block { margin:25px 0; }+.install-tabs { display:flex; flex-wrap:wrap; gap:4px; margin:0 0 8px; user-select:none; }+.documentation .install-tabs button { display:inline-flex; align-items:center; gap:8px; min-height:36px; padding:7px 12px; font-size:13px; color:var(--muted); background:transparent; }+.documentation .install-tabs button:hover { color:var(--text); }+.documentation .install-tabs button[aria-pressed=true] { color:var(--text); background:var(--surface); }+.install-tabs .package-logo { width:16px; height:16px; }+.install-block .code-block { margin:0; }+.doc-cards { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; margin:24px 0 32px; }+.documentation #doc-article .doc-card { display:flex; flex-direction:column; gap:6px; padding:16px 18px; border-radius:var(--radius); background:var(--bg); color:var(--text); text-decoration:none; overflow:hidden; transition:background-color var(--site-motion-quick,110ms) ease; }+.documentation #doc-article .doc-card:hover { background:var(--surface); }+.doc-card img { display:block; width:calc(100% + 36px); max-width:none; margin:-16px -18px 8px; aspect-ratio:16 / 9; object-fit:cover; }+.doc-card strong { display:flex; align-items:center; gap:8px; font-size:15px; font-weight:600; }+.doc-card strong .icon { width:16px; height:16px; color:var(--muted); }+.doc-card span { font-size:13px; line-height:1.6; color:var(--muted); }+.doc-cards, .doc-card { user-select:none; }+.doc-outline { position:sticky; top:calc(var(--navigation-height,80px) + 24px); align-self:start; max-height:calc(100vh - var(--navigation-height,80px) - 48px); overflow-y:auto; padding-top:52px; user-select:none; }+.documentation .doc-outline h2 { font-size:13px; font-weight:650; margin:0 0 10px; letter-spacing:0; }+.documentation .doc-outline a { display:block; padding:6px 0; font-size:13px; line-height:1.45; color:var(--muted); text-decoration:none; }+.documentation .doc-outline a:hover { color:var(--text); }++/* Live examples: the result on top, then the toolbar and the editable code. */+.live-example { margin:28px 0 32px; border-radius:var(--panel-radius); background:var(--bg); overflow:hidden; }+.live-stage { position:relative; display:grid; place-items:center; width:100%; background:#101014; overflow:hidden; }+/* Renderer67 shifts the studio view to the right on canvases wider than 700 px, so examples stay at 700 px to keep the subject centred. */+.live-poster, .live-frame { position:absolute; top:0; left:50%; translate:-50% 0; width:min(100%, 700px); height:100%; border:0; }+.live-poster { object-fit:cover; }+.live-frame { background:#101014; }+.documentation .live-start { position:relative; display:inline-flex; align-items:center; gap:8px; min-height:42px; padding:10px 18px; font-size:14px; background:#171717d9; color:var(--text); backdrop-filter:blur(8px); }+.live-start .icon { width:16px; height:16px; }+.live-example.is-running .live-start { visibility:hidden; }+.live-toolbar { display:flex; align-items:center; gap:6px; padding:10px 12px 0 18px; user-select:none; }+.live-file { font:12px ui-monospace,Consolas,monospace; color:var(--muted); }+.documentation .live-status { display:inline-flex; align-items:center; gap:7px; margin:0 auto 0 10px; min-width:0; font-size:12px; line-height:1.4; color:var(--muted); }+.live-status .icon { flex:none; width:15px; height:15px; }+.live-status[data-kind=ok] .icon { color:var(--docs-ok); }+.live-status[data-kind=error] { color:var(--text); }+.live-status[data-kind=error] .icon { color:var(--docs-warning); }+.documentation .live-toolbar button { display:inline-flex; align-items:center; gap:6px; min-height:32px; padding:6px 10px; font-size:12px; background:transparent; color:var(--muted); }+.documentation .live-toolbar button:hover:not(:disabled) { color:var(--text); background:var(--surface); }+.documentation .live-toolbar button:disabled { opacity:.45; cursor:default; }+.live-toolbar .icon { width:14px; height:14px; margin:0; }+.live-editor { position:relative; max-height:440px; overflow:auto; font:13px/1.75 ui-monospace,Consolas,monospace; }+.live-editor pre, .live-editor textarea { margin:0; padding:12px 20px 20px; font:inherit; white-space:pre; tab-size:2; letter-spacing:0; word-spacing:0; }+.documentation .live-editor pre { position:absolute; inset:0 auto auto 0; min-width:100%; border:0; border-radius:0; background:transparent; overflow:visible; pointer-events:none; }+.live-editor pre code { display:block; padding:0; background:transparent; color:var(--text); }+.live-editor textarea { position:relative; display:block; width:100%; min-height:100%; border:0; outline:0; resize:none; overflow:hidden; background:transparent; color:transparent; caret-color:var(--text); -webkit-text-fill-color:transparent; }+.live-editor textarea::selection { background:#a6c1ff40; }+.live-editor:focus-within { box-shadow:inset 0 0 0 2px var(--focus); border-radius:0 0 var(--panel-radius) var(--panel-radius); }++@media (max-width:760px) {+ .doc-cards { grid-template-columns:minmax(0,1fr); }+ .documentation #doc-article h2 { font-size:21px; margin-top:44px; }+ .doc-step-number { width:30px; height:30px; font-size:14px; }+ .live-editor { font-size:12px; max-height:360px; }+ .live-editor pre, .live-editor textarea { padding:10px 14px 16px; }+ .live-toolbar { padding:8px 8px 0 14px; flex-wrap:wrap; }+ .documentation .live-status { order:5; flex-basis:100%; margin:6px 0 0; }+ .documentation .live-status:empty { display:none; }+}diff --git a/src/documentation.js b/src/documentation.jsindex 8c06b622..7a9e5cd2 100644--- a/src/documentation.js+++ b/src/documentation.js@@ -2,9 +2,14 @@ import './home.js';import './documentation.css';import guide from '../docs/guide.md?raw';import { highlightCode } from './code-highlight.js';+import { createLiveExample, autoRunVisibleExamples } from './docs-live.js';+import { topicAliases, topicSlug, guideTopics, learnTopics, orderTopics } from './documentation-topics.js';++const learnSources = import.meta.glob('../docs/learn/*.md', { query: '?raw', import: 'default', eager: true });const article = document.querySelector('#doc-article');const topicNavigation = document.querySelector('#doc-toc');+const pageOutline = document.querySelector('#doc-outline');const search = document.querySelector('#doc-search');const results = document.querySelector('#doc-results');const topicMenu = document.querySelector('#doc-topic-menu');@@ -13,23 +18,22 @@ const copyStatus = document.querySelector('#doc-copy-status');const desktopTopics = matchMedia('(min-width: 1051px)');topicMenu.open = desktopTopics.matches;desktopTopics.addEventListener('change', () => { topicMenu.open = desktopTopics.matches; });-const groups = [- { title: 'Start here', icon: 'start', ids: ['overview', 'install', 'getting-started'] },- { title: 'Build a scene', icon: 'cube', ids: ['parts-and-geometry', 'materials-and-color', 'renderer-reference', 'cameras-and-framing', 'effects-and-lighting', 'local-lights-and-volume-fog'] },- { title: 'Model and fit surfaces', icon: 'cube', ids: ['procedural-modeling', 'sculpt-brushes', 'contact-detection', 'shrinkwrap-and-surface-patches', 'retained-surface-attachments'] },- { title: 'Animate and interact', icon: 'motion', ids: ['deterministic-animation', 'animation-curves-and-mixing', 'skeletal-and-morph-animation', 'recorded-physics', 'assemblies-and-interaction'] },- { title: 'Assets and media', icon: 'image', ids: ['import-and-export-models', 'images-and-films'] },- { title: 'Reference and workflows', icon: 'book', ids: ['performance-and-memory', 'lifecycle-and-troubleshooting', 'models-and-ai-agents', 'addons-and-limits', 'release-and-source-availability'] },-];+const iconPaths = {start: '<path d="m9 5 10 7-10 7V5Z"/>',cube: '<path d="m12 3 9 5v8l-9 5-9-5V8l9-5Z M3 8l9 5 9-5 M12 13v8"/>',+ world: '<circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c3 3 3 15 0 18M12 3c-3 3-3 15 0 18"/>',motion: '<path d="M5 5h14v14H5z M9 9l6 3-6 3V9Z"/>',image: '<rect x="3" y="4" width="18" height="16" rx="3"/><path d="m3 16 5-5 4 4 3-3 6 6"/><circle cx="16" cy="8" r="1"/>',book: '<path d="M12 6c-3-2-6-2-9-1v14c3-1 6-1 9 1 3-2 6-2 9-1V5c-3-1-6-1-9 1Zm0 0v14"/>',copy: '<rect x="8" y="8" width="12" height="13" rx="2"/><path d="M15 8V3H3v12h5"/>',arrow: '<path d="M5 12h14m-6-6 6 6-6 6"/>',chevron: '<path d="m6 9 6 6 6-6"/>',+ tip: '<path d="M9 18h6M10 21h4M12 3a6 6 0 0 0-3.5 10.9c.6.5 1 1.2 1 2.1h5c0-.9.4-1.6 1-2.1A6 6 0 0 0 12 3Z"/>',+ note: '<circle cx="12" cy="12" r="9"/><path d="M12 11v6M12 7.5v.01"/>',+ warning: '<path d="M12 3 2 21h20L12 3Zm0 7v5m0 3v.01"/>',+ check: '<path d="m5 12 5 5 9-10"/>',+ terminal: '<rect x="3" y="4" width="18" height="16" rx="3"/><path d="m7 9 3 3-3 3M13 15h4"/>',};function icon(name) {@@ -40,26 +44,30 @@ function escapeHtml(value) {return value.replace(/[&<>"']/g, character => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[character]));}+function inlineText(value) {+ return escapeHtml(value)+ .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')+ .replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (match, label, href) => {+ const external = /^https?:/.test(href) && !href.startsWith('https://67js.codepawl.com');+ return `<a href="${href}"${external ? ' rel="noopener"' : ''}>${label}</a>`;+ });+}++// Code spans are cut out first, so `**` or `[x](y)` inside code stays literal.function inline(value) {- return escapeHtml(value).replace(/`([^`]+)`/g, '<code>$1</code>').replace(/\[([^\]]+)\]\((\/[^)]+|#[^)]+)\)/g, '<a href="$2">$1</a>');-}--// Keep exact source slices for Copy page, including the Markdown heading.-const headings = [...guide.matchAll(/^## (.+)\r?$/gm)];-const topics = [- { id: 'overview', title: 'About 67js', raw: guide.slice(0, headings[0].index) },- ...headings.map((heading, index) => ({- id: heading[1].trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-$/, ''),- title: heading[1].trim(),- raw: guide.slice(heading.index, headings[index + 1]?.index ?? guide.length),- })),-];+ return value.split(/(`[^`]+`)/g).map(piece => piece.startsWith('`') && piece.endsWith('`') && piece.length > 1+ ? `<code>${escapeHtml(piece.slice(1, -1))}</code>`+ : inlineText(piece)).join('');+}++const { groups, topics } = orderTopics([...guideTopics(guide), ...learnTopics(learnSources)].filter(topic => !(topic.id in topicAliases)));let currentTopic;+let exampleStarter;async function copyText(button, text, code) {try {await navigator.clipboard.writeText(text);- button.innerHTML = `✓ ${code ? 'Copied' : 'Page copied'}`;+ button.innerHTML = `${icon('check')}${code ? 'Copied' : 'Page copied'}`;copyStatus.textContent = `✓ ${code ? 'Code' : 'Page Markdown'} copied to clipboard.`;} catch {if (code) {@@ -87,35 +95,188 @@ async function copyText(button, text, code) {}, 2000);}-function codeBlock(block, title) {- const sourceLanguage = block.match(/^```([^\n\r]*)/)[1].trim();- const language = { js: 'javascript', javascript: 'javascript', html: 'xml', xml: 'xml', sh: 'bash', bash: 'bash' }[sourceLanguage];- const label = { javascript: 'JavaScript', xml: 'HTML', bash: 'Shell' }[language] ?? (sourceLanguage || 'Plain text');- const source = block.replace(/^```[^\n]*\n/, '').replace(/```\s*$/, '').trimEnd();+const languages = { js: 'javascript', javascript: 'javascript', html: 'xml', xml: 'xml', sh: 'bash', bash: 'bash' };+const languageLabels = { javascript: 'JavaScript', xml: 'HTML', bash: 'Shell' };++function fenceInfo(block) {+ const [language = '', ...flags] = block.match(/^```([^\n]*)/)[1].trim().split(/\s+/);+ const options = {};+ for (const flag of flags) {+ const [key, value = true] = flag.split('=');+ options[key] = value;+ }+ return { language, options, source: block.replace(/^```[^\n]*\n/, '').replace(/```\s*$/, '').trimEnd() };+}++function codeBlock({ language: sourceLanguage, options, source }, title) {+ const language = languages[sourceLanguage];+ const label = options.file ?? (sourceLanguage === 'text' ? 'Output' : languageLabels[language] ?? (sourceLanguage || 'Plain text'));const container = document.createElement('div');- container.className = 'code-block';+ container.className = sourceLanguage === 'text' ? 'code-block code-output' : 'code-block';const header = document.createElement('div');header.className = 'code-header';const languageLabel = document.createElement('span');languageLabel.className = 'code-language';- languageLabel.textContent = label;- const button = document.createElement('button');- button.className = 'copy-code';- button.innerHTML = `${icon('copy')}Copy code`;- button.setAttribute('aria-label', `Copy ${label} code from ${title}`);+ languageLabel.innerHTML = sourceLanguage === 'text' ? `${icon('terminal')}${escapeHtml(label)}` : escapeHtml(label);+ header.append(languageLabel);const pre = document.createElement('pre');const code = document.createElement('code');code.className = language ? `hljs language-${language}` : 'hljs';code.innerHTML = language ? highlightCode(source, language) : escapeHtml(source);- button.addEventListener('click', () => copyText(button, source, code));- header.append(languageLabel, button);+ if (sourceLanguage !== 'text') {+ const button = document.createElement('button');+ button.className = 'copy-code';+ button.innerHTML = `${icon('copy')}Copy code`;+ button.setAttribute('aria-label', `Copy ${label} code from ${title}`);+ button.addEventListener('click', () => copyText(button, source, code));+ header.append(button);+ }pre.append(code);container.append(header, pre);return container;}+// `npm install x` becomes one tab per package manager, the same choice the homepage offers.+const packageManagers = [+ { name: 'npm', command: command => command },+ { name: 'pnpm', command: command => command.replace(/^npm install/, 'pnpm add').replace(/^npm create/, 'pnpm create').replace(/^npm run /, 'pnpm ') },+ { name: 'yarn', command: command => command.replace(/^npm install/, 'yarn add').replace(/^npm create/, 'yarn create').replace(/ -- /, ' ').replace(/^npm run /, 'yarn ') },+ { name: 'bun', command: command => command.replace(/^npm install/, 'bun add').replace(/^npm create/, 'bun create').replace(/ -- /, ' ').replace(/^npm run /, 'bun run ') },+];+let chosenPackageManager = 'npm';+try { chosenPackageManager = localStorage.getItem('docs-package-manager') ?? 'npm'; } catch { /* Storage can be blocked. */ }++function installBlock(info, title) {+ const container = document.createElement('div');+ container.className = 'install-block';+ const tabs = document.createElement('div');+ tabs.className = 'install-tabs';+ tabs.setAttribute('role', 'group');+ tabs.setAttribute('aria-label', 'Package manager');+ const holder = document.createElement('div');+ function show(name) {+ const manager = packageManagers.find(entry => entry.name === name) ?? packageManagers[0];+ const source = info.source.split('\n').map(line => manager.command(line)).join('\n');+ holder.replaceChildren(codeBlock({ language: 'sh', options: {}, source }, title));+ for (const button of tabs.children) button.setAttribute('aria-pressed', String(button.dataset.manager === manager.name));+ }+ for (const manager of packageManagers) {+ const button = document.createElement('button');+ button.type = 'button';+ button.dataset.manager = manager.name;+ button.innerHTML = `<span class="package-logo package-logo-${manager.name}" aria-hidden="true"></span>${manager.name}`;+ button.addEventListener('click', () => {+ chosenPackageManager = manager.name;+ try { localStorage.setItem('docs-package-manager', manager.name); } catch { /* Storage can be blocked. */ }+ for (const block of document.querySelectorAll('.install-block')) block.showManager(manager.name);+ });+ tabs.append(button);+ }+ container.showManager = show;+ container.append(tabs, holder);+ show(chosenPackageManager);+ return container;+}++// A card list: one card per line, `Title | link | description | optional picture`.+function cardList(info) {+ const list = document.createElement('div');+ list.className = 'doc-cards';+ for (const line of info.source.split('\n').filter(Boolean)) {+ const [title, href, description = '', picture] = line.split('|').map(part => part.trim());+ const card = document.createElement('a');+ card.className = picture ? 'doc-card has-picture' : 'doc-card';+ card.href = href;+ card.innerHTML = `${picture ? `<img src="${escapeHtml(picture)}" alt="" loading="lazy" decoding="async">` : ''}<strong>${inline(title)} ${icon('arrow')}</strong><span>${inline(description)}</span>`;+ list.append(card);+ }+ return list;+}++function webglCheck() {+ const probe = document.createElement('canvas').getContext('webgl2');+ probe?.getExtension('WEBGL_lose_context')?.loseContext();+ const element = document.createElement('p');+ element.className = probe ? 'doc-check doc-check-ok' : 'doc-check doc-check-failed';+ element.setAttribute('role', 'status');+ element.innerHTML = probe+ ? `${icon('check')}<span>This browser supports WebGL2.</span>`+ : `${icon('warning')}<span>This browser has no WebGL2. Turn on hardware acceleration in its settings, or use a current Chrome, Edge, Firefox or Safari.</span>`;+ return element;+}++function renderFence(block, section) {+ const info = fenceInfo(block);+ if (info.options.live) {+ section.append(createLiveExample({ source: info.source, title: currentTopic.title, poster: info.options.poster, file: info.options.file }));+ } else if (info.options.install) {+ section.append(installBlock(info, currentTopic.title));+ } else if (info.language === 'cards') {+ section.append(cardList(info));+ } else if (info.language === 'check') {+ section.append(webglCheck());+ } else {+ section.append(codeBlock(info, currentTopic.title));+ }+}++function figure(paragraph) {+ const match = paragraph.match(/^!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)$/);+ const [, alt, source, caption] = match;+ const element = document.createElement('figure');+ element.className = 'doc-figure';+ if (/\.(webm|mp4)$/.test(source)) {+ const still = matchMedia('(prefers-reduced-motion: reduce)').matches;+ element.innerHTML = `<video src="${source}" ${still ? 'controls' : 'autoplay loop'} muted playsinline preload="metadata" aria-label="${escapeHtml(alt)}"></video>`;+ } else {+ element.innerHTML = `<img src="${source}" alt="${escapeHtml(alt)}" loading="lazy" decoding="async">`;+ }+ if (caption) element.insertAdjacentHTML('beforeend', `<figcaption>${inline(caption)}</figcaption>`);+ return element;+}++// `> **Tip:** text` becomes a callout that leads with its own icon.+function callout(paragraph) {+ const text = paragraph.split('\n').map(line => line.replace(/^>\s?/, '')).join(' ');+ const kind = text.match(/^\*\*(Tip|Note|Warning):\*\*/)?.[1]?.toLowerCase() ?? 'note';+ const element = document.createElement('aside');+ element.className = `doc-callout doc-callout-${kind}`;+ element.innerHTML = `${icon(kind)}<p>${inline(text)}</p>`;+ return element;+}++function list(paragraph, ordered) {+ const element = document.createElement(ordered ? 'ol' : 'ul');+ const items = paragraph.split(/\n(?=\d+\.\s|[-*]\s)/);+ for (const line of items) {+ const item = document.createElement('li');+ item.innerHTML = inline(line.replace(/^(\d+\.|[-*])\s/, '').replace(/\n\s*/g, ' '));+ element.append(item);+ }+ return element;+}++function heading(paragraph) {+ const [, hashes, text] = paragraph.match(/^(#{2,4})\s+(.+)$/);+ const level = hashes.length;+ const element = document.createElement(`h${level}`);+ const step = level === 2 && text.match(/^(\d+)\.\s+(.+)$/);+ element.id = topicSlug(step ? step[2] : text);+ if (step) {+ element.className = 'doc-step';+ element.innerHTML = `<span class="doc-step-number" aria-hidden="true">${step[1]}</span><span>${inline(step[2])}</span>`;+ element.dataset.outline = step[2];+ } else {+ element.innerHTML = inline(text);+ element.dataset.outline = text;+ }+ return element;+}+function renderParagraph(paragraph, section) {- if (paragraph.startsWith('|')) {+ if (/^#{2,4}\s/.test(paragraph) && !paragraph.includes('\n')) {+ section.append(heading(paragraph));+ } else if (paragraph.startsWith('|')) {const table = document.createElement('table');const rows = paragraph.split('\n').filter(row => !/^\|[\s:|-]+\|$/.test(row));table.innerHTML = rows.map((row, rowIndex) => `<tr>${row.split('|').slice(1, -1).map(cell => `<${rowIndex ? 'td' : 'th'}>${inline(cell.trim())}</${rowIndex ? 'td' : 'th'}>`).join('')}</tr>`).join('');@@ -123,17 +284,17 @@ function renderParagraph(paragraph, section) {scroll.className = 'table-scroll';scroll.append(table);section.append(scroll);+ } else if (/^!\[[^\]]*\]\([^)]+\)$/.test(paragraph)) {+ section.append(figure(paragraph));+ } else if (paragraph.startsWith('>')) {+ section.append(callout(paragraph));} else if (/^\d+\.\s/.test(paragraph)) {- const list = document.createElement('ol');- for (const line of paragraph.split('\n')) {- const item = document.createElement('li');- item.innerHTML = inline(line.replace(/^\d+\.\s/, ''));- list.append(item);- }- section.append(list);+ section.append(list(paragraph, true));+ } else if (/^[-*]\s/.test(paragraph)) {+ section.append(list(paragraph, false));} else {const element = document.createElement('p');- element.innerHTML = inline(paragraph);+ element.innerHTML = inline(paragraph.replace(/\n/g, ' '));section.append(element);}}@@ -147,9 +308,9 @@ function renderNavigation() {if (!members.length) continue;const region = document.createElement('div');region.className = 'doc-topic-group';- const heading = document.createElement('h2');- heading.innerHTML = `${icon(group.icon)}${escapeHtml(group.title)}`;- region.append(heading);+ const groupHeading = document.createElement('h2');+ groupHeading.innerHTML = `${icon(group.icon)}${escapeHtml(group.title)}`;+ region.append(groupHeading);for (const topic of members) {const link = document.createElement('a');link.href = `#${topic.id}`;@@ -166,32 +327,54 @@ function renderNavigation() {results.textContent = words.length ? matching.length ? `${matching.length} ${matching.length === 1 ? 'topic' : 'topics'} found` : '⌕ No matching topics. Try camera, memory, or agents.' : '';}+function renderOutline(section) {+ const headings = [...section.querySelectorAll('h2[id]')];+ pageOutline.replaceChildren();+ pageOutline.hidden = headings.length < 2;+ if (pageOutline.hidden) return;+ const title = document.createElement('h2');+ title.textContent = 'On this page';+ pageOutline.append(title);+ for (const element of headings) {+ const link = document.createElement('a');+ link.href = `#${currentTopic.id}/${element.id}`;+ link.textContent = element.dataset.outline.replace(/`/g, '');+ if (element.classList.contains('doc-step')) link.prepend(`${element.querySelector('.doc-step-number').textContent}. `);+ pageOutline.append(link);+ }+}++function parseHash() {+ const [requestedTopic = '', requestedSection = ''] = decodeURIComponent(location.hash.slice(1)).split('/');+ return { requestedTopic: topicAliases[requestedTopic] ?? requestedTopic, requestedSection };+}++function stopExamples() {+ exampleStarter?.disconnect();+ for (const example of article.querySelectorAll('.live-example')) example.liveExample.dispose();+}+function openTopic(focus = false) {- const requested = location.hash.slice(1);- currentTopic = topics.find(topic => topic.id === requested) ?? topics.find(topic => topic.id === 'install');- if (requested !== currentTopic.id) history.replaceState(null, '', `#${currentTopic.id}`);+ const { requestedTopic, requestedSection } = parseHash();+ const sameTopic = currentTopic && currentTopic.id === requestedTopic;+ if (sameTopic && requestedSection) {+ document.getElementById(requestedSection)?.scrollIntoView({ behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' });+ return;+ }+ stopExamples();+ currentTopic = topics.find(topic => topic.id === requestedTopic) ?? topics.find(topic => topic.id === 'introduction');+ if (requestedTopic !== currentTopic.id) history.replaceState(null, '', `#${currentTopic.id}`);const section = document.createElement('section');section.id = currentTopic.id;- const heading = document.createElement('h1');- heading.textContent = currentTopic.title;- section.append(heading);+ const title = document.createElement('h1');+ title.textContent = currentTopic.title;+ section.append(title);const content = currentTopic.raw.replace(/^#{1,2} [^\n]*\n/, '').trim().replace(/\r\n/g, '\n');- const blocks = content.split(/(```[^\n]*\n[\s\S]*?```)/g);- for (const block of blocks) {- if (block.startsWith('```')) {- section.append(codeBlock(block, currentTopic.title));- } else {- for (const paragraph of block.trim().split(/\n\s*\n/)) {- if (paragraph.trim()) renderParagraph(paragraph, section);- }- }+ for (const block of content.split(/(```[^\n]*\n[\s\S]*?```)/g)) {+ if (block.startsWith('```')) renderFence(block, section);+ else for (const paragraph of block.trim().split(/\n\s*\n/)) if (paragraph.trim()) renderParagraph(paragraph.trim(), section);}article.replaceChildren(section);- if (currentTopic.id === 'install') {- const managerLink = document.createElement('p');- managerLink.innerHTML = `<a class="doc-install-link" href="/#downloads">Install 67js ${icon('arrow')}</a>`;- section.append(managerLink);- }const index = topics.indexOf(currentTopic);const pagination = document.createElement('nav');pagination.className = 'doc-pagination';@@ -200,6 +383,7 @@ function openTopic(focus = false) {if (!topic) continue;const link = document.createElement('a');link.href = `#${topic.id}`;+ link.className = `doc-pagination-${direction.toLowerCase()}`;link.innerHTML = `<span>${direction}</span><strong>${escapeHtml(topic.title)} ${direction === 'Next' ? icon('arrow') : ''}</strong>`;pagination.append(link);}@@ -210,7 +394,11 @@ function openTopic(focus = false) {document.querySelector('.doc-copy-fallback')?.remove();copyPage.innerHTML = `${icon('copy')}Copy page`;renderNavigation();- if (focus) {+ renderOutline(section);+ exampleStarter = autoRunVisibleExamples(article);+ if (requestedSection) {+ requestAnimationFrame(() => document.getElementById(requestedSection)?.scrollIntoView());+ } else if (focus) {article.focus({ preventScroll: true });window.scrollTo({ top: 0 });for (const animation of article.getAnimations()) animation.cancel();diff --git a/tests/docs-pages.test.js b/tests/docs-pages.test.jsnew file mode 100644index 00000000..a1385fe2--- /dev/null+++ b/tests/docs-pages.test.js@@ -0,0 +1,77 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { readFileSync, readdirSync, existsSync } from 'node:fs';+import { fileURLToPath } from 'node:url';++const learnFolder = new URL('../docs/learn/', import.meta.url);+const pages = readdirSync(learnFolder).filter(file => file.endsWith('.md')).map(file => ({+ id: file.slice(0, -3),+ text: readFileSync(new URL(file, learnFolder), 'utf8').replace(/\r\n/g, '\n'),+}));+const guide = readFileSync(new URL('../docs/guide.md', import.meta.url), 'utf8');+const navigation = readFileSync(new URL('../src/documentation-topics.js', import.meta.url), 'utf8');++function slug(text) {+ return text.trim().toLowerCase().replace(/`/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');+}++const topicIds = new Set([+ ...pages.map(page => page.id),+ ...[...guide.matchAll(/^## (.+)$/gm)].map(match => slug(match[1])),+]);++test('each start page has one title and is in the navigation', () => {+ for (const page of pages) {+ assert.equal(page.text.match(/^# /gm)?.length, 1, `${page.id} needs one # title`);+ assert.ok(navigation.includes(`'${page.id}'`), `${page.id} is missing from the navigation groups`);+ }+});++test('every navigation id names a real topic', () => {+ const groupIds = [...navigation.matchAll(/ids: \[([^\]]+)\]/g)].flatMap(match => [...match[1].matchAll(/'([\w-]+)'/g)].map(id => id[1]));+ for (const id of groupIds) assert.ok(topicIds.has(id), `navigation lists ${id}, which has no topic`);+});++test('documentation links to topics and sections resolve', () => {+ for (const page of [...pages, { id: 'guide', text: guide }]) {+ for (const [, target] of page.text.matchAll(/\]\(#([^)\s]+)\)|^[^|\n]+\|\s*#([\w/-]+)/gm)) {+ if (!target) continue;+ const [topic, section] = target.split('/');+ assert.ok(topicIds.has(topic) || ['overview', 'getting-started'].includes(topic), `${page.id} links to #${target}, which has no topic`);+ if (section) {+ const owner = pages.find(entry => entry.id === topic);+ const headings = [...owner.text.matchAll(/^##+ (?:\d+\.\s+)?(.+)$/gm)].map(match => slug(match[1]));+ assert.ok(headings.includes(section), `${page.id} links to #${target}, which has no section`);+ }+ }+ }+});++test('every poster and loop of a live example exists', () => {+ for (const page of pages) {+ for (const [, name] of page.text.matchAll(/^```js live[^\n]*\bposter=([\w-]+)/gm)) {+ assert.ok(existsSync(new URL(`../public/docs-media/${name}.webp`, import.meta.url)), `${page.id}: run npm run docs:media for ${name}.webp`);+ }+ for (const [, file] of page.text.matchAll(/\]\((\/docs-media\/[\w.-]+)/g)) {+ assert.ok(existsSync(new URL(`../public${file}`, import.meta.url)), `${page.id}: ${file} is missing`);+ }+ }+});++test('the plain-text guide holds every topic once, in navigation order', async () => {+ const { plainGuide } = await import('../scripts/plain-guide.mjs');+ const text = await plainGuide(fileURLToPath(new URL('..', import.meta.url)));+ assert.equal(text.match(/^# /gm).length, 1);+ for (const page of pages) assert.ok(text.includes(`## ${page.text.match(/^# (.+)$/m)[1]}\n`), `${page.id} is missing from /guide.md`);+ assert.ok(text.indexOf('## Introduction') < text.indexOf('## Parts and geometry'));+});++test('links to plain-text contracts point at files the site publishes', () => {+ const release = readFileSync(new URL('../scripts/prepare-release.mjs', import.meta.url), 'utf8');+ const published = new Set(['guide.md', 'gltf.md', 'changelog.md', ...[...release.matchAll(/'([\w-]+\.md)'/g)].map(match => match[1])]);+ for (const page of pages) {+ for (const [, file] of page.text.matchAll(/\]\(\/([\w-]+\.md)(?:#[\w-]+)?\)/g)) {+ assert.ok(published.has(file), `${page.id} links to /${file}, which the site does not publish`);+ }+ }+});