spider-paint 26.11.26001 → 26.11.26003

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,12 @@ 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
+ The text box (Y, or T in Q) is typed on the same bottom line (`text › …`). **The palette (P)** is a text panel on the
74
+ right over the picture: ↑↓ (or the wheel) chooses the material, Tab chooses metal / rough / alpha / emit / soft and ← →
75
+ change it (Shift: five steps), a click takes a material or a place on a value's bar, ✕ / P / Esc close it; Ctrl+click on
76
+ the picture still paints. **`/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
77
  terminal text). Ctrl+C quits. On WSL: install a Chrome or Chromium inside Ubuntu, or the native viewer starts.
73
78
 
74
79
  A scene **file** (`.json`, `.3draft`, a sky catalogue, a story) is packed into the page's address, as an MCP link is, and
@@ -76,26 +81,30 @@ A scene **file** (`.json`, `.3draft`, a sky catalogue, a story) is packed into t
76
81
 
77
82
  ### In VS Code
78
83
 
79
- `vscode/` is a VS Code extension: the app itself in a webview tab (sharp, every key). Commands: **Spider Paint: Open**,
84
+ `vscode/` is a VS Code extension: the app itself in a webview tab (sharp, every key). Commands: **spider-paint: Open**,
80
85
  **Open a scene from the list…**, **Show this scene file in 3D** (the editor's `.json` / `.3draft` beside it, reloaded on
81
86
  every save; also a button in the editor's title bar). Try it from the checkout: open the `vscode` folder in VS Code and
82
87
  press F5 (it uses the checkout's app), or build a `.vsix` (`cd vscode && npm run package`, then
83
88
  `code --install-extension spider-paint-*.vsix`); the *VS Code extension (.vsix)* workflow builds one on every push.
84
89
 
85
- ### In Vim / Neovim
90
+ ### The help and the markdown reader
86
91
 
87
- The checkout is a Vim plugin too (`vim/plugin/spider-paint.vim`):
92
+ The in-app help is the `help/` folder: `index.md` lists the sections, one markdown file each. `src/md/` reads them
93
+ (no dependencies, its own tests in `tests/md.mjs`, ready to live in a repository of its own): `markdown.js` turns the
94
+ blocks into the smallest HTML or into terminal lines, `highlight.js` colours code blocks and does not stop where the
95
+ languages nest — an ```html block's `<script>` is JavaScript, its `/** jsDoc */` gets its tags, names and `{TypeScript
96
+ types}` coloured, a `<style>` is CSS. The page's help panel and the terminal's help view (`?` in the app view, `/help
97
+ [word]` in the native one) show the same files with the same colours.
88
98
 
89
- ```vim
90
- " vim-plug (lazy.nvim: { 'Pengeszikra/Spider-Paint', config = function(p) vim.opt.rtp:append(p.dir .. '/vim') end })
91
- Plug 'Pengeszikra/Spider-Paint', { 'rtp': 'vim', 'do': 'npm install --omit=dev' }
92
- set termguicolors mouse=a
93
- ```
99
+ The same files as one web page: `npm run docs -- --out help.html` (or `--template page.html`, which puts the page
100
+ into a site's own header and footer). The Tüskék és Gyökerek docs page ([`dist/spider-docs.html`](https://github.com/Pengeszikra/tuskek-es-gyokerek/blob/main/dist/spider-docs.html))
101
+ is generated this way, by that site's `spider-docs` workflow, from the current `master`.
94
102
 
95
- `:SpiderPaint` opens spider-paint in a vertical terminal split: the buffer's scene file if it is one (saving it reloads the
96
- view), else the start scene; `:SpiderPaint bridge` a scene of the + scene list; `:SpiderPaint path.json` a file.
97
- `g:spider_paint_split` = `'vertical'` | `'horizontal'` | `'tab'`. In the split every key belongs to spider-paint; Ctrl+W
98
- (Vim) or Ctrl+\ Ctrl+N (Neovim) gets back to the editor, Ctrl+C quits spider-paint. Vim 8.1+ or Neovim, node 22+.
103
+ Markdown in colour on the console, with the same reader: `spider-paint -md file.md` (or `spider-md file.md`,
104
+ `npx spider-md README.md`; `-` reads stdin, `--width N`, `--page` through `less -R`, `--plain` without colours). A code
105
+ file (`.js`, `.html`, `.json`, `.rs`, `.sh`…) is shown as one coloured block. Pictures in the markdown (`![alt](file.png)`, a path
106
+ beside the file or `https://…`) are drawn the way the 3D view is: half blocks, two pixels a cell (`--image-rows N`,
107
+ `--no-images`). PNG and GIF are read in node; JPEG, SVG and WebP go through a headless Chrome when there is one.
99
108
 
