spider-paint 26.11.26001 → 26.11.26002

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/MCP.md CHANGED
@@ -166,7 +166,7 @@ A command reaches only viewers that are open: the result's `sent_to` says how ma
166
166
 
167
167
  ### What the person can do in the viewer
168
168
 
169
- Enter: find a target by name. Tab: next target. W/S, A/D, R/F: speed forward, sideways, up. [ / ő and ] / ú: roll. 0 / ö: orbit. Space: stop. Esc: let go. `?` opens the full help (help.md).
169
+ Enter: find a target by name. Tab: next target. W/S, A/D, R/F: speed forward, sideways, up. [ / ő and ] / ú: roll. 0 / ö: orbit. Space: stop. Esc: let go. `?` opens the full help (the `help/` folder: one markdown file a section).
170
170
 
171
171
  ## Tools
172
172
 
package/README.md CHANGED
@@ -68,7 +68,9 @@ J, E, L, N, K, C, 9, Z… The picture is the app's own view in half blocks (roug
68
68
  with the HUD's important bits (EDIT, speed, the target, the object under the cross, fps; a command's answer for a moment)
69
69
  and **the Enter line**, lighter while the Enter box is open (focused): what you type goes into the app's box, its list (the
70
70
  targets, `/l` scenes, `/mat`, `/help`…) covers the bottom of the view, ↑↓ / Tab / Enter / Esc and a click on a row work
71
- as in the app. The mouse is the app's (the cross follows it, drag turns, the wheel zooms; Shift / Option + drag selects
71
+ as in the app; in the edit mode (Q), where Enter builds, cuts or turns, **Shift+Enter** opens the box (the terminal is asked
72
+ for the kitty keyboard protocol so that it can tell Shift+Enter apart; **Alt+Enter** does the same in every terminal).
73
+ **`/q`** (`/quit`) in the box leaves. The mouse is the app's (the cross follows it, drag turns, the wheel zooms; Shift / Option + drag selects
72
74
  terminal text). Ctrl+C quits. On WSL: install a Chrome or Chromium inside Ubuntu, or the native viewer starts.
73
75
 
74
76
  A scene **file** (`.json`, `.3draft`, a sky catalogue, a story) is packed into the page's address, as an MCP link is, and
@@ -82,6 +84,21 @@ every save; also a button in the editor's title bar). Try it from the checkout:
82
84
  press F5 (it uses the checkout's app), or build a `.vsix` (`cd vscode && npm run package`, then
83
85
  `code --install-extension spider-paint-*.vsix`); the *VS Code extension (.vsix)* workflow builds one on every push.
84
86
 
87
+ ### The help and the markdown reader
88
+
89
+ The in-app help is the `help/` folder: `index.md` lists the sections, one markdown file each. `src/md/` reads them
90
+ (no dependencies, its own tests in `tests/md.mjs`, ready to live in a repository of its own): `markdown.js` turns the
91
+ blocks into the smallest HTML or into terminal lines, `highlight.js` colours code blocks and does not stop where the
92
+ languages nest — an ```html block's `<script>` is JavaScript, its `/** jsDoc */` gets its tags, names and `{TypeScript
93
+ types}` coloured, a `<style>` is CSS. The page's help panel and the terminal's help view (`?` in the app view, `/help
94
+ [word]` in the native one) show the same files with the same colours.
95
+
96
+ Markdown in colour on the console, with the same reader: `spider-paint -md file.md` (or `spider-md file.md`,
97
+ `npx spider-md README.md`; `-` reads stdin, `--width N`, `--page` through `less -R`, `--plain` without colours). A code
98
+ file (`.js`, `.html`, `.json`, `.rs`, `.sh`…) is shown as one coloured block. Pictures in the markdown (`![alt](file.png)`, a path
99
+ beside the file or `https://…`) are drawn the way the 3D view is: half blocks, two pixels a cell (`--image-rows N`,
100
+ `--no-images`). PNG and GIF are read in node; JPEG, SVG and WebP go through a headless Chrome when there is one.
101
+
85
102
  ### In Vim / Neovim
86
103
 
87
104
  The checkout is a Vim plugin too (`vim/plugin/spider-paint.vim`):
