diff --git a/package.json b/package.json index 38eaa8e..188f3b1 100644 --- a/package.json +++ b/package.json @@ -64,7 +64,7 @@ "build": "tsc -p tsconfig.build.json", "typecheck": "tsc -p tsconfig.json", "check": "node scripts/check.ts", - "test": "node --test \"src/kit/*.test.ts\" \"src/kit/recipes/*.test.ts\"", + "test": "node --test \"src/kit/*.test.ts\" \"src/kit/recipes/*.test.ts\" \"src/*.test.ts\"", "test:perf": "KIT_PERF=1 node --test --test-concurrency=1 \"src/kit/*.test.ts\" \"src/kit/recipes/*.test.ts\"", "kit": "node scripts/kit/show.ts", "kit:docs": "node scripts/kit/docs.ts", diff --git a/skills/ascii-rest/references/pieces.md b/skills/ascii-rest/references/pieces.md index 7d234c2..04f9b7b 100644 --- a/skills/ascii-rest/references/pieces.md +++ b/skills/ascii-rest/references/pieces.md @@ -139,7 +139,7 @@ | `command-code` | `commandCode` | canvas | 64×32 | 30 | the command key in a rounded square, glinting now and then | `{"shine":5}` | | `databuddy` | `databuddy` | canvas | 56×28 | 30 | the databuddy bunny, glinting now and then | `{"shine":5}` | | `greptile` | `greptile` | canvas | 49×28 | 30 | the g folded into a cube, in green, glinting now and then | `{"shine":5}` | -| `gta-vi` | `gtaVi` | canvas | 70×24 | 30 | the vi of grand theft auto vi, in pink, glinting now and then | `{"shine":5}` | +| `gta-vi` | `gtaVi` | canvas | 76×32 | 30 | the vi of grand theft auto vi, in a sunset, glinting now and then | `{"shine":5}` | | `helium` | `helium` | canvas | 49×28 | 30 | the six-point asterisk, in blue, glinting now and then | `{"shine":5}` | | `helixdb` | `helixdb` | canvas | 64×32 | 30 | the stepped rungs of a helix between two posts, glinting now and then | `{"shine":5}` | | `helmcode` | `helmcode` | canvas | 53×30 | 30 | the helmcode hexagon in its violet, glinting now and then | `{"shine":5}` | diff --git a/src/mount.test.ts b/src/mount.test.ts new file mode 100644 index 0000000..f1b6c84 --- /dev/null +++ b/src/mount.test.ts @@ -0,0 +1,127 @@ +import { test, type TestContext } from "node:test"; +import assert from "node:assert/strict"; +import type { Env, Piece } from "./types.ts"; + +// Colours "#000000" to "#999999", so the colour a glyph is drawn in says which index it was given. +const palette = Array.from({ length: 10 }, (_, i) => "#" + String(i).repeat(6)); + +// A piece of square cells showing `text(t)`, with `colors` written into env.color. +const piece = (cols: number, rows: number, text: (t: number) => string, colors: number[], fps = 0): Piece => ({ + meta: { name: "test", category: "ui", note: "test", cols, rows, fps, palette, ground: "#000000", cell: 1 }, + default: () => (t: number, env?: Env) => { + env?.color?.set(colors); + return text(t); + }, +}); + +// mount() on a canvas 100px a cell, with the browser stubbed. The atlas records the glyph rasterised into each slot and +// its colour; the canvas records each glyph copied into it, as "glyph colour at column,row+cells", and each cell cleared. +async function onCanvas(t: TestContext, p: Piece) { + const g = globalThis as Record; + const names = ["HTMLCanvasElement", "ResizeObserver", "IntersectionObserver", "document", "devicePixelRatio", "getComputedStyle", "matchMedia", "requestAnimationFrame", "cancelAnimationFrame"]; + const saved = Object.fromEntries(names.map((k) => [k, g[k]])); + const slots = new Map(); + const drawn: string[] = []; + const cleared: string[] = []; + const frames: ((now: number) => void)[] = []; + let seen: ((e: { isIntersecting: boolean }[]) => void) | undefined; + let slot = ""; + class Canvas { + style = {}; + clientWidth = 100 * p.meta.cols; + width = 0; + height = 0; + atlas: boolean; + constructor(atlas = false) { + this.atlas = atlas; + } + getContext() { + if (this.atlas) + return { + fillStyle: "", + rect: (x: number, y: number) => (slot = `${x + 1},${y + 1}`), + fillText(this: { fillStyle: string }, ch: string) { + slots.set(slot, `${ch} ${this.fillStyle}`); + }, + save() {}, + restore() {}, + beginPath() {}, + clip() {}, + clearRect() {}, + }; + return { + fillStyle: "", + fillRect: (x: number, y: number, w: number) => cleared.push(`${x / 100},${y / 100}+${w / 100}`), + clearRect() {}, + drawImage: (_: unknown, sx: number, sy: number, _sw: number, _sh: number, dx: number, dy: number, dw: number) => + drawn.push(`${slots.get(`${sx},${sy}`)} at ${dx / 100},${dy / 100}+${dw / 100}`), + }; + } + } + Object.assign(g, { + HTMLCanvasElement: Canvas, + ResizeObserver: class { + observe() {} + disconnect() {} + }, + IntersectionObserver: class { + constructor(cb: typeof seen) { + seen = cb; + } + observe() {} + disconnect() {} + }, + document: { hidden: false, createElement: () => new Canvas(true), addEventListener() {}, removeEventListener() {} }, + devicePixelRatio: 1, + getComputedStyle: () => ({ color: "rgb(0, 0, 0)" }), + matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }), + requestAnimationFrame: (cb: (now: number) => void) => frames.push(cb), + cancelAnimationFrame: () => {}, + }); + const { mount } = await import("./mount.ts"); + const stop = mount(new Canvas() as unknown as HTMLElement, p); + t.after(() => { + stop(); + Object.assign(g, saved); + }); + return { + drawn, + cleared, + /** Plays the next frame, a tenth of a second on. */ + tick() { + seen?.([{ isIntersecting: true }]); + frames.shift()?.(performance.now() + 100); + }, + }; +} + +test("a canvas draws each character in its own cell's colour, on every row", async (t) => { + const { drawn } = await onCanvas(t, piece(3, 3, () => "abc\ndef\nghi", [0, 1, 2, 3, 4, 5, 6, 7, 8])); + assert.deepEqual( + drawn, + [..."abcdefghi"].map((ch, i) => `${ch} ${palette[i]} at ${i % 3},${Math.floor(i / 3)}+1`), + ); +}); + +test("a full-width character takes two cells, and the characters after it keep their own colours", async (t) => { + // meta.cols counts characters: 新 takes two cells, so the row's last character, a space, does not fit and is dropped. + const { drawn } = await onCanvas(t, piece(4, 2, () => "新AB \nabcd", [1, 2, 3, 4, 5, 6, 7, 8])); + assert.deepEqual(drawn, [ + `新 ${palette[1]} at 0,0+2`, + `A ${palette[2]} at 2,0+1`, + `B ${palette[3]} at 3,0+1`, + `a ${palette[5]} at 0,1+1`, + `b ${palette[6]} at 1,1+1`, + `c ${palette[7]} at 2,1+1`, + `d ${palette[8]} at 3,1+1`, + ]); +}); + +test("a cell a character moves out of is cleared when a wide character before it narrows", async (t) => { + const c = await onCanvas(t, piece(3, 1, (t) => (t ? "aA " : "新A "), [1, 1, 1], 30)); + assert.deepEqual(c.drawn, [`新 ${palette[1]} at 0,0+2`, `A ${palette[1]} at 2,0+1`]); + c.drawn.length = c.cleared.length = 0; + c.tick(); + assert.deepEqual(c.drawn, [`a ${palette[1]} at 0,0+1`, `A ${palette[1]} at 1,0+1`]); + assert.deepEqual(c.cleared, ["0,0+1", "1,0+1", "2,0+1"]); +}); diff --git a/src/mount.ts b/src/mount.ts index 325073b..019c635 100644 --- a/src/mount.ts +++ b/src/mount.ts @@ -18,6 +18,7 @@ * const stop = mount(document.querySelector("pre")!, donut); */ import type { Env, Frame, Meta, Options, Piece } from "./types.ts"; +import { cellWidth } from "./width.ts"; /** * The piece's option overrides, `fps` to override its frame rate, and `motion` @@ -77,11 +78,21 @@ export function mount(el: HTMLElement, piece: Piece | Piece["default"], options: const atlas = document.createElement("canvas"); const actx = atlas.getContext("2d")!; const slots = new Map(); - // A slot is a glyph's box with a pixel of clear space round it, which a cell's rectangle may reach into. - let w = 0, h = 0, sw = 0, sh = 0, pw = 0, ph = 0, width = -1, ink = ""; + // A slot is a glyph's box with a pixel of clear space round it, which a cell's rectangle may reach into. A slot + // holds two cells across, so a full-width character has room for the two it covers. + let w = 0, h = 0, sw = 0, sh = 0, pw = 0, ph = 0, slotW = 0, width = -1, ink = ""; // Each column's and row's whole-pixel edges, and where its glyph's box starts. let xs = new Int32Array(0), ys = new Int32Array(0), gx = new Int32Array(0), gy = new Int32Array(0); - let last = "", full = true; + let full = true; + // What each cell of the canvas shows: the character drawn in it, -1 for a cleared cell, and -2 for the second cell + // of a full-width glyph. Frames are compared cell by cell rather than by string index: a character whose index in + // the string is unchanged still moves to another cell when one before it on the line changes width, and the cell it + // left has to be cleared. + const drawn = new Int32Array(cols * rows).fill(-1); + const next = new Int32Array(cols * rows); + // A piece's colours are indexed by character position, so each is carried to the cell its character is drawn in. + // Reading them by display column would hand a character the colour of one further along the row, past a wide glyph. + const nextColor = color && new Uint8Array(cols * rows); const lastColor = color && new Uint8Array(cols * rows); canvas.style.display ||= "block"; canvas.style.width ||= "100%"; @@ -94,9 +105,10 @@ export function mount(el: HTMLElement, piece: Piece | Piece["default"], options: sh = Math.ceil(h); pw = sw + 2; ph = sh + 2; + slotW = 2 * pw; canvas.width = Math.round(w * cols); canvas.height = Math.round(h * rows); - atlas.width = pw * 32; + atlas.width = slotW * 32; atlas.height = ph * 32; xs = Int32Array.from({ length: cols + 1 }, (_, x) => Math.round(x * w)); ys = Int32Array.from({ length: rows + 1 }, (_, y) => Math.round(y * h)); @@ -106,6 +118,7 @@ export function mount(el: HTMLElement, piece: Piece | Piece["default"], options: full = true; }; const glyph = (code: number, i: number) => { + const cells = cellWidth(code); const key = code * 256 + i; let s = slots.get(key); if (s !== undefined) return s; @@ -114,8 +127,10 @@ export function mount(el: HTMLElement, piece: Piece | Piece["default"], options: slots.clear(); } s = slots.size; - const x = (s % 32) * pw + 1, y = Math.floor(s / 32) * ph + 1; - actx.font = font(w / 0.6); + const x = (s % 32) * slotW + 1, y = Math.floor(s / 32) * ph + 1; + // A glyph is drawn at the size that fills its cells: a monospace face draws an ASCII character 0.6em wide, and a + // full-width one 1em wide, so a wide glyph takes the font size whose 1em spans the two cells it covers. + actx.font = font(cells === 1 ? w / 0.6 : w / 0.5); actx.textAlign = "center"; actx.textBaseline = "middle"; actx.fillStyle = palette ? palette[i] || palette[0] : ink; @@ -123,9 +138,9 @@ export function mount(el: HTMLElement, piece: Piece | Piece["default"], options: // the cells of that slot's glyph would then show. actx.save(); actx.beginPath(); - actx.rect(x - 1, y - 1, pw, ph); + actx.rect(x - 1, y - 1, cells * pw, ph); actx.clip(); - actx.fillText(String.fromCharCode(code), x + sw / 2, y + sh / 2); + actx.fillText(String.fromCharCode(code), x + (cells * sw) / 2, y + sh / 2); actx.restore(); slots.set(key, s); return s; @@ -139,34 +154,59 @@ export function mount(el: HTMLElement, piece: Piece | Piece["default"], options: } const text = frame(t, env()); if (ground) ctx.fillStyle = ground; - if (full) { - if (ground) ctx.fillRect(0, 0, canvas.width, canvas.height); - else ctx.clearRect(0, 0, canvas.width, canvas.height); - } - for (let k = 0, x = 0, y = 0; k < text.length; k++) { + // What this frame puts in each cell, laid out exactly as the draw loop below lays it out. `j` is the character's + // place in its row: env.color holds one colour a character, row by row, with none for the newlines, so its colour + // is at `y * cols + j`. `x` is the display column it is drawn from, which runs ahead of `j` past a wide glyph. + next.fill(-1); + for (let k = 0, j = 0, x = 0, y = 0; k < text.length; k++) { const c = text.charCodeAt(k); if (c === 10) { - x = 0; + x = j = 0; y++; continue; } - const i = y * cols + x; - if (full || c !== last.charCodeAt(k) || (color && color[i] !== lastColor![i])) { - const x0 = xs[x], y0 = ys[y], cw = xs[x + 1] - x0, ch = ys[y + 1] - y0; - if (!full) { - if (ground) ctx.fillRect(x0, y0, cw, ch); - else ctx.clearRect(x0, y0, cw, ch); - } - if (c !== 32) { - const s = glyph(c, color ? color[i] : 0); - // the cell's own rectangle of the glyph's slot, the glyph's box placed where it always sits - ctx.drawImage(atlas, (s % 32) * pw + 1 + x0 - gx[x], Math.floor(s / 32) * ph + 1 + y0 - gy[y], cw, ch, x0, y0, cw, ch); - } + const at = y * cols + j++; + const cells = cellWidth(c); + // `meta.cols` counts characters, so a line carrying wide ones can run past the last column. What does not fit + // is dropped rather than wrapped onto the next row, which would scatter it across cells it never named. + if (x >= cols) { + x += cells; + continue; + } + const span = Math.min(cells, cols - x); + const base = y * cols + x; + next[base] = c; + for (let n = 1; n < span; n++) next[base + n] = -2; + if (color && nextColor) nextColor[base] = color[at]; + x += cells; + } + if (full) { + if (ground) ctx.fillRect(0, 0, canvas.width, canvas.height); + else ctx.clearRect(0, 0, canvas.width, canvas.height); + drawn.fill(-1); + } + for (let i = 0, y = 0, x = 0; i < next.length; i++, (++x === cols) && (x = 0, y++)) { + const c = next[i]; + // The second cell of a wide glyph is covered by the glyph drawn from the cell before it. + if (c === -2) continue; + if (!full && c === drawn[i] && (!color || nextColor![i] === lastColor![i])) continue; + const x0 = xs[x], y0 = ys[y]; + const cells = c === -1 ? 1 : cellWidth(c); + const span = Math.min(cells, cols - x); + const cw = xs[x + span] - x0, ch = ys[y + 1] - y0; + // The cell is cleared before anything is drawn into it, so a glyph that shrank leaves nothing behind. + if (ground) ctx.fillRect(x0, y0, cw, ch); + else ctx.clearRect(x0, y0, cw, ch); + if (c > 32) { + const s = glyph(c, color ? nextColor![i] : 0); + // the cell's own rectangle of the glyph's slot, the glyph's box placed where it always sits. The source is + // the cell's own size, never the slot's padded box: copying `pw` into a cell `cw` wide would scale a narrow + // glyph down and open gaps in box drawing lines that are meant to meet. + ctx.drawImage(atlas, (s % 32) * slotW + 1 + x0 - gx[x], Math.floor(s / 32) * ph + 1 + y0 - gy[y], cw, ch, x0, y0, cw, ch); } - x++; } - last = text; - if (color) lastColor!.set(color); + drawn.set(next); + if (color && nextColor && lastColor) lastColor.set(nextColor); full = false; }; size(); diff --git a/src/width.test.ts b/src/width.test.ts new file mode 100644 index 0000000..c8318de --- /dev/null +++ b/src/width.test.ts @@ -0,0 +1,27 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { cellWidth } from "./width.ts"; + +test("ascii and box drawing take one cell", () => { + for (const ch of ["a", "Z", "0", " ", "[", "+", "\u2500", "\u256d", "\u2591"]) { + assert.equal(cellWidth(ch.charCodeAt(0)), 1, JSON.stringify(ch)); + } +}); + +test("full-width CJK takes two cells", () => { + for (const ch of ["新", "会", "话", "中", "A", "ア", "한"]) { + assert.equal(cellWidth(ch.charCodeAt(0)), 2, JSON.stringify(ch)); + } +}); + +test("the wide ranges' own edges are counted", () => { + assert.equal(cellWidth(0x1100), 2); + assert.equal(cellWidth(0x115f), 2); + assert.equal(cellWidth(0x2e80), 2); + assert.equal(cellWidth(0xac00), 2); + assert.equal(cellWidth(0xf900), 2); + assert.equal(cellWidth(0xff01), 2); + assert.equal(cellWidth(0xff60), 2); + assert.equal(cellWidth(0x10ff), 1); + assert.equal(cellWidth(0xff61), 1); +}); diff --git a/src/width.ts b/src/width.ts new file mode 100644 index 0000000..0daa818 --- /dev/null +++ b/src/width.ts @@ -0,0 +1,27 @@ +/* + * How many cells a character takes on screen. A piece's frame is counted in + * cells, not in characters: a renderer that advanced one cell per character + * would draw a full-width character (CJK) into half a cell and crush every + * glyph after it. + * + * These are East Asian Width's Wide and Fullwidth classes, Basic Multilingual + * Plane only. Characters outside it are two UTF-16 units, which the cell model + * does not carry: a frame's columns are counted in characters. + */ + +/** Cells `code` occupies: 2 when it is drawn full-width, 1 otherwise. */ +export function cellWidth(code: number): 1 | 2 { + return code >= 0x1100 && + (code <= 0x115f || // Hangul Jamo initials + code === 0x2329 || + code === 0x232a || + (code >= 0x2e80 && code <= 0xa4cf && code !== 0x303f) || // CJK radicals through Yi + (code >= 0xac00 && code <= 0xd7a3) || // Hangul syllables + (code >= 0xf900 && code <= 0xfaff) || // CJK compatibility ideographs + (code >= 0xfe10 && code <= 0xfe19) || + (code >= 0xfe30 && code <= 0xfe6f) || + (code >= 0xff00 && code <= 0xff60) || // fullwidth forms + (code >= 0xffe0 && code <= 0xffe6)) + ? 2 + : 1; +}