Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Docs live examples: console output panel, status label fixed, orbit on the introduction cube

Nguyen Xuan Ancf3f868cd98f
diff --git a/changes/docs-live-console.md b/changes/docs-live-console.md
new file mode 100644
index 00000000..89c51205
--- /dev/null
+++ b/changes/docs-live-console.md
@@ -0,0 +1 @@
+- Docs live examples: the status label no longer takes the article's paragraph style (it was 14 px with a 23 px bottom margin, so it sat high and large), each example shows what its `console.log`, `info`, `warn` and `error` print in a small output panel under the picture, and the introduction cube can be dragged to orbit.
diff --git a/docs/learn/introduction.md b/docs/learn/introduction.md
index f13843c1..77de17f6 100644
--- a/docs/learn/introduction.md
+++ b/docs/learn/introduction.md
@@ -2,12 +2,13 @@
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.
+The program below is a complete 67js scene. It runs on this page. Drag the picture to turn the camera. 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');
+canvas.style.touchAction = 'none';
const cube = {
name: 'Cube',
geometry: box(),
@@ -15,9 +16,25 @@ const cube = {
material: { color: [0.85, 0.45, 0.2], metallic: 0, roughness: 0.4 },
};
const renderer = new Renderer67(canvas, [cube]);
+const orbit = { yaw: 0.6, pitch: 0.4, distance: 4.7 };
+
+function draw() {
+ const flat = Math.cos(orbit.pitch) * orbit.distance;
+ const eye = [Math.sin(orbit.yaw) * flat, Math.sin(orbit.pitch) * orbit.distance + 0.5, Math.cos(orbit.yaw) * flat];
+ renderer.render({ eye, target: [0, 0.5, 0] });
+}
+
+// Drag to orbit: each pointer move changes the angles and draws one frame.
+canvas.addEventListener('pointerdown', event => canvas.setPointerCapture(event.pointerId));
+canvas.addEventListener('pointermove', event => {
+ if (!canvas.hasPointerCapture(event.pointerId)) return;
+ orbit.yaw -= event.movementX * 0.01;
+ orbit.pitch = Math.min(1.4, Math.max(0.05, orbit.pitch + event.movementY * 0.01));
+ draw();
+});
new ResizeObserver(() => {
renderer.resize();
- renderer.render({ eye: [2.5, 1.8, 3.5], target: [0, 0.5, 0] });
+ draw();
}).observe(canvas);
```
diff --git a/public/docs-media/introduction-cube.webp b/public/docs-media/introduction-cube.webp
index 480c9afd..1c4e0736 100644
Binary files a/public/docs-media/introduction-cube.webp and b/public/docs-media/introduction-cube.webp differ
diff --git a/src/docs-live.js b/src/docs-live.js
index e04dfe35..9a68752f 100644
--- a/src/docs-live.js
+++ b/src/docs-live.js
@@ -74,6 +74,32 @@ async function importMapFor(source) {
return imports;
}
+// The example's console.log, info, warn and error go to the page as text, so the docs can show what a call returns.
+// Typed arrays print their length and first values; deep objects stop at three levels.
+const consoleRelay = `
+ const formatValue = (value, depth = 0) => {
+ if (typeof value === 'string') return value;
+ if (typeof value === 'number') return String(Math.round(value * 1e4) / 1e4);
+ if (value === null || typeof value !== 'object') return String(value);
+ if (ArrayBuffer.isView(value)) {
+ const head = Array.from(value.slice(0, 6), number => formatValue(number)).join(', ');
+ return value.constructor.name + '(' + value.length + ') [' + head + (value.length > 6 ? ', …' : '') + ']';
+ }
+ if (value instanceof Error) return value.message;
+ if (depth >= 3) return Array.isArray(value) ? '[…]' : '{…}';
+ if (Array.isArray(value)) return '[' + value.slice(0, 20).map(item => formatValue(item, depth + 1)).join(', ') + (value.length > 20 ? ', …' : '') + ']';
+ const entries = Object.entries(value).slice(0, 20).map(([key, item]) => key + ': ' + formatValue(item, depth + 1));
+ return '{ ' + entries.join(', ') + ' }';
+ };
+ for (const level of ['log', 'info', 'warn', 'error']) {
+ const original = console[level].bind(console);
+ console[level] = (...values) => {
+ original(...values);
+ report({ log: { level, text: values.map(value => formatValue(value)).join(' ') } });
+ };
+ }`;
+const CONSOLE_LINE_LIMIT = 200;
+
// 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;
@@ -98,6 +124,7 @@ function frameDocument(source, imports, exampleId, capture) {
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) }));
+ ${consoleRelay}
${capture ? captureClock : ''}
</script></head><body><canvas id="scene"></canvas>
<script type="module">${code}</script>
@@ -134,9 +161,10 @@ export function createLiveExample({ source, title, poster, file = 'main.js', asp
${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>
+ <pre class="live-console" aria-label="Console output" hidden></pre>
<div class="live-toolbar">
<span class="live-file">${file}</span>
- <p class="live-status" role="status" aria-live="polite"></p>
+ <span class="live-status" role="status" aria-live="polite"></span>
<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>
@@ -148,6 +176,7 @@ export function createLiveExample({ source, title, poster, file = 'main.js', asp
const stage = root.querySelector('.live-stage');
const startButton = root.querySelector('.live-start');
const status = root.querySelector('.live-status');
+ const consoleOutput = root.querySelector('.live-console');
const resetButton = root.querySelector('.live-reset');
const copyButton = root.querySelector('.live-copy');
const editor = root.querySelector('textarea');
@@ -174,9 +203,26 @@ export function createLiveExample({ source, title, poster, file = 'main.js', asp
status.append(label);
}
+ function clearConsole() {
+ consoleOutput.replaceChildren();
+ consoleOutput.hidden = true;
+ }
+
+ function appendConsoleLine({ level, text }) {
+ if (consoleOutput.childElementCount >= CONSOLE_LINE_LIMIT) consoleOutput.firstElementChild.remove();
+ const line = document.createElement('span');
+ line.className = 'live-console-line';
+ line.dataset.level = level;
+ line.textContent = text;
+ consoleOutput.append(line);
+ consoleOutput.hidden = false;
+ consoleOutput.scrollTop = consoleOutput.scrollHeight;
+ }
+
async function run() {
const thisRun = ++runNumber;
running = true;
+ clearConsole();
root.classList.add('is-running');
setStatus('busy', '');
let imports;
@@ -208,7 +254,8 @@ export function createLiveExample({ source, title, poster, file = 'main.js', asp
}
messageHandlers.set(exampleId, message => {
- if (message.error) setStatus('error', message.error);
+ if (message.log) appendConsoleLine(message.log);
+ else if (message.error) setStatus('error', message.error);
else if (message.ready && status.dataset.kind !== 'error') {
setStatus('ok', 'Running');
root.dataset.ready = 'true';
diff --git a/src/documentation.css b/src/documentation.css
index 6d6fea2f..2cccd2d1 100644
--- a/src/documentation.css
+++ b/src/documentation.css
@@ -142,6 +142,11 @@
.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; }
+.documentation .live-console { display:block; max-height:140px; margin:0; padding:10px 20px; border:0; border-radius:0; background:#0c0c10; overflow:auto; font:12px/1.6 ui-monospace,Consolas,monospace; color:var(--muted); white-space:pre-wrap; overflow-wrap:anywhere; }
+.documentation .live-console[hidden] { display:none; }
+.live-console-line { display:block; }
+.live-console-line[data-level=warn] { color:var(--docs-warning); }
+.live-console-line[data-level=error] { color:var(--text); }
.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); }