package/bin/cloud-run.mjs CHANGED
@@ -32,9 +32,9 @@ const types = {
32
32
  const publicFiles = new Set([
33
33
  'index.html', 'player.html', 'emulator.html', 'sky.html',
34
34
  'xr-test.html', 'xr-compare.html', 'workshop.html',
35
- 'favicon.svg', 'manifest.webmanifest', 'sw.js', 'help.md', 'sky.md',
35
+ 'favicon.svg', 'manifest.webmanifest', 'sw.js', 'sky.md',
36
36
  ]);
37
- const publicDirs = new Set(['src', 'engine', 'models', 'media', 'icons', 'app']);
37
+ const publicDirs = new Set(['src', 'engine', 'models', 'media', 'icons', 'app', 'help']);
38
38
  async function serveStatic(req, res, url) {
39
39
  if (req.method !== 'GET' && req.method !== 'HEAD') {
40
40
  res.writeHead(405, { Allow: 'GET, HEAD' }).end();
@@ -0,0 +1,88 @@
1
+ #!/usr/bin/env node
2
+ // Markdown in colour in the terminal (src/md: the same reader and code colours as the help):
3
+ // spider-md file.md [more.md …] [--width N] [--page] (- reads stdin; spider-paint -md file.md does the same)
4
+ // A file that is not markdown (.js, .html, .json, .rs, .sh…) is shown as one coloured code block.
5
+ // Pictures (![alt](file.png), https://…) are drawn in half blocks (--image-rows N, --no-images).
6
+ // --page: through `less -R` when it is longer than the screen. --plain: no colours (a pipe gets them unless asked).
7
+ import { readFileSync, realpathSync } from 'node:fs';
8
+ import { spawnSync } from 'node:child_process';
9
+ import { extname, basename } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { toAnsi, parse, inline } from '../src/md/markdown.js';
12
+ import { dirname, resolve as resolvePath } from 'node:path';
13
+ import { decodeImage, imageLines, closeImages } from './term-image.mjs';
14
+
15
+ const LANG = { '.js': 'js', '.mjs': 'js', '.cjs': 'js', '.jsx': 'js', '.ts': 'ts', '.tsx': 'ts', '.html': 'html', '.htm': 'html', '.svg': 'html', '.xml': 'html', '.css': 'css', '.json': 'json', '.3draft': 'json', '.sh': 'sh', '.bash': 'sh', '.zsh': 'sh', '.rs': 'rust', '.c': 'c', '.h': 'c', '.cpp': 'c', '.go': 'go', '.py': 'python', '.wat': 'wat', '.hexaw': 'wat' };
16
+
17
+ export const mdToTerminal = (text, { file = '', width = 100, images = null, rows = 20 } = {}) => {
18
+ const lang = LANG[extname(file).toLowerCase()];
19
+ const fence = '`'.repeat(Math.max(3, ...[...text.matchAll(/`{3,}/g)].map((m) => m[0].length + 1)));
20
+ const md = lang ? `${fence}${lang}\n${text.replace(/\n$/, '')}\n${fence}` : text;
21
+ const image = images ? (src, alt, cols) => (images.get(src) ? imageLines(images.get(src), { cols, rows }) : null) : null;
22
+ return toAnsi(md, { width, image }).join('\n');
23
+ };
24
+
25
+ // the pictures a markdown text shows: read (a path next to the file, or https://…) and decoded, before the text is laid out
26
+ const picturesOf = (md) => {
27
+ const srcs = new Set();
28
+ const walk = (blocks) => {
29
+ for (const b of blocks) {
30
+ if (b.type === 'p') for (const s of inline(b.text)) if (s.img) srcs.add(s.img);
31
+ if (b.type === 'list') for (const it of b.items) (inline(it.text).forEach((s) => s.img && srcs.add(s.img)), walk(it.children));
32
+ if (b.type === 'quote') walk(b.blocks);
33
+ }
34
+ };
35
+ walk(parse(md));
36
+ return [...srcs];
37
+ };
38
+ export const loadPictures = async (md, file) => {
39
+ const map = new Map();
40
+ for (const src of picturesOf(md)) {
41
+ try {
42
+ let buf;
43
+ if (/^https?:\/\//.test(src)) {
44
+ const r = await fetch(src, { signal: AbortSignal.timeout(8000) });
45
+ if (!r.ok) continue;
46
+ buf = Buffer.from(await r.arrayBuffer());
47
+ } else if (/^data:/.test(src)) buf = Buffer.from(src.split(',')[1] ?? '', /;base64,/.test(src) ? 'base64' : 'utf8');
48
+ else buf = readFileSync(resolvePath(file && file !== '-' ? dirname(file) : '.', decodeURIComponent(src.replace(/[?#].*$/, ''))));
49
+ const img = await decodeImage(buf, src);
50
+ if (img) map.set(src, img);
51
+ } catch {} // (a missing picture keeps its alt text)
52
+ }
53
+ return map;
54
+ };
55
+
56
+ export const run = async (argv = process.argv.slice(2)) => {
57
+ const opt = (n) => {
58
+ const i = argv.indexOf(`--${n}`);
59
+ return i >= 0 ? argv[i + 1] : undefined;
60
+ };
61
+ const files = argv.filter((a, i) => (!a.startsWith('-') || a === '-') && !['--width', '--image-rows'].includes(argv[i - 1]));
62
+ if (!files.length) {
63
+ console.error('spider-md file.md [more.md …] [--width N] [--page] [--plain] (- reads stdin)');
64
+ return 2;
65
+ }
66
+ const width = Math.max(20, Number(opt('width')) || Math.min(process.stdout.columns || 100, 120));
67
+ const pics = !argv.includes('--no-images') && !argv.includes('--plain');
68
+ const rows = Math.max(6, Math.min(Number(opt('image-rows')) || 20, (process.stdout.rows || 40) - 4));
69
+ const parts = [];
70
+ for (const f of files) {
71
+ const text = f === '-' ? readFileSync(0, 'utf8') : readFileSync(f, 'utf8');
72
+ const images = pics && !LANG[extname(f).toLowerCase()] ? await loadPictures(text, f) : null;
73
+ parts.push((files.length > 1 ? `\x1b[2m── ${f === '-' ? 'stdin' : basename(f)} ──\x1b[0m\n` : '') + mdToTerminal(text, { file: f, width, images, rows }));
74
+ }
75
+ await closeImages();
76
+ let out = parts.join('\n\n');
77
+ if (argv.includes('--plain')) out = out.replace(/\x1b\[[0-9;]*m/g, '');
78
+ if (argv.includes('--page') && process.stdout.isTTY && out.split('\n').length > (process.stdout.rows || 0)) {
79
+ const r = spawnSync('less', ['-R'], { input: `${out}\n`, stdio: ['pipe', 'inherit', 'inherit'] });
80
+ if (!r.error) return 0;
81
+ }
82
+ process.stdout.write(`${out}\n`);
83
+ return 0;
84
+ };
85
+
86
+ // run as a command (also through npm's link in node_modules/.bin), not when imported
87
+ const self = (() => { try { return realpathSync(process.argv[1] ?? '') === realpathSync(fileURLToPath(import.meta.url)); } catch { return false; } })();
88
+ if (self) run().then((code) => (process.exitCode = code));
@@ -5,6 +5,9 @@ import { resolve, join, sep, extname, dirname } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { buildInfo } from '../mcp/build-info.js';
7
7
  const root=resolve(dirname(fileURLToPath(import.meta.url)),'..');
8
+ // spider-paint -md file.md: markdown in colour in the terminal (bin/spider-md.mjs), no server
9
+ const mdAt=process.argv.findIndex((a)=>a==='-md'||a==='--md');
10
+ if(mdAt>=0){const {run}=await import('./spider-md.mjs');process.exit(await run(process.argv.slice(2).filter((a,i)=>i!==mdAt-2)));}
8
11
  const port=Number(process.env.PORT || process.argv[2] || 5173);
9
12
  const versionInfo=JSON.stringify(buildInfo);
10
13
  const types={'.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8','.mjs':'text/javascript; charset=utf-8','.json':'application/json; charset=utf-8','.svg':'image/svg+xml','.png':'image/png','.webmanifest':'application/manifest+json','.md':'text/plain; charset=utf-8','.css':'text/css; charset=utf-8','.wasm':'application/wasm'};
@@ -14,6 +14,8 @@ import { merge, bounds } from '../engine/45789c908f86/mesh.js';
14
14
  import { instantiate } from '../engine/45789c908f86/instances.js';
15
15
  import { BUILTIN_MATERIALS } from '../mcp/materials.js';
16
16
  import { rasterize, rasterSky, lookAtAngles, ansiLines, fitZoom } from '../src/term-render.js';
17
+ import { createHelpView } from './term-help.mjs';
18
+ import { helpBlocks, helpSections } from '../src/md/help.js';
17
19
 
18
20
  const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
19
21
  const argv = process.argv.slice(2);
@@ -165,8 +167,9 @@ const draw = () => {
165
167
  paint();
166
168
  }, Math.max(0, 33 - (performance.now() - lastPaint)));
167
169
  };
170
+ let helpView = null, helpOn = false; // the help (/help): text from help/*.md in place of the picture
168
171
  const paint = () => {
169
- const lines = picture();
172
+ const lines = helpOn ? (helpView ??= createHelpView(root)).rows(size().cols, size().rows) : picture();
170
173
  const { rows, cols } = size();
171
174
  let buf = '\x1b[?2026h'; // synchronised output: the terminal shows the frame whole (where it is understood)
172
175
  lines.forEach((l, i) => {
@@ -253,8 +256,27 @@ const run = (text) => {
253
256
  case 'quit':
254
257
  return quit();
255
258
  case 'help':
256
- case 'h':
257
- return note('/l scene · /view front|top|iso… · /spin · /outline · /fit · /zoom n · /ls · /q · a name: turn round that object');
259
+ case 'h': {
260
+ // the help as text; with a word: where it is first said
261
+ helpView ??= createHelpView(root);
262
+ let place = null, file = 'index.md';
263
+ if (arg) {
264
+ const dir = join(root, 'help');
265
+ const read = (f) => (existsSync(join(dir, f)) ? readFileSync(join(dir, f), 'utf8') : '');
266
+ const q = arg.toLowerCase();
267
+ for (const s of [{ file: 'index.md' }, ...helpSections(read('index.md'))]) {
268
+ const b = helpBlocks(read(s.file)).find((x) => x.text.toLowerCase().includes(q));
269
+ if (b) ((file = s.file), (place = { text: b.text.slice(Math.max(0, b.text.toLowerCase().indexOf(q) - 10)) }));
270
+ if (b) break;
271
+ }
272
+ if (!place) note(`"${arg}" is not in the help`);
273
+ }
274
+ helpView.open(file, place);
275
+ helpOn = true;
276
+ return draw();
277
+ }
278
+ case 'keys':
279
+ return note('/l scene · /view front|top|iso… · /spin · /outline · /fit · /zoom n · /ls · /help [word] · /q · a name: turn round that object');
258
280
  default:
259
281
  return note(`no command ${cmd} (/help)`);
260
282
  }
@@ -281,6 +303,11 @@ const cellFace = (x, y) => {
281
303
  return top >= 0 ? top : py + 1 < img.height ? img.ids[(py + 1) * img.width + px] : -1;
282
304
  };
283
305
  const mouse = (b, x, y, release) => {
306
+ if (helpOn) {
307
+ if (b & 64) return helpView.scroll((b & 3) === 0 ? -3 : 3, size().rows), draw();
308
+ if (!(b & 32) && !release && (b & 3) === 0 && y === 1) return helpView.click(x - 1), draw();
309
+ return;
310
+ }
284
311
  const motion = b & 32, button = b & 3, wheel = b & 64;
285
312
  if (wheel) {
286
313
  if (scene.sky) view.fov = Math.max(0.5 * D, Math.min(150 * D, view.fov * (button === 0 ? 1 / 1.12 : 1.12)));
@@ -326,6 +353,15 @@ process.stdin.on('data', (b) => {
326
353
  s = s.replace(/\x1b\[<(\d+);(\d+);(\d+)([Mm])/g, (_, b2, x, y, m) => (mouse(Number(b2), Number(x), Number(y), m === 'm'), ''));
327
354
  if (!s) return;
328
355
  if (s.includes('\x03')) return quit();
356
+ if (helpOn && line.mode !== 'prompt') {
357
+ // the help's keys (Enter still opens the command line)
358
+ if (!/[\r\n]/.test(s)) {
359
+ const k = s === '\x1b' ? 'Escape' : { '\x1b[A': 'ArrowUp', '\x1b[B': 'ArrowDown', '\x1b[C': 'ArrowRight', '\x1b[D': 'ArrowLeft', '\x1b[5~': 'PageUp', '\x1b[6~': 'PageDown', '\x1b[H': 'Home', '\x1b[F': 'End', '\t': 'Tab', '\x1b[Z': 'Tab' }[s] ?? s;
360
+ const r = helpView.key({ key: k, shift: s === '\x1b[Z' }, size().rows);
361
+ if (r === 'close') helpOn = false;
362
+ return draw();
363
+ }
364
+ }
329
365
  if (line.mode !== 'prompt') {
330
366
  const at = s.search(/[\r\n]/);
331
367
  if (at < 0) return; // (zen: no key but Enter)
package/bin/term-app.mjs CHANGED
@@ -11,6 +11,7 @@ import { tmpdir } from 'node:os';
11
11
  import { join, resolve, sep, extname } from 'node:path';
12
12
  import { inflateSync, deflateRawSync } from 'node:zlib';
13
13
  import { ansiLines } from '../src/term-render.js';
14
+ import { createHelpView } from './term-help.mjs';
14
15
 
15
16
  // ---- Chrome: CHROME_PATH, or the usual places
16
17
  export const findChrome = () => {
@@ -80,7 +81,7 @@ const serve = (root) =>
80
81
  });
81
82
 
82
83
  // ---- the DevTools protocol: one WebSocket to the browser, a flat session for the page
83
- const devtools = async (wsUrl) => {
84
+ export const devtools = async (wsUrl) => {
84
85
  const ws = new WebSocket(wsUrl);
85
86
  await new Promise((ok, no) => ((ws.onopen = ok), (ws.onerror = () => no(new Error('no DevTools connection')))));
86
87
  let id = 0;
@@ -111,9 +112,10 @@ const PAGE_STATE = `(() => {
111
112
  return {
112
113
  hud: [...(t('hud')?.querySelectorAll('.row') ?? [])].map(words).filter(Boolean),
113
114
  flight: words(t('flight')),
114
- edit: t('editSw')?.classList.contains('on') ? 'EDIT' + (t('editText')?.textContent.trim() ? ' ' + t('editText').textContent.trim() : '') : '',
115
+ edit: globalThis.__editing?.() ?? null,
115
116
  fps: t('fps')?.textContent ?? '',
116
117
  toast: toast?.isConnected ? toast.textContent : '',
118
+ help: t('helpPanel') && !t('helpPanel').hidden ? { file: globalThis.__helpAt ?? 'index.md', found: globalThis.__helpFound ?? null } : null,
117
119
  find: box && !box.hidden ? { value: t('findInput').value, rows: [...t('findList').children].map((d) => ({ i: d.dataset.i ?? null, sel: d.classList.contains('sel'), left: (d.children[0]?.innerText ?? d.innerText).replace(/\\s+/g, ' ').trim(), right: (d.children[1]?.innerText ?? '').trim() })) } : null,
118
120
  };
119
121
  })()`;
@@ -132,6 +134,20 @@ export const keysOf = (s) => {
132
134
  for (let i = 0; i < s.length; ) {
133
135
  const ch = s[i];
134
136
  if (ch === '\x1b') {
137
+ // a key the terminal reports with its modifiers (the kitty keyboard protocol: ESC [ code ; mods u, or xterm's
138
+ // modifyOtherKeys: ESC [ 27 ; mods ; code ~): Shift+Enter, Ctrl+…, Alt+…, a plain Esc
139
+ const u = /^\x1b\[(\d+)(?::\d*)*(?:;(\d+)(?::\d+)?)?u/.exec(s.slice(i)) ?? /^\x1b\[27;(\d+);(\d+)~/.exec(s.slice(i));
140
+ if (u) {
141
+ const other = u[0].endsWith('~');
142
+ const code = Number(other ? u[2] : u[1]), mods = Math.max(0, Number((other ? u[1] : u[2]) ?? 1) - 1);
143
+ const name = { 13: 'Enter', 27: 'Escape', 9: 'Tab', 127: 'Backspace', 8: 'Backspace', 32: ' ' }[code];
144
+ const shift = Boolean(mods & 1);
145
+ let key = name ?? String.fromCodePoint(code);
146
+ if (!name && shift) key = key.toUpperCase();
147
+ out.push({ key, shift, alt: Boolean(mods & 2), ctrl: Boolean(mods & 4) });
148
+ i += u[0].length;
149
+ continue;
150
+ }
135
151
  const m = /^\x1b(\[[0-9;]*[A-Za-z~]|O[A-D])/.exec(s.slice(i));
136
152
  if (m) {
137
153
  const raw = m[1].replace(/^\[1;(\d)/, '[');
@@ -237,8 +253,9 @@ export const runApp = async ({ root, scene, chrome, url }) => {
237
253
  await page('Runtime.enable');
238
254
 
239
255
  const MOUSE_ON = '\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h', MOUSE_OFF = '\x1b[?1006l\x1b[?1003l\x1b[?1002l\x1b[?1000l';
240
- const RESTORE = `\x1b[0m${MOUSE_OFF}\x1b[?25h\x1b[?1049l`;
241
- out.write(`\x1b[?1049h\x1b[?25l${MOUSE_ON}\x1b[2J`);
256
+ // \x1b[>1u: the kitty keyboard protocol (disambiguate), so Shift+Enter is not plain Enter where the terminal knows it
257
+ const RESTORE = `\x1b[<u\x1b[0m${MOUSE_OFF}\x1b[?25h\x1b[?1049l`;
258
+ out.write(`\x1b[?1049h\x1b[>1u\x1b[?25l${MOUSE_ON}\x1b[2J`);
242
259
  let done = false;
243
260
  const quit = async (code = 0) => {
244
261
  if (done) return;
@@ -263,16 +280,31 @@ export const runApp = async ({ root, scene, chrome, url }) => {
263
280
  // ---- the frame: the picture (the list over it), the info line, the Enter line
264
281
  let shown = [], state = null, listRows = []; // listRows: [{ row (screen line), i }]
265
282
  const fit = (s, n) => (s.length > n ? `${s.slice(0, Math.max(0, n - 1))}…` : s);
283
+ // the help: drawn here as text from help/*.md while the page's help panel is open (the page's section, its /help finds)
284
+ const helpView = createHelpView(root);
285
+ let helpSeen = null;
286
+ const followHelp = (h) => {
287
+ const key = h ? `${h.file}|${h.found?.file ?? ''}|${h.found?.text ?? ''}` : null;
288
+ if (key === helpSeen) return;
289
+ const before = helpSeen;
290
+ helpSeen = key;
291
+ if (!h) return;
292
+ if (h.found && h.found.file === h.file && (!before || !before.endsWith(`|${h.found.text}`))) helpView.open(h.file, { text: h.found.text });
293
+ else helpView.open(h.file);
294
+ };
266
295
  const frame = async () => {
267
- const [shot, st] = await Promise.all([
268
- page('Page.captureScreenshot', { format: 'png', clip: { x: 0, y: 0, width: L.cols * CW, height: L.rows * CH, scale: 1 / CW }, captureBeyondViewport: false }),
269
- page('Runtime.evaluate', { expression: PAGE_STATE, returnByValue: true }).catch(() => null),
270
- ]);
296
+ const st = await page('Runtime.evaluate', { expression: PAGE_STATE, returnByValue: true }).catch(() => null);
271
297
  state = st?.result?.value ?? state;
272
- const img = decodePng(Buffer.from(shot.data, 'base64'));
273
- if (img.width !== L.cols || img.height < L.rows * 2) return; // (a resize is on its way)
274
- img.height = L.rows * 2;
275
- const lines = ansiLines(img);
298
+ followHelp(state?.help);
299
+ let lines;
300
+ if (state?.help) lines = helpView.rows(L.cols, L.rows);
301
+ else {
302
+ const shot = await page('Page.captureScreenshot', { format: 'png', clip: { x: 0, y: 0, width: L.cols * CW, height: L.rows * CH, scale: 1 / CW }, captureBeyondViewport: false });
303
+ const img = decodePng(Buffer.from(shot.data, 'base64'));
304
+ if (img.width !== L.cols || img.height < L.rows * 2) return; // (a resize is on its way)
305
+ img.height = L.rows * 2;
306
+ lines = ansiLines(img);
307
+ }
276
308
  // the Enter box's list, over the bottom of the picture
277
309
  listRows = [];
278
310
  const rows = state?.find?.rows ?? [];
@@ -283,16 +315,21 @@ export const runApp = async ({ root, scene, chrome, url }) => {
283
315
  const right = r.right ? ` ${r.right} ` : ' ';
284
316
  const left = fit(` ${r.left}`, L.cols - right.length);
285
317
  const pad = ' '.repeat(Math.max(0, L.cols - left.length - right.length));
286
- lines[at] = `${r.sel ? '\x1b[0;48;2;57;255;20;38;2;0;0;0' : '\x1b[0;48;2;28;30;34;38;2;220;222;226'}m${left}${pad}\x1b[38;2;${r.sel ? '0;60;0' : '130;134;140'}m${right}\x1b[0m`;
318
+ // (the chosen row in the blue of the target's corner ticks)
319
+ lines[at] = `${r.sel ? '\x1b[0;48;2;77;171;247;38;2;4;20;36' : '\x1b[0;48;2;28;30;34;38;2;220;222;226'}m${left}${pad}\x1b[38;2;${r.sel ? '10;45;80' : '130;134;140'}m${right}\x1b[0m`;
287
320
  if (r.i !== null) listRows.push({ row: at, i: r.i });
288
321
  });
289
322
  }
290
323
  // the info line: the HUD's important bits
291
324
  const s = state ?? {};
292
- const info = s.toast || [s.edit, s.flight, ...(s.hud ?? []).slice(0, 4), /\d/.test(s.fps ?? '') ? s.fps : ''].filter(Boolean).join(' · ');
293
- lines.push(`\x1b[0;48;2;18;18;20;38;2;150;154;160m${fit(` ${info}`, L.cols).padEnd(L.cols)}\x1b[0m`);
325
+ const info = s.toast || [s.flight, ...(s.hud ?? []).slice(0, 4), /\d/.test(s.fps ?? '') ? s.fps : ''].filter(Boolean).join(' · ');
326
+ // in the edit mode (Q) the line starts with a coloured mark, the mode and the model's name
327
+ const mode = s.edit ? { draw: 'draw', vertex: 'points', edge: 'lines', face: 'faces', saw: 'saw', lathe: 'lathe' }[s.edit.mode] ?? s.edit.mode : '';
328
+ const badge = s.edit ? `\x1b[0;1;48;2;241;72;28;38;2;255;255;255m EDIT \x1b[0;48;2;60;24;14;38;2;255;214;190m ${mode} \x1b[0;1;48;2;18;18;20;38;2;240;240;232m ${s.edit.name} ` : '';
329
+ const badgeLen = s.edit ? 6 + mode.length + 2 + s.edit.name.length + 2 : 0;
330
+ lines.push(`${badge}\x1b[0;48;2;18;18;20;38;2;150;154;160m${fit(` ${info}`, Math.max(0, L.cols - badgeLen)).padEnd(Math.max(0, L.cols - badgeLen))}\x1b[0m`);
294
331
  // the Enter line: lighter while the box is open (focused)
295
- const enter = s.find ? `\x1b[0;48;2;62;66;74;38;2;240;240;240m${fit(` › ${s.find.value}`, L.cols).padEnd(L.cols)}\x1b[0m` : `\x1b[0;48;2;30;31;34;38;2;90;94;100m${fit(' Enter: find / commands (/l /s /svg /help …) · Ctrl+C: quit', L.cols).padEnd(L.cols)}\x1b[0m`;
332
+ const enter = s.find ? `\x1b[0;48;2;62;66;74;38;2;240;240;240m${fit(` › ${s.find.value}`, L.cols).padEnd(L.cols)}\x1b[0m` : `\x1b[0;48;2;30;31;34;38;2;90;94;100m${fit(' Enter: find / commands (/l /s /svg /help …) · in Q: Shift+Enter (or Alt+Enter) · /q: quit', L.cols).padEnd(L.cols)}\x1b[0m`;
296
333
  lines.push(enter);
297
334
  let buf = '\x1b[?2026h';
298
335
  lines.forEach((l, i) => {
@@ -319,6 +356,12 @@ export const runApp = async ({ root, scene, chrome, url }) => {
319
356
  const wheel = b & 64, motion = b & 32, btn = b & 3;
320
357
  const mods = (b & 4 ? 8 : 0) | (b & 8 ? 1 : 0) | (b & 16 ? 2 : 0);
321
358
  if (y > L.rows) return; // (the info and Enter lines)
359
+ if (state?.help && !state?.find) {
360
+ // the help view: the wheel scrolls it, a click on the section row changes the section
361
+ if (wheel) return void helpView.scroll(btn === 0 ? -3 : 3, L.rows);
362
+ if (!motion && !release && btn === 0 && y === 1) helpView.click(x - 1);
363
+ return;
364
+ }
322
365
  const at = px(x, y);
323
366
  if (wheel) return page('Input.dispatchMouseEvent', { type: 'mouseWheel', ...at, deltaX: 0, deltaY: btn === 0 ? -120 : 120, modifiers: mods });
324
367
  const name = ['left', 'middle', 'right'][btn] ?? 'none', bit = [1, 4, 2][btn] ?? 0;
@@ -334,10 +377,26 @@ export const runApp = async ({ root, scene, chrome, url }) => {
334
377
  process.stdin.resume();
335
378
  process.stdin.on('data', async (b) => {
336
379
  let s = b.toString();
337
- if (s.includes('\x03')) return quit();
380
+ if (s.includes('\x03') || /\x1b\[99(?::\d*)*;5(?::\d+)?u/.test(s)) return quit(); // Ctrl+C (also as the kitty protocol says it)
338
381
  const events = [];
339
382
  s = s.replace(/\x1b\[<(\d+);(\d+);(\d+)([Mm])/g, (_, b2, x, y, m) => (events.push(() => mouse(Number(b2), Number(x), Number(y), m === 'm')), ''));
340
- for (const k of keysOf(s)) for (const e of keyEvents(k)) events.push(() => page('Input.dispatchKeyEvent', e));
383
+ for (let k of keysOf(s)) {
384
+ // Alt+Enter = Shift+Enter (every terminal tells Alt+Enter apart: ESC Enter): the Enter box in the edit mode (Q) too
385
+ if (k.key === 'Enter' && k.alt) k = { key: 'Enter', shift: true };
386
+ // the help view takes its keys (Enter still opens the box over it)
387
+ if (state?.help && !state?.find && k.key !== 'Enter') {
388
+ const r = helpView.key(k, L.rows);
389
+ if (r === 'close') events.push(() => page('Runtime.evaluate', { expression: "document.getElementById('helpClose')?.click()" }));
390
+ continue;
391
+ }
392
+ // /q, /quit (or /exit) in the Enter box: leave the terminal
393
+ if (k.key === 'Enter' && !k.shift)
394
+ events.push(async () => {
395
+ const r = await page('Runtime.evaluate', { expression: `document.getElementById('findBox')?.hidden === false ? document.getElementById('findInput').value : ''`, returnByValue: true }).catch(() => null);
396
+ if (/^\s*\/(q|quit|exit)\s*$/i.test(r?.result?.value ?? '')) await quit();
397
+ });
398
+ for (const e of keyEvents(k)) events.push(() => page('Input.dispatchKeyEvent', e));
399
+ }
341
400
  for (const e of events) await e().catch(() => {});
342
401
  });
343
402
  out.on('resize', async () => {
@@ -0,0 +1,102 @@
1
+ // The help in a terminal: the help/ folder's markdown drawn as text (src/md: the same files and colours as the page's
2
+ // help panel). A row of the sections on top, the section under it, scrolled with the keys or the wheel.
3
+ // ↑ ↓ (k j) a line · PgUp PgDn (Space) a page · Home End (g G) · ← → (Tab, Shift+Tab, h l) the sections ·
4
+ // a click on a section's name · Esc, ?, q: back to the view
5
+ import { readFileSync, existsSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { toAnsi, visible } from '../src/md/markdown.js';
8
+ import { helpSections } from '../src/md/help.js';
9
+
10
+ const fg = (r, g, b) => `\x1b[38;2;${r};${g};${b}m`;
11
+ const bg = (r, g, b) => `\x1b[48;2;${r};${g};${b}m`;
12
+ const RESET = '\x1b[0m';
13
+ const fold = (s) => s.toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '');
14
+
15
+ export const createHelpView = (root) => {
16
+ const dir = join(root, 'help');
17
+ const read = (f) => (existsSync(join(dir, f)) ? readFileSync(join(dir, f), 'utf8') : `# ${f}\n\nThis section is not there.`);
18
+ const index = read('index.md');
19
+ const sections = [{ file: 'index.md', title: 'Help' }, ...helpSections(index)];
20
+ let at = 0, top = 0, width = 0, lines = [], marks = {}, tabs = [], pending = null;
21
+ const layout = (cols) => {
22
+ if (cols === width && lines.length) return;
23
+ width = cols;
24
+ marks = {};
25
+ lines = toAnsi(read(sections[at].file), { width: Math.max(20, cols - 2), marks }).map((l) => ` ${l}`);
26
+ if (pending) go(pending), (pending = null);
27
+ };
28
+ // to a place: a heading id, or the first line holding some words
29
+ const go = ({ id, text }) => {
30
+ if (id && marks[id] !== undefined) return void (top = Math.max(0, marks[id] - 1));
31
+ if (text) {
32
+ const key = fold(text.replace(/\s+/g, ' ').trim().slice(0, 24));
33
+ const k = lines.findIndex((l) => fold(l.replace(/\x1b\[[0-9;]*m/g, '')).includes(key));
34
+ if (k >= 0) top = Math.max(0, k - 2);
35
+ }
36
+ };
37
+ const view = {
38
+ open(file = 'index.md', place = null) {
39
+ const k = Math.max(0, sections.findIndex((s) => s.file === file));
40
+ if (k !== at || !lines.length) {
41
+ at = k;
42
+ width = 0; // (laid out again at the next draw, then the place is found)
43
+ top = 0;
44
+ pending = place;
45
+ } else if (place) go(place);
46
+ },
47
+ get file() {
48
+ return sections[at].file;
49
+ },
50
+ section(step) {
51
+ at = (at + step + sections.length) % sections.length;
52
+ width = 0;
53
+ top = 0;
54
+ },
55
+ scroll(n, rows) {
56
+ top = Math.max(0, Math.min(Math.max(0, lines.length - rows + 1), top + n));
57
+ },
58
+ /** The rows to draw: the section row, then the text (rows - 1 lines); each at most cols wide. */
59
+ rows(cols, rows) {
60
+ layout(cols);
61
+ // the section row: their names, the current one lit; scrolled so the current one shows
62
+ tabs = [];
63
+ let x = 0, row = '';
64
+ const names = sections.map((s, k) => ` ${s.title.replace(/\s*\(.*\)$/, '')} `);
65
+ let first = 0;
66
+ while (names.slice(first, at + 1).reduce((a, n) => a + n.length + 1, 0) > cols && first < at) first++;
67
+ for (let k = first; k < sections.length && x + names[k].length <= cols; k++) {
68
+ row += (k === at ? `${bg(47, 191, 201)}${fg(4, 24, 26)}\x1b[1m` : `${bg(26, 28, 24)}${fg(150, 154, 146)}`) + names[k] + RESET + ' ';
69
+ tabs.push({ from: x, to: x + names[k].length, k });
70
+ x += names[k].length + 1;
71
+ }
72
+ const out = [`${row}${bg(11, 11, 10)}${' '.repeat(Math.max(0, cols - x))}${RESET}`];
73
+ top = Math.max(0, Math.min(top, Math.max(0, lines.length - (rows - 1) + 1)));
74
+ for (let i = 0; i < rows - 1; i++) {
75
+ const l = lines[top + i] ?? '';
76
+ out.push(`${bg(11, 11, 10)}${l.replaceAll(RESET, RESET + bg(11, 11, 10))}${' '.repeat(Math.max(0, cols - visible(l)))}${RESET}`);
77
+ }
78
+ return out;
79
+ },
80
+ /** A key ({ key, shift }); true when it was the help's, 'close' to leave. */
81
+ key({ key, shift }, rows) {
82
+ const page = Math.max(1, rows - 3);
83
+ if (key === 'Escape' || key === '?' || key === 'q') return 'close';
84
+ if (key === 'ArrowDown' || key === 'j') return view.scroll(1, rows), true;
85
+ if (key === 'ArrowUp' || key === 'k') return view.scroll(-1, rows), true;
86
+ if (key === 'PageDown' || key === ' ') return view.scroll(page, rows), true;
87
+ if (key === 'PageUp') return view.scroll(-page, rows), true;
88
+ if (key === 'Home' || key === 'g') return (top = 0), true;
89
+ if (key === 'End' || key === 'G') return view.scroll(1e9, rows), true;
90
+ if (key === 'ArrowRight' || key === 'l' || (key === 'Tab' && !shift)) return view.section(1), true;
91
+ if (key === 'ArrowLeft' || key === 'h' || (key === 'Tab' && shift)) return view.section(-1), true;
92
+ return false;
93
+ },
94
+ /** A click on the section row (x: 0-based column). */
95
+ click(x) {
96
+ const t = tabs.find((t) => x >= t.from && x < t.to);
97
+ if (t) (at = t.k), (width = 0), (top = 0);
98
+ return Boolean(t);
99
+ },
100
+ };
101
+ return view;
102
+ };