100
109
  **The native viewer (`--native`, or when there is no Chrome):** The scene is drawn with 24-bit colour half blocks (two pixels a character cell), a depth buffer and one shaded colour a
101
110
  face (`src/term-render.js`, pure: no node, no DOM), with dark outlines at the silhouettes, folds and depth jumps in place of
@@ -114,7 +123,7 @@ mouse reporting (iTerm2, WezTerm, kitty, Ghostty, Windows Terminal, VS Code; not
114
123
 
115
124
  ## Project boundaries and deployments
116
125
 
117
- - **spider-paint** (`Pengeszikra/spider-paint`) is deployed to Cloud Run only, at `spider-paint.run.app`, and has the `spider-paint` npm package. There is no spider-paint Vercel deployment.
126
+ - **spider-paint** (`Pengeszikra/spider-paint`) is deployed to Cloud Run (`.github/workflows/cloud-run-deploy.yml`) and has the `spider-paint` npm package.
118
127
  - **3Draft** (`Pengeszikra/3Draft`) is the separate 3D engine repository and npm module.
119
128
 
120
129
  The product name is always lowercase **spider-paint**. The app header can retain **3Draft** as a quiet engine attribution.
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,89 @@
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
+ // one character of room on each side: the text is laid out two narrower and every line starts with a space
23
+ return toAnsi(md, { width: Math.max(10, width - 2), image }).map((l) => (l ? ` ${l}` : l)).join('\n');
24
+ };
25
+
26
+ // the pictures a markdown text shows: read (a path next to the file, or https://…) and decoded, before the text is laid out
27
+ const picturesOf = (md) => {
28
+ const srcs = new Set();
29
+ const walk = (blocks) => {
30
+ for (const b of blocks) {
31
+ if (b.type === 'p') for (const s of inline(b.text)) if (s.img) srcs.add(s.img);
32
+ if (b.type === 'list') for (const it of b.items) (inline(it.text).forEach((s) => s.img && srcs.add(s.img)), walk(it.children));
33
+ if (b.type === 'quote') walk(b.blocks);
34
+ }
35
+ };
36
+ walk(parse(md));
37
+ return [...srcs];
38
+ };
39
+ export const loadPictures = async (md, file) => {
40
+ const map = new Map();
41
+ for (const src of picturesOf(md)) {
42
+ try {
43
+ let buf;
44
+ if (/^https?:\/\//.test(src)) {
45
+ const r = await fetch(src, { signal: AbortSignal.timeout(8000) });
46
+ if (!r.ok) continue;
47
+ buf = Buffer.from(await r.arrayBuffer());
48
+ } else if (/^data:/.test(src)) buf = Buffer.from(src.split(',')[1] ?? '', /;base64,/.test(src) ? 'base64' : 'utf8');
49
+ else buf = readFileSync(resolvePath(file && file !== '-' ? dirname(file) : '.', decodeURIComponent(src.replace(/[?#].*$/, ''))));
50
+ const img = await decodeImage(buf, src);
51
+ if (img) map.set(src, img);
52
+ } catch {} // (a missing picture keeps its alt text)
53
+ }
54
+ return map;
55
+ };
56
+
57
+ export const run = async (argv = process.argv.slice(2)) => {
58
+ const opt = (n) => {
59
+ const i = argv.indexOf(`--${n}`);
60
+ return i >= 0 ? argv[i + 1] : undefined;
61
+ };
62
+ const files = argv.filter((a, i) => (!a.startsWith('-') || a === '-') && !['--width', '--image-rows'].includes(argv[i - 1]));
63
+ if (!files.length) {
64
+ console.error('spider-md file.md [more.md …] [--width N] [--page] [--plain] (- reads stdin)');
65
+ return 2;
66
+ }
67
+ const width = Math.max(20, Number(opt('width')) || Math.min(process.stdout.columns || 100, 120));
68
+ const pics = !argv.includes('--no-images') && !argv.includes('--plain');
69
+ const rows = Math.max(6, Math.min(Number(opt('image-rows')) || 20, (process.stdout.rows || 40) - 4));
70
+ const parts = [];
71
+ for (const f of files) {
72
+ const text = f === '-' ? readFileSync(0, 'utf8') : readFileSync(f, 'utf8');
73
+ const images = pics && !LANG[extname(f).toLowerCase()] ? await loadPictures(text, f) : null;
74
+ parts.push((files.length > 1 ? `\x1b[2m── ${f === '-' ? 'stdin' : basename(f)} ──\x1b[0m\n` : '') + mdToTerminal(text, { file: f, width, images, rows }));
75
+ }
76
+ await closeImages();
77
+ let out = parts.join('\n\n');
78
+ if (argv.includes('--plain')) out = out.replace(/\x1b\[[0-9;]*m/g, '');
79
+ if (argv.includes('--page') && process.stdout.isTTY && out.split('\n').length > (process.stdout.rows || 0)) {
80
+ const r = spawnSync('less', ['-R'], { input: `${out}\n`, stdio: ['pipe', 'inherit', 'inherit'] });
81
+ if (!r.error) return 0;
82
+ }
83
+ process.stdout.write(`${out}\n`);
84
+ return 0;
85
+ };
86
+
87
+ // run as a command (also through npm's link in node_modules/.bin), not when imported
88
+ const self = (() => { try { return realpathSync(process.argv[1] ?? '') === realpathSync(fileURLToPath(import.meta.url)); } catch { return false; } })();
89
+ 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
@@ -10,7 +10,9 @@ import { existsSync, readFileSync, watch } from 'node:fs';
10
10
  import { tmpdir } from 'node:os';
11
11
  import { join, resolve, sep, extname } from 'node:path';
12
12
  import { inflateSync, deflateRawSync } from 'node:zlib';
13
- import { ansiLines } from '../src/term-render.js';
13
+ import { cellRows, diffRow } from '../src/term-render.js';
14
+ import { createHelpView } from './term-help.mjs';
15
+ import { createPaletteView } from './term-palette.mjs';
14
16
 
15
17
  // ---- Chrome: CHROME_PATH, or the usual places
16
18
  export const findChrome = () => {
@@ -80,7 +82,7 @@ const serve = (root) =>
80
82
  });
81
83
 
82
84
  // ---- the DevTools protocol: one WebSocket to the browser, a flat session for the page
83
- const devtools = async (wsUrl) => {
85
+ export const devtools = async (wsUrl) => {
84
86
  const ws = new WebSocket(wsUrl);
85
87
  await new Promise((ok, no) => ((ws.onopen = ok), (ws.onerror = () => no(new Error('no DevTools connection')))));
86
88
  let id = 0;
@@ -111,9 +113,12 @@ const PAGE_STATE = `(() => {
111
113
  return {
112
114
  hud: [...(t('hud')?.querySelectorAll('.row') ?? [])].map(words).filter(Boolean),
113
115
  flight: words(t('flight')),
114
- edit: t('editSw')?.classList.contains('on') ? 'EDIT' + (t('editText')?.textContent.trim() ? ' ' + t('editText').textContent.trim() : '') : '',
116
+ edit: globalThis.__editing?.() ?? null,
115
117
  fps: t('fps')?.textContent ?? '',
116
118
  toast: toast?.isConnected ? toast.textContent : '',
119
+ palette: t('palette') && !t('palette').hidden ? globalThis.__palette?.() ?? null : null,
120
+ text: t('textBox') && !t('textBox').hidden ? { value: t('textBox').value, hint: t('textBox').placeholder } : null,
121
+ help: t('helpPanel') && !t('helpPanel').hidden ? { file: globalThis.__helpAt ?? 'index.md', found: globalThis.__helpFound ?? null } : null,
117
122
  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
123
  };
119
124
  })()`;
@@ -122,7 +127,7 @@ const PAGE_STATE = `(() => {
122
127
  const PAGE_CSS = `header.bar, footer.bar, footer.console, #hud, #editbar, #flight, #surface, #zenOff, .build, #cmdToast, #cloudToast { display: none !important; }
123
128
  #stage { position: fixed !important; inset: 0 !important; border: 0 !important; border-radius: 0 !important; z-index: 1; }
124
129
  body { padding: 0 !important; gap: 0 !important; }
125
- #findBox { opacity: 0 !important; pointer-events: none !important; }`;
130
+ #findBox, #textBox, #palette { opacity: 0 !important; pointer-events: none !important; }`;
126
131
 
127
132
  // ---- terminal keys -> DOM key events
128
133
  const VK = { Enter: 13, Escape: 27, Tab: 9, Backspace: 8, Delete: 46, ' ': 32, ArrowLeft: 37, ArrowUp: 38, ArrowRight: 39, ArrowDown: 40, Home: 36, End: 35, PageUp: 33, PageDown: 34 };
@@ -132,6 +137,20 @@ export const keysOf = (s) => {
132
137
  for (let i = 0; i < s.length; ) {
133
138
  const ch = s[i];
134
139
  if (ch === '\x1b') {
140
+ // a key the terminal reports with its modifiers (the kitty keyboard protocol: ESC [ code ; mods u, or xterm's
141
+ // modifyOtherKeys: ESC [ 27 ; mods ; code ~): Shift+Enter, Ctrl+…, Alt+…, a plain Esc
142
+ const u = /^\x1b\[(\d+)(?::\d*)*(?:;(\d+)(?::\d+)?)?u/.exec(s.slice(i)) ?? /^\x1b\[27;(\d+);(\d+)~/.exec(s.slice(i));
143
+ if (u) {
144
+ const other = u[0].endsWith('~');
145
+ const code = Number(other ? u[2] : u[1]), mods = Math.max(0, Number((other ? u[1] : u[2]) ?? 1) - 1);
146
+ const name = { 13: 'Enter', 27: 'Escape', 9: 'Tab', 127: 'Backspace', 8: 'Backspace', 32: ' ' }[code];
147
+ const shift = Boolean(mods & 1);
148
+ let key = name ?? String.fromCodePoint(code);
149
+ if (!name && shift) key = key.toUpperCase();
150
+ out.push({ key, shift, alt: Boolean(mods & 2), ctrl: Boolean(mods & 4) });
151
+ i += u[0].length;
152
+ continue;
153
+ }
135
154
  const m = /^\x1b(\[[0-9;]*[A-Za-z~]|O[A-D])/.exec(s.slice(i));
136
155
  if (m) {
137
156
  const raw = m[1].replace(/^\[1;(\d)/, '[');
@@ -237,8 +256,9 @@ export const runApp = async ({ root, scene, chrome, url }) => {
237
256
  await page('Runtime.enable');
238
257
 
239
258
  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`);
259
+ // \x1b[>1u: the kitty keyboard protocol (disambiguate), so Shift+Enter is not plain Enter where the terminal knows it
260
+ const RESTORE = `\x1b[<u\x1b[0m${MOUSE_OFF}\x1b[?25h\x1b[?1049l`;
261
+ out.write(`\x1b[?1049h\x1b[>1u\x1b[?25l${MOUSE_ON}\x1b[2J`);
242
262
  let done = false;
243
263
  const quit = async (code = 0) => {
244
264
  if (done) return;
@@ -262,17 +282,52 @@ export const runApp = async ({ root, scene, chrome, url }) => {
262
282
 
263
283
  // ---- the frame: the picture (the list over it), the info line, the Enter line
264
284
  let shown = [], state = null, listRows = []; // listRows: [{ row (screen line), i }]
285
+ // shown[i]: what screen line i holds: a string (a text line) or the picture's cells (rows of [code, ch]), so a
286
+ // frame sends only the cells that changed. Inside Vim / Neovim (their :terminal parses every byte, slowly) the
287
+ // colours are rounded a little and the frames are fewer: SPIDER_TERM_QUANT (0–5 bits) and SPIDER_TERM_FPS set them.
288
+ const inEditor = !!(process.env.VIM_TERMINAL || process.env.NVIM);
289
+ const QUANT = Math.max(0, Math.min(5, Number(process.env.SPIDER_TERM_QUANT ?? (inEditor ? 3 : 0)) || 0));
290
+ const FPS = Math.max(1, Math.min(30, Number(process.env.SPIDER_TERM_FPS) || (inEditor ? 10 : 14)));
265
291
  const fit = (s, n) => (s.length > n ? `${s.slice(0, Math.max(0, n - 1))}…` : s);
292
+ // the help: drawn here as text from help/*.md while the page's help panel is open (the page's section, its /help finds)
293
+ const helpView = createHelpView(root);
294
+ const palView = createPaletteView();
295
+ // a change from the palette panel: to the page, and its answer (the palette as it is now) is drawn at once
296
+ const palApply = async (a) => {
297
+ if (a === 'close') return page('Runtime.evaluate', { expression: "document.getElementById('palClose')?.click()" });
298
+ if (a && typeof a === 'object') {
299
+ const r = await page('Runtime.evaluate', { expression: `globalThis.__paletteSet(${JSON.stringify(a)})`, returnByValue: true }).catch(() => null);
300
+ if (state && r?.result?.value) state.palette = r.result.value;
301
+ }
302
+ };
303
+ let helpSeen = null;
304
+ const followHelp = (h) => {
305
+ const key = h ? `${h.file}|${h.found?.file ?? ''}|${h.found?.text ?? ''}` : null;
306
+ if (key === helpSeen) return;
307
+ const before = helpSeen;
308
+ helpSeen = key;
309
+ if (!h) return;
310
+ if (h.found && h.found.file === h.file && (!before || !before.endsWith(`|${h.found.text}`))) helpView.open(h.file, { text: h.found.text });
311
+ else helpView.open(h.file);
312
+ };
266
313
  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
- ]);
314
+ const st = await page('Runtime.evaluate', { expression: PAGE_STATE, returnByValue: true }).catch(() => null);
271
315
  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);
316
+ followHelp(state?.help);
317
+ let lines;
318
+ if (state?.help) lines = helpView.rows(L.cols, L.rows);
319
+ else {
320
+ 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 });
321
+ const img = decodePng(Buffer.from(shot.data, 'base64'));
322
+ if (img.width !== L.cols || img.height < L.rows * 2) return; // (a resize is on its way)
323
+ img.height = L.rows * 2;
324
+ lines = cellRows(img, QUANT);
325
+ // the palette (P): a text panel on the right, over the picture
326
+ if (state?.palette) {
327
+ const { x0, lines: panel } = palView.draw(state.palette, L.cols, L.rows);
328
+ for (const [y, c] of panel) lines[y] = lines[y].slice(0, x0).concat(c);
329
+ }
330
+ }
276
331
  // the Enter box's list, over the bottom of the picture
277
332
  listRows = [];
278
333
  const rows = state?.find?.rows ?? [];
@@ -283,24 +338,40 @@ export const runApp = async ({ root, scene, chrome, url }) => {
283
338
  const right = r.right ? ` ${r.right} ` : ' ';
284
339
  const left = fit(` ${r.left}`, L.cols - right.length);
285
340
  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`;
341
+ // (the chosen row in the blue of the target's corner ticks)
342
+ 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
343
  if (r.i !== null) listRows.push({ row: at, i: r.i });
288
344
  });
289
345
  }
290
346
  // the info line: the HUD's important bits
291
347
  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`);
348
+ const info = s.toast || [s.flight, ...(s.hud ?? []).slice(0, 4), /\d/.test(s.fps ?? '') ? s.fps : ''].filter(Boolean).join(' · ');
349
+ // in the edit mode (Q) the line starts with a coloured mark, the mode and the model's name
350
+ const mode = s.edit ? { draw: 'draw', vertex: 'points', edge: 'lines', face: 'faces', saw: 'saw', lathe: 'lathe' }[s.edit.mode] ?? s.edit.mode : '';
351
+ 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} ` : '';
352
+ const badgeLen = s.edit ? 6 + mode.length + 2 + s.edit.name.length + 2 : 0;
353
+ 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
354
  // 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`;
355
+ // the text box (Y, T in Q): the words being typed, on the same line
356
+ const textLine = (t) => {
357
+ const head = ' text › ';
358
+ const body = fit(t.value || t.hint || '', Math.max(0, L.cols - head.length));
359
+ return `\x1b[0;48;2;62;66;74;38;2;240;240;240m${head}${t.value ? '' : '\x1b[38;2;150;154;160m'}${body}${' '.repeat(Math.max(0, L.cols - head.length - body.length))}\x1b[0m`;
360
+ };
361
+ const enter = s.text
362
+ ? textLine(s.text)
363
+ : 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
364
  lines.push(enter);
297
365
  let buf = '\x1b[?2026h';
298
366
  lines.forEach((l, i) => {
299
- if (shown[i] !== l) buf += `\x1b[${i + 1};1H${l}`;
367
+ if (typeof l === 'string') {
368
+ if (shown[i] !== l) buf += `\x1b[${i + 1};1H${l}`;
369
+ } else buf += diffRow(Array.isArray(shown[i]) ? shown[i] : null, l, i + 1);
300
370
  });
301
371
  shown = lines;
302
- buf += s.find ? `\x1b[${L.rows + 2};${Math.min(L.cols, 4 + s.find.value.length)}H\x1b[?25h` : '\x1b[?25l';
303
- out.write(`${buf}\x1b[?2026l`);
372
+ buf += s.text ? `\x1b[${L.rows + 2};${Math.min(L.cols, 9 + s.text.value.length)}H\x1b[?25h` : s.find ? `\x1b[${L.rows + 2};${Math.min(L.cols, 4 + s.find.value.length)}H\x1b[?25h` : '\x1b[?25l';
373
+ // the terminal decides the pace: while it has not taken the last frame, no new one is made (no lag piles up)
374
+ if (!out.write(`${buf}\x1b[?2026l`)) await new Promise((r) => out.once('drain', r));
304
375
  };
305
376
  const loop = async () => {
306
377
  while (!done) {
@@ -308,7 +379,7 @@ export const runApp = async ({ root, scene, chrome, url }) => {
308
379
  try {
309
380
  await frame();
310
381
  } catch {}
311
- await new Promise((r) => setTimeout(r, Math.max(10, 70 - (performance.now() - t)))); // (~14 frames a second at most)
382
+ await new Promise((r) => setTimeout(r, Math.max(10, 1000 / FPS - (performance.now() - t)))); // (FPS frames a second at most)
312
383
  }
313
384
  };
314
385
 
@@ -319,6 +390,16 @@ export const runApp = async ({ root, scene, chrome, url }) => {
319
390
  const wheel = b & 64, motion = b & 32, btn = b & 3;
320
391
  const mods = (b & 4 ? 8 : 0) | (b & 8 ? 1 : 0) | (b & 16 ? 2 : 0);
321
392
  if (y > L.rows) return; // (the info and Enter lines)
393
+ if (state?.help && !state?.find) {
394
+ // the help view: the wheel scrolls it, a click on the section row changes the section
395
+ if (wheel) return void helpView.scroll(btn === 0 ? -3 : 3, L.rows);
396
+ if (!motion && !release && btn === 0 && y === 1) helpView.click(x - 1);
397
+ return;
398
+ }
399
+ if (state?.palette && !state?.find) {
400
+ const r = palView.mouse(x - 1, y - 1, { press: !motion && !release && btn === 0 && !wheel, wheel: wheel ? (btn === 0 ? -1 : 1) : 0 }, state.palette);
401
+ if (r) return palApply(r);
402
+ }
322
403
  const at = px(x, y);
323
404
  if (wheel) return page('Input.dispatchMouseEvent', { type: 'mouseWheel', ...at, deltaX: 0, deltaY: btn === 0 ? -120 : 120, modifiers: mods });
324
405
  const name = ['left', 'middle', 'right'][btn] ?? 'none', bit = [1, 4, 2][btn] ?? 0;
@@ -334,10 +415,34 @@ export const runApp = async ({ root, scene, chrome, url }) => {
334
415
  process.stdin.resume();
335
416
  process.stdin.on('data', async (b) => {
336
417
  let s = b.toString();
337
- if (s.includes('\x03')) return quit();
418
+ if (s.includes('\x03') || /\x1b\[99(?::\d*)*;5(?::\d+)?u/.test(s)) return quit(); // Ctrl+C (also as the kitty protocol says it)
338
419
  const events = [];
339
420
  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));
421
+ for (let k of keysOf(s)) {
422
+ // Alt+Enter = Shift+Enter (every terminal tells Alt+Enter apart: ESC Enter): the Enter box in the edit mode (Q) too
423
+ if (k.key === 'Enter' && k.alt) k = { key: 'Enter', shift: true };
424
+ // the help view takes its keys (Enter still opens the box over it)
425
+ if (state?.help && !state?.find && k.key !== 'Enter') {
426
+ const r = helpView.key(k, L.rows);
427
+ if (r === 'close') events.push(() => page('Runtime.evaluate', { expression: "document.getElementById('helpClose')?.click()" }));
428
+ continue;
429
+ }
430
+ // the palette panel takes ↑ ↓ ← → Tab (not while a box is open: there they are typing keys)
431
+ if (state?.palette && !state?.find && !state?.text) {
432
+ const r = palView.key(k, state.palette);
433
+ if (r) {
434
+ if (r !== 'draw') events.push(() => palApply(r));
435
+ continue;
436
+ }
437
+ }
438
+ // /q, /quit (or /exit) in the Enter box: leave the terminal
439
+ if (k.key === 'Enter' && !k.shift)
440
+ events.push(async () => {
441
+ const r = await page('Runtime.evaluate', { expression: `document.getElementById('findBox')?.hidden === false ? document.getElementById('findInput').value : ''`, returnByValue: true }).catch(() => null);
442
+ if (/^\s*\/(q|quit|exit)\s*$/i.test(r?.result?.value ?? '')) await quit();
443
+ });
444
+ for (const e of keyEvents(k)) events.push(() => page('Input.dispatchKeyEvent', e));
445
+ }
341
446
  for (const e of events) await e().catch(() => {});
342
447
  });
343
448
  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
+ };