@shadow-garden/bapbong-painter-canvas 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Le Phuoc Minh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,34 @@
1
+ # @shadow-garden/bapbong-painter-canvas
2
+
3
+ Paints a `ResolvedLayout` (from `@shadow-garden/bapbong-layout-engine`) onto
4
+ HTML `<canvas>`. bapbong's core differentiator: the painter consumes
5
+ pre-computed coordinates only — **it never measures text at paint time**.
6
+
7
+ - **Scope:** `scope:painter`
8
+ - **Depends on:** `@shadow-garden/bapbong-contracts`
9
+
10
+ ## What it does
11
+
12
+ - **One `<canvas>` per page** (virtualized): only on-screen pages get a backing
13
+ store, sidestepping the browser's ~65535px max canvas dimension on long docs.
14
+ - Draws text runs, images, tables (borders/shading), floats, footnotes, and
15
+ header/footer chrome; tints commented ranges (skipping resolved threads).
16
+ - `pageToCanvas({ pageIndex, x, y })` maps page coords → container pixels for the
17
+ caret/selection overlay and comment anchors.
18
+
19
+ ```ts
20
+ import { CanvasPainter } from '@shadow-garden/bapbong-painter-canvas';
21
+
22
+ const painter = new CanvasPainter(container, { createCanvas });
23
+ painter.paint(resolvedLayout, { zoom: 1, resolvedComments });
24
+ painter.paintOverlay({ caret, selection }); // caret/selection, no relayout
25
+ ```
26
+
27
+ Also: `PaintOptions`, `PainterDeps`.
28
+
29
+ ## Build / test
30
+
31
+ ```sh
32
+ pnpm nx build @shadow-garden/bapbong-painter-canvas
33
+ pnpm nx test @shadow-garden/bapbong-painter-canvas
34
+ ```
package/dist/index.cjs ADDED
@@ -0,0 +1,550 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // packages/painter-canvas/src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ CanvasPainter: () => CanvasPainter
24
+ });
25
+ module.exports = __toCommonJS(index_exports);
26
+
27
+ // packages/painter-canvas/src/lib/painter-canvas.ts
28
+ var VIEWPORT_MARGIN = 200;
29
+ var POOL_LIMIT = 8;
30
+ var DEFAULTS = {
31
+ zoom: 1,
32
+ pageGap: 24,
33
+ pageBackground: "#ffffff",
34
+ pageBorder: "#c8c8c8",
35
+ tableBorder: "#b0b0b0",
36
+ textColor: "#000000",
37
+ caretColor: "#1a1a1a",
38
+ selectionColor: "rgba(59, 130, 246, 0.30)",
39
+ decorations: []
40
+ };
41
+ var fontCss = (f) => `${f.italic ? "italic " : ""}${f.bold ? "700" : "400"} ${f.sizePt}pt ${f.family}`;
42
+ var defaultDpr = () => typeof globalThis.devicePixelRatio === "number" ? Math.min(globalThis.devicePixelRatio, 2) : 1;
43
+ var CanvasPainter = class {
44
+ constructor(container, deps = {}) {
45
+ this.container = container;
46
+ this.createCanvas = deps.createCanvas ?? (() => document.createElement("canvas"));
47
+ }
48
+ container;
49
+ createCanvas;
50
+ images = /* @__PURE__ */ new Map();
51
+ /** pageIndex → its mounted canvas; idle canvases wait in `pool`. */
52
+ mounted = /* @__PURE__ */ new Map();
53
+ pool = [];
54
+ /** The 2D context of the page currently being drawn (paint* read this). */
55
+ ctx;
56
+ lastLayout = null;
57
+ /** Last paint options, minus caret/selection (those live in lastOverlay). */
58
+ lastOptions = {};
59
+ lastOverlay = {
60
+ caret: null,
61
+ selection: []
62
+ };
63
+ lastFrame = null;
64
+ /** Top edge (layout px) of each page in the stacked document. */
65
+ pageY = [];
66
+ /** Pages currently showing caret/selection (so an overlay change can clear them). */
67
+ overlayPages = /* @__PURE__ */ new Set();
68
+ paint(layout, options = {}) {
69
+ this.lastLayout = layout;
70
+ const { caret, selection, ...rest } = options;
71
+ this.lastOptions = rest;
72
+ if (caret !== void 0 || selection !== void 0) {
73
+ this.lastOverlay = { caret: caret ?? null, selection: selection ?? [] };
74
+ }
75
+ const o = { ...DEFAULTS, ...rest };
76
+ const dpr = options.devicePixelRatio ?? defaultDpr();
77
+ this.lastFrame = { o, dpr };
78
+ const width = layout.pages.reduce((m, p) => Math.max(m, p.width), 0);
79
+ this.pageY = [];
80
+ let acc = 0;
81
+ for (const page of layout.pages) {
82
+ this.pageY.push(acc);
83
+ acc += page.height + o.pageGap;
84
+ }
85
+ const totalHeight = Math.max(0, acc - o.pageGap);
86
+ this.container.style.position ||= "relative";
87
+ this.container.style.width = `${Math.round(width * o.zoom)}px`;
88
+ this.container.style.height = `${Math.round(totalHeight * o.zoom)}px`;
89
+ const vp = options.viewport;
90
+ const vTop = vp ? vp.top / o.zoom - VIEWPORT_MARGIN : -Infinity;
91
+ const vBottom = vp ? (vp.top + vp.height) / o.zoom + VIEWPORT_MARGIN : Infinity;
92
+ const desired = /* @__PURE__ */ new Set();
93
+ layout.pages.forEach((page, i) => {
94
+ const top = this.pageY[i];
95
+ if (top + page.height >= vTop && top <= vBottom) desired.add(i);
96
+ });
97
+ for (const idx of [...this.mounted.keys()]) {
98
+ if (!desired.has(idx)) this.unmountPage(idx);
99
+ }
100
+ this.overlayPages = /* @__PURE__ */ new Set();
101
+ for (const i of desired) this.drawPage(i, o, dpr);
102
+ if (this.lastOverlay.caret) this.overlayPages.add(this.lastOverlay.caret.pageIndex);
103
+ for (const r of this.lastOverlay.selection) this.overlayPages.add(r.pageIndex);
104
+ }
105
+ /** Redraw just the pages whose caret/selection changed — the cheap path for
106
+ * blink and drag (one page for a blink, a handful for a drag). */
107
+ paintOverlay(overlay = {}) {
108
+ this.lastOverlay = { caret: overlay.caret ?? null, selection: overlay.selection ?? [] };
109
+ const frame = this.lastFrame;
110
+ if (!frame || !this.lastLayout) return;
111
+ const next = /* @__PURE__ */ new Set();
112
+ if (this.lastOverlay.caret) next.add(this.lastOverlay.caret.pageIndex);
113
+ for (const r of this.lastOverlay.selection) next.add(r.pageIndex);
114
+ const affected = /* @__PURE__ */ new Set([...this.overlayPages, ...next]);
115
+ this.overlayPages = next;
116
+ for (const i of affected) {
117
+ if (this.mounted.has(i)) this.drawPage(i, frame.o, frame.dpr);
118
+ }
119
+ }
120
+ /** Mount (or reuse) page `i`'s canvas, size + position it, and draw it. */
121
+ drawPage(i, o, dpr) {
122
+ const page = this.lastLayout?.pages[i];
123
+ if (!page) return;
124
+ const slot = this.mountPage(i);
125
+ this.sizeCanvas(slot.canvas, page.width, page.height, o.zoom, dpr);
126
+ slot.canvas.style.top = `${Math.round(this.pageY[i] * o.zoom)}px`;
127
+ this.ctx = slot.ctx;
128
+ this.ctx.setTransform(o.zoom * dpr, 0, 0, o.zoom * dpr, 0, 0);
129
+ this.ctx.clearRect(0, 0, page.width, page.height);
130
+ this.ctx.textBaseline = "alphabetic";
131
+ const pageInfo = { page: page.index + 1, pages: this.lastLayout?.pages.length ?? 1 };
132
+ this.paintPage(page, 0, o, pageInfo);
133
+ for (const chrome of [this.chromeFor(i, "header"), this.chromeFor(i, "footer")]) {
134
+ if (!chrome) continue;
135
+ for (const line of chrome.lines) this.paintLine(line, 0, o, pageInfo);
136
+ for (const table of chrome.tables) this.paintTable(table, 0, o, pageInfo);
137
+ for (const f of chrome.floats ?? []) this.paintFloat(f, 0, o, pageInfo);
138
+ }
139
+ }
140
+ /** Pick the header/footer band for page `i`: the first variant on page 1 when
141
+ * titlePg is set, the even variant on even pages when evenAndOdd is set, else
142
+ * the default. A selected-but-absent variant means a blank band (no fallback
143
+ * to the default — that's Word's behavior for title/even pages). */
144
+ chromeFor(i, kind) {
145
+ const L = this.lastLayout;
146
+ if (!L) return void 0;
147
+ const s = L.chromeSelect;
148
+ const pick = (def, first, even) => {
149
+ if (s?.titlePg && i === 0) return first;
150
+ if (s?.evenAndOdd && (i + 1) % 2 === 0) return even;
151
+ return def;
152
+ };
153
+ return kind === "header" ? pick(L.pageHeader, L.pageHeaderFirst, L.pageHeaderEven) : pick(L.pageFooter, L.pageFooterFirst, L.pageFooterEven);
154
+ }
155
+ /** Get page `i`'s slot, reusing a pooled canvas or creating one. */
156
+ mountPage(i) {
157
+ const existing = this.mounted.get(i);
158
+ if (existing) return existing;
159
+ let slot = this.pool.pop();
160
+ if (!slot) {
161
+ const canvas = this.createCanvas();
162
+ const ctx = canvas.getContext("2d");
163
+ if (!ctx) throw new Error("bapbong-painter-canvas: 2D canvas context unavailable");
164
+ canvas.style.position = "absolute";
165
+ canvas.style.left = "0";
166
+ canvas.style.display = "block";
167
+ canvas.style.pointerEvents = "none";
168
+ slot = { canvas, ctx };
169
+ }
170
+ this.container.appendChild(slot.canvas);
171
+ this.mounted.set(i, slot);
172
+ return slot;
173
+ }
174
+ /** Detach page `i`, freeing its backing store (kept in the pool for reuse). */
175
+ unmountPage(i) {
176
+ const slot = this.mounted.get(i);
177
+ if (!slot) return;
178
+ this.mounted.delete(i);
179
+ slot.canvas.width = 0;
180
+ slot.canvas.height = 0;
181
+ slot.canvas.parentNode?.removeChild(slot.canvas);
182
+ if (this.pool.length < POOL_LIMIT) this.pool.push(slot);
183
+ }
184
+ /** Only resize when needed: assigning width/height — even the same value —
185
+ * clears and reallocates the backing store. */
186
+ sizeCanvas(c, width, height, zoom, dpr) {
187
+ const deviceW = Math.max(1, Math.round(width * zoom * dpr));
188
+ const deviceH = Math.max(1, Math.round(height * zoom * dpr));
189
+ if (c.width !== deviceW) c.width = deviceW;
190
+ if (c.height !== deviceH) c.height = deviceH;
191
+ c.style.width = `${Math.round(width * zoom)}px`;
192
+ c.style.height = `${Math.round(height * zoom)}px`;
193
+ }
194
+ paintPage(page, yOffset, o, pageInfo) {
195
+ const ctx = this.ctx;
196
+ ctx.fillStyle = o.pageBackground;
197
+ ctx.fillRect(0, yOffset, page.width, page.height);
198
+ ctx.strokeStyle = o.pageBorder;
199
+ ctx.lineWidth = 1;
200
+ ctx.strokeRect(0.5, yOffset + 0.5, page.width - 1, page.height - 1);
201
+ for (const f of page.floats ?? []) this.paintFloat(f, yOffset, o, pageInfo);
202
+ ctx.fillStyle = o.selectionColor;
203
+ for (const r of this.lastOverlay.selection) {
204
+ if (r.pageIndex === page.index) ctx.fillRect(r.x, yOffset + r.y, r.width, r.height);
205
+ }
206
+ for (const d of o.decorations) {
207
+ if (d.kind !== "background") continue;
208
+ ctx.fillStyle = d.color;
209
+ for (const r of d.rects) {
210
+ if (r.pageIndex === page.index) ctx.fillRect(r.x, yOffset + r.y, r.width, r.height);
211
+ }
212
+ }
213
+ for (const line of page.lines) this.paintLine(line, yOffset, o, pageInfo);
214
+ for (const table of page.tables ?? []) this.paintTable(table, yOffset, o, pageInfo);
215
+ for (const d of o.decorations) {
216
+ if (d.kind === "background") continue;
217
+ ctx.fillStyle = d.color;
218
+ for (const r of d.rects) {
219
+ if (r.pageIndex !== page.index) continue;
220
+ const thickness = Math.max(1, r.height * 0.06);
221
+ const y = d.kind === "underline" ? yOffset + r.y + r.height - thickness : yOffset + r.y + r.height / 2;
222
+ ctx.fillRect(r.x, y, r.width, thickness);
223
+ }
224
+ }
225
+ if (page.footnotes) {
226
+ const fn = page.footnotes;
227
+ const startX = fn.lines[0]?.x ?? 0;
228
+ const sepY = Math.round(yOffset + fn.separatorY) + 0.5;
229
+ ctx.strokeStyle = o.pageBorder;
230
+ ctx.lineWidth = 1;
231
+ ctx.beginPath();
232
+ ctx.moveTo(startX, sepY);
233
+ ctx.lineTo(startX + Math.min(192, page.width * 0.3), sepY);
234
+ ctx.stroke();
235
+ for (const line of fn.lines) this.paintLine(line, yOffset, o, pageInfo);
236
+ }
237
+ const caret = this.lastOverlay.caret;
238
+ if (caret && caret.pageIndex === page.index) {
239
+ ctx.fillStyle = o.caretColor;
240
+ ctx.fillRect(caret.x, yOffset + caret.y, 1.5, caret.height);
241
+ }
242
+ }
243
+ /** Run `draw` rotated `deg` clockwise around the center of the given box —
244
+ * the paint-only rotation of images/shapes (the layout box stays put). */
245
+ withRotation(deg, x, y, w, h, draw) {
246
+ if (!deg) {
247
+ draw();
248
+ return;
249
+ }
250
+ const ctx = this.ctx;
251
+ ctx.save();
252
+ ctx.translate(x + w / 2, y + h / 2);
253
+ ctx.rotate(deg * Math.PI / 180);
254
+ ctx.translate(-(x + w / 2), -(y + h / 2));
255
+ draw();
256
+ ctx.restore();
257
+ }
258
+ /** One anchored float: vector shape or bitmap, then any textbox text laid
259
+ * out inside it (box-local lines — translate to the float's origin, and
260
+ * clip to the box the way Word hides textbox overflow). */
261
+ paintFloat(f, yOffset, o, pageInfo) {
262
+ this.withRotation(f.rotation, f.x, yOffset + f.y, f.width, f.height, () => {
263
+ if (f.shape) {
264
+ this.drawShape(f.shape, f.x, yOffset + f.y, f.width, f.height);
265
+ } else {
266
+ const el = this.requestImage(f.src);
267
+ if (el?.complete && el.naturalWidth > 0) {
268
+ this.ctx.drawImage(el, f.x, yOffset + f.y, f.width, f.height);
269
+ }
270
+ }
271
+ if (f.lines && f.lines.length > 0) {
272
+ const ctx = this.ctx;
273
+ ctx.save();
274
+ ctx.beginPath();
275
+ ctx.rect(f.x, yOffset + f.y, f.width, f.height);
276
+ ctx.clip();
277
+ ctx.translate(f.x, yOffset + f.y);
278
+ for (const line of f.lines) this.paintLine(line, 0, o, pageInfo);
279
+ ctx.restore();
280
+ }
281
+ });
282
+ }
283
+ paintLine(line, yOffset, o, pageInfo) {
284
+ const ctx = this.ctx;
285
+ const baselineY = yOffset + line.y + line.baseline;
286
+ for (const seg of line.segments) {
287
+ if (seg.background && seg.width) {
288
+ ctx.fillStyle = seg.background;
289
+ ctx.fillRect(seg.x, yOffset + line.y, seg.width, line.height);
290
+ }
291
+ }
292
+ for (const seg of line.segments) {
293
+ ctx.font = fontCss(seg.font);
294
+ ctx.fillStyle = seg.color ?? o.textColor;
295
+ const text = seg.field && pageInfo ? String(seg.field === "pageNumber" ? pageInfo.page : pageInfo.pages) : seg.text;
296
+ const em = seg.font.sizePt * (96 / 72);
297
+ const segY = seg.vertAlign === "super" ? baselineY - em * 0.5 : seg.vertAlign === "sub" ? baselineY + em * 0.2 : baselineY;
298
+ ctx.fillText(text, seg.x, segY);
299
+ if ((seg.underline || seg.strike) && seg.width) {
300
+ const em2 = seg.font.sizePt * (96 / 72);
301
+ const thickness = Math.max(1, em2 * 0.05);
302
+ if (seg.underline) ctx.fillRect(seg.x, baselineY + Math.max(1, em2 * 0.1), seg.width, thickness);
303
+ if (seg.strike) ctx.fillRect(seg.x, baselineY - em2 * 0.27, seg.width, thickness);
304
+ }
305
+ }
306
+ for (const img of line.images ?? []) {
307
+ this.withRotation(img.rotation, img.x, baselineY - img.height, img.width, img.height, () => {
308
+ if (img.shape) {
309
+ this.drawShape(img.shape, img.x, baselineY - img.height, img.width, img.height);
310
+ return;
311
+ }
312
+ const el = this.requestImage(img.src);
313
+ if (el?.complete && el.naturalWidth > 0) {
314
+ ctx.drawImage(el, img.x, baselineY - img.height, img.width, img.height);
315
+ }
316
+ });
317
+ }
318
+ }
319
+ /** Vector shape in an image box, per ShapeSpec.kind. The path is built with
320
+ * primitive calls (no Path2D) and filled then stroked; strokes stay inside
321
+ * the box so thick outlines don't bleed into text. */
322
+ drawShape(s, x, y, w, h) {
323
+ const ctx = this.ctx;
324
+ const lw = s.strokeWidth || 1;
325
+ const fillStroke = () => {
326
+ if (s.fill) {
327
+ ctx.fillStyle = s.fill;
328
+ ctx.fill();
329
+ }
330
+ if (s.stroke) {
331
+ ctx.strokeStyle = s.stroke;
332
+ ctx.lineWidth = lw;
333
+ ctx.stroke();
334
+ }
335
+ };
336
+ switch (s.kind) {
337
+ case "rect": {
338
+ if (s.fill) {
339
+ ctx.fillStyle = s.fill;
340
+ ctx.fillRect(x, y, w, h);
341
+ }
342
+ if (s.stroke) {
343
+ ctx.strokeStyle = s.stroke;
344
+ ctx.lineWidth = lw;
345
+ ctx.strokeRect(x + lw / 2, y + lw / 2, Math.max(0, w - lw), Math.max(0, h - lw));
346
+ }
347
+ return;
348
+ }
349
+ case "line": {
350
+ if (!s.stroke) return;
351
+ ctx.strokeStyle = s.stroke;
352
+ ctx.lineWidth = lw;
353
+ ctx.beginPath();
354
+ if (s.flipV) {
355
+ ctx.moveTo(x, y + h);
356
+ ctx.lineTo(x + w, y);
357
+ } else {
358
+ ctx.moveTo(x, y);
359
+ ctx.lineTo(x + w, y + h);
360
+ }
361
+ ctx.stroke();
362
+ return;
363
+ }
364
+ case "ellipse": {
365
+ ctx.beginPath();
366
+ ctx.ellipse(x + w / 2, y + h / 2, Math.max(0, (w - lw) / 2), Math.max(0, (h - lw) / 2), 0, 0, Math.PI * 2);
367
+ fillStroke();
368
+ return;
369
+ }
370
+ case "roundRect": {
371
+ const r = Math.min(0.16667 * Math.min(w, h), w / 2, h / 2);
372
+ const [x0, y0, x1, y1] = [x + lw / 2, y + lw / 2, x + w - lw / 2, y + h - lw / 2];
373
+ ctx.beginPath();
374
+ ctx.moveTo(x0 + r, y0);
375
+ ctx.lineTo(x1 - r, y0);
376
+ ctx.quadraticCurveTo(x1, y0, x1, y0 + r);
377
+ ctx.lineTo(x1, y1 - r);
378
+ ctx.quadraticCurveTo(x1, y1, x1 - r, y1);
379
+ ctx.lineTo(x0 + r, y1);
380
+ ctx.quadraticCurveTo(x0, y1, x0, y1 - r);
381
+ ctx.lineTo(x0, y0 + r);
382
+ ctx.quadraticCurveTo(x0, y0, x0 + r, y0);
383
+ ctx.closePath();
384
+ fillStroke();
385
+ return;
386
+ }
387
+ case "rightArrow": {
388
+ const head = Math.min(0.5 * Math.min(w, h), w);
389
+ const hx = x + w - head;
390
+ ctx.beginPath();
391
+ ctx.moveTo(x, y + h / 4);
392
+ ctx.lineTo(hx, y + h / 4);
393
+ ctx.lineTo(hx, y);
394
+ ctx.lineTo(x + w, y + h / 2);
395
+ ctx.lineTo(hx, y + h);
396
+ ctx.lineTo(hx, y + 3 * h / 4);
397
+ ctx.lineTo(x, y + 3 * h / 4);
398
+ ctx.closePath();
399
+ fillStroke();
400
+ return;
401
+ }
402
+ case "horizontalScroll": {
403
+ const r = Math.min(0.125 * Math.min(w, h), w / 4);
404
+ ctx.beginPath();
405
+ ctx.rect(x + r, y + lw / 2, w - 2 * r, h - lw);
406
+ fillStroke();
407
+ for (const cx of [x + r, x + w - r]) {
408
+ ctx.beginPath();
409
+ ctx.ellipse(cx, y + h / 2, r, Math.max(0, (h - lw) / 2), 0, 0, Math.PI * 2);
410
+ fillStroke();
411
+ }
412
+ return;
413
+ }
414
+ }
415
+ }
416
+ paintTable(table, yOffset, o, pageInfo) {
417
+ const ctx = this.ctx;
418
+ for (const cell of table.cells) {
419
+ if (cell.background) {
420
+ ctx.fillStyle = cell.background;
421
+ ctx.fillRect(cell.x, yOffset + cell.y, cell.width, cell.height);
422
+ }
423
+ }
424
+ for (const cell of table.cells) {
425
+ const clip = cell.lines.some((l) => l.images?.some((im) => im.rotation));
426
+ if (clip) {
427
+ ctx.save();
428
+ ctx.beginPath();
429
+ ctx.rect(cell.x, yOffset + cell.y, cell.width, cell.height);
430
+ ctx.clip();
431
+ }
432
+ for (const line of cell.lines) this.paintLine(line, yOffset, o, pageInfo);
433
+ for (const nested of cell.tables ?? []) this.paintTable(nested, yOffset, o, pageInfo);
434
+ if (clip) ctx.restore();
435
+ }
436
+ const b = table.borders;
437
+ if (b || table.cells.some((c) => c.borders)) {
438
+ const eps = 0.5;
439
+ for (const cell of table.cells) {
440
+ const cb = cell.borders;
441
+ const x0 = cell.x + 0.5;
442
+ const x1 = cell.x + cell.width + 0.5;
443
+ const y0 = yOffset + cell.y + 0.5;
444
+ const y1 = yOffset + cell.y + cell.height + 0.5;
445
+ const topOuter = Math.abs(cell.y - table.y) < eps;
446
+ const bottomOuter = Math.abs(cell.y + cell.height - (table.y + table.height)) < eps;
447
+ const leftOuter = Math.abs(cell.x - table.x) < eps;
448
+ const rightOuter = Math.abs(cell.x + cell.width - (table.x + table.width)) < eps;
449
+ const top = cb?.top ?? (topOuter ? b?.top : b?.insideH);
450
+ const bottom = cb?.bottom ?? (bottomOuter ? b?.bottom : b?.insideH);
451
+ const left = cb?.left ?? (leftOuter ? b?.left : b?.insideV);
452
+ const right = cb?.right ?? (rightOuter ? b?.right : b?.insideV);
453
+ if (top) this.strokeBorder(top, x0, y0, x1, y0);
454
+ if (bottom) this.strokeBorder(bottom, x0, y1, x1, y1);
455
+ if (left) this.strokeBorder(left, x0, y0, x0, y1);
456
+ if (right) this.strokeBorder(right, x1, y0, x1, y1);
457
+ }
458
+ ctx.setLineDash([]);
459
+ }
460
+ for (const cell of table.cells) {
461
+ for (const f of cell.floats ?? []) this.paintFloat(f, yOffset, o, pageInfo);
462
+ }
463
+ }
464
+ /** Stroke one border edge with its width / style / colour. The edge is always
465
+ * horizontal or vertical (table grid lines). */
466
+ strokeBorder(side, x1, y1, x2, y2) {
467
+ const ctx = this.ctx;
468
+ ctx.strokeStyle = side.color;
469
+ if (side.style === "double") {
470
+ ctx.setLineDash([]);
471
+ ctx.lineWidth = Math.max(0.75, side.width / 3);
472
+ const gap = Math.max(2, side.width) / 2;
473
+ const horiz = y1 === y2;
474
+ ctx.beginPath();
475
+ ctx.moveTo(x1 + (horiz ? 0 : -gap), y1 + (horiz ? -gap : 0));
476
+ ctx.lineTo(x2 + (horiz ? 0 : -gap), y2 + (horiz ? -gap : 0));
477
+ ctx.moveTo(x1 + (horiz ? 0 : gap), y1 + (horiz ? gap : 0));
478
+ ctx.lineTo(x2 + (horiz ? 0 : gap), y2 + (horiz ? gap : 0));
479
+ ctx.stroke();
480
+ return;
481
+ }
482
+ ctx.lineWidth = side.width;
483
+ ctx.setLineDash(
484
+ side.style === "dashed" ? [side.width * 3, side.width * 2] : side.style === "dotted" ? [side.width, side.width * 1.6] : []
485
+ );
486
+ ctx.beginPath();
487
+ ctx.moveTo(x1, y1);
488
+ ctx.lineTo(x2, y2);
489
+ ctx.stroke();
490
+ }
491
+ /** Container CSS-px point → page-local point. Points in the gap between pages
492
+ * clamp to the nearer page edge; null before the first paint. */
493
+ canvasToPage(cssX, cssY) {
494
+ if (!this.lastLayout) return null;
495
+ const zoom = this.lastOptions.zoom ?? DEFAULTS.zoom;
496
+ const gap = this.lastOptions.pageGap ?? DEFAULTS.pageGap;
497
+ const x = cssX / zoom;
498
+ const y = cssY / zoom;
499
+ let yOffset = 0;
500
+ const pages = this.lastLayout.pages;
501
+ for (let i = 0; i < pages.length; i++) {
502
+ const page = pages[i];
503
+ const isLast = i === pages.length - 1;
504
+ const claim = page.height + (isLast ? Infinity : gap / 2);
505
+ if (y < yOffset + claim) {
506
+ return { pageIndex: i, x, y: Math.min(Math.max(y - yOffset, 0), page.height) };
507
+ }
508
+ yOffset += page.height + gap;
509
+ }
510
+ return null;
511
+ }
512
+ /** Page-local point → container CSS-px point; null before the first paint. */
513
+ pageToCanvas(point) {
514
+ if (!this.lastLayout) return null;
515
+ const zoom = this.lastOptions.zoom ?? DEFAULTS.zoom;
516
+ const gap = this.lastOptions.pageGap ?? DEFAULTS.pageGap;
517
+ let yOffset = 0;
518
+ for (let i = 0; i < point.pageIndex; i++) {
519
+ const page = this.lastLayout.pages[i];
520
+ if (!page) return null;
521
+ yOffset += page.height + gap;
522
+ }
523
+ return { x: point.x * zoom, y: (yOffset + point.y) * zoom };
524
+ }
525
+ /** Return the cached image for `src`, kicking off a load (and a repaint on
526
+ * completion) the first time. Returns undefined where Image is unavailable
527
+ * (SSR / tests) — the image is simply skipped. */
528
+ requestImage(src) {
529
+ const cached = this.images.get(src);
530
+ if (cached) return cached;
531
+ if (typeof Image === "undefined") return void 0;
532
+ const el = new Image();
533
+ el.onload = () => {
534
+ if (this.lastLayout) {
535
+ this.paint(this.lastLayout, {
536
+ ...this.lastOptions,
537
+ caret: this.lastOverlay.caret,
538
+ selection: this.lastOverlay.selection
539
+ });
540
+ }
541
+ };
542
+ el.src = src;
543
+ this.images.set(src, el);
544
+ return el;
545
+ }
546
+ };
547
+ // Annotate the CommonJS export names for ESM import in node:
548
+ 0 && (module.exports = {
549
+ CanvasPainter
550
+ });
@@ -0,0 +1,2 @@
1
+ export * from './lib/painter-canvas.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,yBAAyB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,523 @@
1
+ // packages/painter-canvas/src/lib/painter-canvas.ts
2
+ var VIEWPORT_MARGIN = 200;
3
+ var POOL_LIMIT = 8;
4
+ var DEFAULTS = {
5
+ zoom: 1,
6
+ pageGap: 24,
7
+ pageBackground: "#ffffff",
8
+ pageBorder: "#c8c8c8",
9
+ tableBorder: "#b0b0b0",
10
+ textColor: "#000000",
11
+ caretColor: "#1a1a1a",
12
+ selectionColor: "rgba(59, 130, 246, 0.30)",
13
+ decorations: []
14
+ };
15
+ var fontCss = (f) => `${f.italic ? "italic " : ""}${f.bold ? "700" : "400"} ${f.sizePt}pt ${f.family}`;
16
+ var defaultDpr = () => typeof globalThis.devicePixelRatio === "number" ? Math.min(globalThis.devicePixelRatio, 2) : 1;
17
+ var CanvasPainter = class {
18
+ constructor(container, deps = {}) {
19
+ this.container = container;
20
+ this.createCanvas = deps.createCanvas ?? (() => document.createElement("canvas"));
21
+ }
22
+ container;
23
+ createCanvas;
24
+ images = /* @__PURE__ */ new Map();
25
+ /** pageIndex → its mounted canvas; idle canvases wait in `pool`. */
26
+ mounted = /* @__PURE__ */ new Map();
27
+ pool = [];
28
+ /** The 2D context of the page currently being drawn (paint* read this). */
29
+ ctx;
30
+ lastLayout = null;
31
+ /** Last paint options, minus caret/selection (those live in lastOverlay). */
32
+ lastOptions = {};
33
+ lastOverlay = {
34
+ caret: null,
35
+ selection: []
36
+ };
37
+ lastFrame = null;
38
+ /** Top edge (layout px) of each page in the stacked document. */
39
+ pageY = [];
40
+ /** Pages currently showing caret/selection (so an overlay change can clear them). */
41
+ overlayPages = /* @__PURE__ */ new Set();
42
+ paint(layout, options = {}) {
43
+ this.lastLayout = layout;
44
+ const { caret, selection, ...rest } = options;
45
+ this.lastOptions = rest;
46
+ if (caret !== void 0 || selection !== void 0) {
47
+ this.lastOverlay = { caret: caret ?? null, selection: selection ?? [] };
48
+ }
49
+ const o = { ...DEFAULTS, ...rest };
50
+ const dpr = options.devicePixelRatio ?? defaultDpr();
51
+ this.lastFrame = { o, dpr };
52
+ const width = layout.pages.reduce((m, p) => Math.max(m, p.width), 0);
53
+ this.pageY = [];
54
+ let acc = 0;
55
+ for (const page of layout.pages) {
56
+ this.pageY.push(acc);
57
+ acc += page.height + o.pageGap;
58
+ }
59
+ const totalHeight = Math.max(0, acc - o.pageGap);
60
+ this.container.style.position ||= "relative";
61
+ this.container.style.width = `${Math.round(width * o.zoom)}px`;
62
+ this.container.style.height = `${Math.round(totalHeight * o.zoom)}px`;
63
+ const vp = options.viewport;
64
+ const vTop = vp ? vp.top / o.zoom - VIEWPORT_MARGIN : -Infinity;
65
+ const vBottom = vp ? (vp.top + vp.height) / o.zoom + VIEWPORT_MARGIN : Infinity;
66
+ const desired = /* @__PURE__ */ new Set();
67
+ layout.pages.forEach((page, i) => {
68
+ const top = this.pageY[i];
69
+ if (top + page.height >= vTop && top <= vBottom) desired.add(i);
70
+ });
71
+ for (const idx of [...this.mounted.keys()]) {
72
+ if (!desired.has(idx)) this.unmountPage(idx);
73
+ }
74
+ this.overlayPages = /* @__PURE__ */ new Set();
75
+ for (const i of desired) this.drawPage(i, o, dpr);
76
+ if (this.lastOverlay.caret) this.overlayPages.add(this.lastOverlay.caret.pageIndex);
77
+ for (const r of this.lastOverlay.selection) this.overlayPages.add(r.pageIndex);
78
+ }
79
+ /** Redraw just the pages whose caret/selection changed — the cheap path for
80
+ * blink and drag (one page for a blink, a handful for a drag). */
81
+ paintOverlay(overlay = {}) {
82
+ this.lastOverlay = { caret: overlay.caret ?? null, selection: overlay.selection ?? [] };
83
+ const frame = this.lastFrame;
84
+ if (!frame || !this.lastLayout) return;
85
+ const next = /* @__PURE__ */ new Set();
86
+ if (this.lastOverlay.caret) next.add(this.lastOverlay.caret.pageIndex);
87
+ for (const r of this.lastOverlay.selection) next.add(r.pageIndex);
88
+ const affected = /* @__PURE__ */ new Set([...this.overlayPages, ...next]);
89
+ this.overlayPages = next;
90
+ for (const i of affected) {
91
+ if (this.mounted.has(i)) this.drawPage(i, frame.o, frame.dpr);
92
+ }
93
+ }
94
+ /** Mount (or reuse) page `i`'s canvas, size + position it, and draw it. */
95
+ drawPage(i, o, dpr) {
96
+ const page = this.lastLayout?.pages[i];
97
+ if (!page) return;
98
+ const slot = this.mountPage(i);
99
+ this.sizeCanvas(slot.canvas, page.width, page.height, o.zoom, dpr);
100
+ slot.canvas.style.top = `${Math.round(this.pageY[i] * o.zoom)}px`;
101
+ this.ctx = slot.ctx;
102
+ this.ctx.setTransform(o.zoom * dpr, 0, 0, o.zoom * dpr, 0, 0);
103
+ this.ctx.clearRect(0, 0, page.width, page.height);
104
+ this.ctx.textBaseline = "alphabetic";
105
+ const pageInfo = { page: page.index + 1, pages: this.lastLayout?.pages.length ?? 1 };
106
+ this.paintPage(page, 0, o, pageInfo);
107
+ for (const chrome of [this.chromeFor(i, "header"), this.chromeFor(i, "footer")]) {
108
+ if (!chrome) continue;
109
+ for (const line of chrome.lines) this.paintLine(line, 0, o, pageInfo);
110
+ for (const table of chrome.tables) this.paintTable(table, 0, o, pageInfo);
111
+ for (const f of chrome.floats ?? []) this.paintFloat(f, 0, o, pageInfo);
112
+ }
113
+ }
114
+ /** Pick the header/footer band for page `i`: the first variant on page 1 when
115
+ * titlePg is set, the even variant on even pages when evenAndOdd is set, else
116
+ * the default. A selected-but-absent variant means a blank band (no fallback
117
+ * to the default — that's Word's behavior for title/even pages). */
118
+ chromeFor(i, kind) {
119
+ const L = this.lastLayout;
120
+ if (!L) return void 0;
121
+ const s = L.chromeSelect;
122
+ const pick = (def, first, even) => {
123
+ if (s?.titlePg && i === 0) return first;
124
+ if (s?.evenAndOdd && (i + 1) % 2 === 0) return even;
125
+ return def;
126
+ };
127
+ return kind === "header" ? pick(L.pageHeader, L.pageHeaderFirst, L.pageHeaderEven) : pick(L.pageFooter, L.pageFooterFirst, L.pageFooterEven);
128
+ }
129
+ /** Get page `i`'s slot, reusing a pooled canvas or creating one. */
130
+ mountPage(i) {
131
+ const existing = this.mounted.get(i);
132
+ if (existing) return existing;
133
+ let slot = this.pool.pop();
134
+ if (!slot) {
135
+ const canvas = this.createCanvas();
136
+ const ctx = canvas.getContext("2d");
137
+ if (!ctx) throw new Error("bapbong-painter-canvas: 2D canvas context unavailable");
138
+ canvas.style.position = "absolute";
139
+ canvas.style.left = "0";
140
+ canvas.style.display = "block";
141
+ canvas.style.pointerEvents = "none";
142
+ slot = { canvas, ctx };
143
+ }
144
+ this.container.appendChild(slot.canvas);
145
+ this.mounted.set(i, slot);
146
+ return slot;
147
+ }
148
+ /** Detach page `i`, freeing its backing store (kept in the pool for reuse). */
149
+ unmountPage(i) {
150
+ const slot = this.mounted.get(i);
151
+ if (!slot) return;
152
+ this.mounted.delete(i);
153
+ slot.canvas.width = 0;
154
+ slot.canvas.height = 0;
155
+ slot.canvas.parentNode?.removeChild(slot.canvas);
156
+ if (this.pool.length < POOL_LIMIT) this.pool.push(slot);
157
+ }
158
+ /** Only resize when needed: assigning width/height — even the same value —
159
+ * clears and reallocates the backing store. */
160
+ sizeCanvas(c, width, height, zoom, dpr) {
161
+ const deviceW = Math.max(1, Math.round(width * zoom * dpr));
162
+ const deviceH = Math.max(1, Math.round(height * zoom * dpr));
163
+ if (c.width !== deviceW) c.width = deviceW;
164
+ if (c.height !== deviceH) c.height = deviceH;
165
+ c.style.width = `${Math.round(width * zoom)}px`;
166
+ c.style.height = `${Math.round(height * zoom)}px`;
167
+ }
168
+ paintPage(page, yOffset, o, pageInfo) {
169
+ const ctx = this.ctx;
170
+ ctx.fillStyle = o.pageBackground;
171
+ ctx.fillRect(0, yOffset, page.width, page.height);
172
+ ctx.strokeStyle = o.pageBorder;
173
+ ctx.lineWidth = 1;
174
+ ctx.strokeRect(0.5, yOffset + 0.5, page.width - 1, page.height - 1);
175
+ for (const f of page.floats ?? []) this.paintFloat(f, yOffset, o, pageInfo);
176
+ ctx.fillStyle = o.selectionColor;
177
+ for (const r of this.lastOverlay.selection) {
178
+ if (r.pageIndex === page.index) ctx.fillRect(r.x, yOffset + r.y, r.width, r.height);
179
+ }
180
+ for (const d of o.decorations) {
181
+ if (d.kind !== "background") continue;
182
+ ctx.fillStyle = d.color;
183
+ for (const r of d.rects) {
184
+ if (r.pageIndex === page.index) ctx.fillRect(r.x, yOffset + r.y, r.width, r.height);
185
+ }
186
+ }
187
+ for (const line of page.lines) this.paintLine(line, yOffset, o, pageInfo);
188
+ for (const table of page.tables ?? []) this.paintTable(table, yOffset, o, pageInfo);
189
+ for (const d of o.decorations) {
190
+ if (d.kind === "background") continue;
191
+ ctx.fillStyle = d.color;
192
+ for (const r of d.rects) {
193
+ if (r.pageIndex !== page.index) continue;
194
+ const thickness = Math.max(1, r.height * 0.06);
195
+ const y = d.kind === "underline" ? yOffset + r.y + r.height - thickness : yOffset + r.y + r.height / 2;
196
+ ctx.fillRect(r.x, y, r.width, thickness);
197
+ }
198
+ }
199
+ if (page.footnotes) {
200
+ const fn = page.footnotes;
201
+ const startX = fn.lines[0]?.x ?? 0;
202
+ const sepY = Math.round(yOffset + fn.separatorY) + 0.5;
203
+ ctx.strokeStyle = o.pageBorder;
204
+ ctx.lineWidth = 1;
205
+ ctx.beginPath();
206
+ ctx.moveTo(startX, sepY);
207
+ ctx.lineTo(startX + Math.min(192, page.width * 0.3), sepY);
208
+ ctx.stroke();
209
+ for (const line of fn.lines) this.paintLine(line, yOffset, o, pageInfo);
210
+ }
211
+ const caret = this.lastOverlay.caret;
212
+ if (caret && caret.pageIndex === page.index) {
213
+ ctx.fillStyle = o.caretColor;
214
+ ctx.fillRect(caret.x, yOffset + caret.y, 1.5, caret.height);
215
+ }
216
+ }
217
+ /** Run `draw` rotated `deg` clockwise around the center of the given box —
218
+ * the paint-only rotation of images/shapes (the layout box stays put). */
219
+ withRotation(deg, x, y, w, h, draw) {
220
+ if (!deg) {
221
+ draw();
222
+ return;
223
+ }
224
+ const ctx = this.ctx;
225
+ ctx.save();
226
+ ctx.translate(x + w / 2, y + h / 2);
227
+ ctx.rotate(deg * Math.PI / 180);
228
+ ctx.translate(-(x + w / 2), -(y + h / 2));
229
+ draw();
230
+ ctx.restore();
231
+ }
232
+ /** One anchored float: vector shape or bitmap, then any textbox text laid
233
+ * out inside it (box-local lines — translate to the float's origin, and
234
+ * clip to the box the way Word hides textbox overflow). */
235
+ paintFloat(f, yOffset, o, pageInfo) {
236
+ this.withRotation(f.rotation, f.x, yOffset + f.y, f.width, f.height, () => {
237
+ if (f.shape) {
238
+ this.drawShape(f.shape, f.x, yOffset + f.y, f.width, f.height);
239
+ } else {
240
+ const el = this.requestImage(f.src);
241
+ if (el?.complete && el.naturalWidth > 0) {
242
+ this.ctx.drawImage(el, f.x, yOffset + f.y, f.width, f.height);
243
+ }
244
+ }
245
+ if (f.lines && f.lines.length > 0) {
246
+ const ctx = this.ctx;
247
+ ctx.save();
248
+ ctx.beginPath();
249
+ ctx.rect(f.x, yOffset + f.y, f.width, f.height);
250
+ ctx.clip();
251
+ ctx.translate(f.x, yOffset + f.y);
252
+ for (const line of f.lines) this.paintLine(line, 0, o, pageInfo);
253
+ ctx.restore();
254
+ }
255
+ });
256
+ }
257
+ paintLine(line, yOffset, o, pageInfo) {
258
+ const ctx = this.ctx;
259
+ const baselineY = yOffset + line.y + line.baseline;
260
+ for (const seg of line.segments) {
261
+ if (seg.background && seg.width) {
262
+ ctx.fillStyle = seg.background;
263
+ ctx.fillRect(seg.x, yOffset + line.y, seg.width, line.height);
264
+ }
265
+ }
266
+ for (const seg of line.segments) {
267
+ ctx.font = fontCss(seg.font);
268
+ ctx.fillStyle = seg.color ?? o.textColor;
269
+ const text = seg.field && pageInfo ? String(seg.field === "pageNumber" ? pageInfo.page : pageInfo.pages) : seg.text;
270
+ const em = seg.font.sizePt * (96 / 72);
271
+ const segY = seg.vertAlign === "super" ? baselineY - em * 0.5 : seg.vertAlign === "sub" ? baselineY + em * 0.2 : baselineY;
272
+ ctx.fillText(text, seg.x, segY);
273
+ if ((seg.underline || seg.strike) && seg.width) {
274
+ const em2 = seg.font.sizePt * (96 / 72);
275
+ const thickness = Math.max(1, em2 * 0.05);
276
+ if (seg.underline) ctx.fillRect(seg.x, baselineY + Math.max(1, em2 * 0.1), seg.width, thickness);
277
+ if (seg.strike) ctx.fillRect(seg.x, baselineY - em2 * 0.27, seg.width, thickness);
278
+ }
279
+ }
280
+ for (const img of line.images ?? []) {
281
+ this.withRotation(img.rotation, img.x, baselineY - img.height, img.width, img.height, () => {
282
+ if (img.shape) {
283
+ this.drawShape(img.shape, img.x, baselineY - img.height, img.width, img.height);
284
+ return;
285
+ }
286
+ const el = this.requestImage(img.src);
287
+ if (el?.complete && el.naturalWidth > 0) {
288
+ ctx.drawImage(el, img.x, baselineY - img.height, img.width, img.height);
289
+ }
290
+ });
291
+ }
292
+ }
293
+ /** Vector shape in an image box, per ShapeSpec.kind. The path is built with
294
+ * primitive calls (no Path2D) and filled then stroked; strokes stay inside
295
+ * the box so thick outlines don't bleed into text. */
296
+ drawShape(s, x, y, w, h) {
297
+ const ctx = this.ctx;
298
+ const lw = s.strokeWidth || 1;
299
+ const fillStroke = () => {
300
+ if (s.fill) {
301
+ ctx.fillStyle = s.fill;
302
+ ctx.fill();
303
+ }
304
+ if (s.stroke) {
305
+ ctx.strokeStyle = s.stroke;
306
+ ctx.lineWidth = lw;
307
+ ctx.stroke();
308
+ }
309
+ };
310
+ switch (s.kind) {
311
+ case "rect": {
312
+ if (s.fill) {
313
+ ctx.fillStyle = s.fill;
314
+ ctx.fillRect(x, y, w, h);
315
+ }
316
+ if (s.stroke) {
317
+ ctx.strokeStyle = s.stroke;
318
+ ctx.lineWidth = lw;
319
+ ctx.strokeRect(x + lw / 2, y + lw / 2, Math.max(0, w - lw), Math.max(0, h - lw));
320
+ }
321
+ return;
322
+ }
323
+ case "line": {
324
+ if (!s.stroke) return;
325
+ ctx.strokeStyle = s.stroke;
326
+ ctx.lineWidth = lw;
327
+ ctx.beginPath();
328
+ if (s.flipV) {
329
+ ctx.moveTo(x, y + h);
330
+ ctx.lineTo(x + w, y);
331
+ } else {
332
+ ctx.moveTo(x, y);
333
+ ctx.lineTo(x + w, y + h);
334
+ }
335
+ ctx.stroke();
336
+ return;
337
+ }
338
+ case "ellipse": {
339
+ ctx.beginPath();
340
+ ctx.ellipse(x + w / 2, y + h / 2, Math.max(0, (w - lw) / 2), Math.max(0, (h - lw) / 2), 0, 0, Math.PI * 2);
341
+ fillStroke();
342
+ return;
343
+ }
344
+ case "roundRect": {
345
+ const r = Math.min(0.16667 * Math.min(w, h), w / 2, h / 2);
346
+ const [x0, y0, x1, y1] = [x + lw / 2, y + lw / 2, x + w - lw / 2, y + h - lw / 2];
347
+ ctx.beginPath();
348
+ ctx.moveTo(x0 + r, y0);
349
+ ctx.lineTo(x1 - r, y0);
350
+ ctx.quadraticCurveTo(x1, y0, x1, y0 + r);
351
+ ctx.lineTo(x1, y1 - r);
352
+ ctx.quadraticCurveTo(x1, y1, x1 - r, y1);
353
+ ctx.lineTo(x0 + r, y1);
354
+ ctx.quadraticCurveTo(x0, y1, x0, y1 - r);
355
+ ctx.lineTo(x0, y0 + r);
356
+ ctx.quadraticCurveTo(x0, y0, x0 + r, y0);
357
+ ctx.closePath();
358
+ fillStroke();
359
+ return;
360
+ }
361
+ case "rightArrow": {
362
+ const head = Math.min(0.5 * Math.min(w, h), w);
363
+ const hx = x + w - head;
364
+ ctx.beginPath();
365
+ ctx.moveTo(x, y + h / 4);
366
+ ctx.lineTo(hx, y + h / 4);
367
+ ctx.lineTo(hx, y);
368
+ ctx.lineTo(x + w, y + h / 2);
369
+ ctx.lineTo(hx, y + h);
370
+ ctx.lineTo(hx, y + 3 * h / 4);
371
+ ctx.lineTo(x, y + 3 * h / 4);
372
+ ctx.closePath();
373
+ fillStroke();
374
+ return;
375
+ }
376
+ case "horizontalScroll": {
377
+ const r = Math.min(0.125 * Math.min(w, h), w / 4);
378
+ ctx.beginPath();
379
+ ctx.rect(x + r, y + lw / 2, w - 2 * r, h - lw);
380
+ fillStroke();
381
+ for (const cx of [x + r, x + w - r]) {
382
+ ctx.beginPath();
383
+ ctx.ellipse(cx, y + h / 2, r, Math.max(0, (h - lw) / 2), 0, 0, Math.PI * 2);
384
+ fillStroke();
385
+ }
386
+ return;
387
+ }
388
+ }
389
+ }
390
+ paintTable(table, yOffset, o, pageInfo) {
391
+ const ctx = this.ctx;
392
+ for (const cell of table.cells) {
393
+ if (cell.background) {
394
+ ctx.fillStyle = cell.background;
395
+ ctx.fillRect(cell.x, yOffset + cell.y, cell.width, cell.height);
396
+ }
397
+ }
398
+ for (const cell of table.cells) {
399
+ const clip = cell.lines.some((l) => l.images?.some((im) => im.rotation));
400
+ if (clip) {
401
+ ctx.save();
402
+ ctx.beginPath();
403
+ ctx.rect(cell.x, yOffset + cell.y, cell.width, cell.height);
404
+ ctx.clip();
405
+ }
406
+ for (const line of cell.lines) this.paintLine(line, yOffset, o, pageInfo);
407
+ for (const nested of cell.tables ?? []) this.paintTable(nested, yOffset, o, pageInfo);
408
+ if (clip) ctx.restore();
409
+ }
410
+ const b = table.borders;
411
+ if (b || table.cells.some((c) => c.borders)) {
412
+ const eps = 0.5;
413
+ for (const cell of table.cells) {
414
+ const cb = cell.borders;
415
+ const x0 = cell.x + 0.5;
416
+ const x1 = cell.x + cell.width + 0.5;
417
+ const y0 = yOffset + cell.y + 0.5;
418
+ const y1 = yOffset + cell.y + cell.height + 0.5;
419
+ const topOuter = Math.abs(cell.y - table.y) < eps;
420
+ const bottomOuter = Math.abs(cell.y + cell.height - (table.y + table.height)) < eps;
421
+ const leftOuter = Math.abs(cell.x - table.x) < eps;
422
+ const rightOuter = Math.abs(cell.x + cell.width - (table.x + table.width)) < eps;
423
+ const top = cb?.top ?? (topOuter ? b?.top : b?.insideH);
424
+ const bottom = cb?.bottom ?? (bottomOuter ? b?.bottom : b?.insideH);
425
+ const left = cb?.left ?? (leftOuter ? b?.left : b?.insideV);
426
+ const right = cb?.right ?? (rightOuter ? b?.right : b?.insideV);
427
+ if (top) this.strokeBorder(top, x0, y0, x1, y0);
428
+ if (bottom) this.strokeBorder(bottom, x0, y1, x1, y1);
429
+ if (left) this.strokeBorder(left, x0, y0, x0, y1);
430
+ if (right) this.strokeBorder(right, x1, y0, x1, y1);
431
+ }
432
+ ctx.setLineDash([]);
433
+ }
434
+ for (const cell of table.cells) {
435
+ for (const f of cell.floats ?? []) this.paintFloat(f, yOffset, o, pageInfo);
436
+ }
437
+ }
438
+ /** Stroke one border edge with its width / style / colour. The edge is always
439
+ * horizontal or vertical (table grid lines). */
440
+ strokeBorder(side, x1, y1, x2, y2) {
441
+ const ctx = this.ctx;
442
+ ctx.strokeStyle = side.color;
443
+ if (side.style === "double") {
444
+ ctx.setLineDash([]);
445
+ ctx.lineWidth = Math.max(0.75, side.width / 3);
446
+ const gap = Math.max(2, side.width) / 2;
447
+ const horiz = y1 === y2;
448
+ ctx.beginPath();
449
+ ctx.moveTo(x1 + (horiz ? 0 : -gap), y1 + (horiz ? -gap : 0));
450
+ ctx.lineTo(x2 + (horiz ? 0 : -gap), y2 + (horiz ? -gap : 0));
451
+ ctx.moveTo(x1 + (horiz ? 0 : gap), y1 + (horiz ? gap : 0));
452
+ ctx.lineTo(x2 + (horiz ? 0 : gap), y2 + (horiz ? gap : 0));
453
+ ctx.stroke();
454
+ return;
455
+ }
456
+ ctx.lineWidth = side.width;
457
+ ctx.setLineDash(
458
+ side.style === "dashed" ? [side.width * 3, side.width * 2] : side.style === "dotted" ? [side.width, side.width * 1.6] : []
459
+ );
460
+ ctx.beginPath();
461
+ ctx.moveTo(x1, y1);
462
+ ctx.lineTo(x2, y2);
463
+ ctx.stroke();
464
+ }
465
+ /** Container CSS-px point → page-local point. Points in the gap between pages
466
+ * clamp to the nearer page edge; null before the first paint. */
467
+ canvasToPage(cssX, cssY) {
468
+ if (!this.lastLayout) return null;
469
+ const zoom = this.lastOptions.zoom ?? DEFAULTS.zoom;
470
+ const gap = this.lastOptions.pageGap ?? DEFAULTS.pageGap;
471
+ const x = cssX / zoom;
472
+ const y = cssY / zoom;
473
+ let yOffset = 0;
474
+ const pages = this.lastLayout.pages;
475
+ for (let i = 0; i < pages.length; i++) {
476
+ const page = pages[i];
477
+ const isLast = i === pages.length - 1;
478
+ const claim = page.height + (isLast ? Infinity : gap / 2);
479
+ if (y < yOffset + claim) {
480
+ return { pageIndex: i, x, y: Math.min(Math.max(y - yOffset, 0), page.height) };
481
+ }
482
+ yOffset += page.height + gap;
483
+ }
484
+ return null;
485
+ }
486
+ /** Page-local point → container CSS-px point; null before the first paint. */
487
+ pageToCanvas(point) {
488
+ if (!this.lastLayout) return null;
489
+ const zoom = this.lastOptions.zoom ?? DEFAULTS.zoom;
490
+ const gap = this.lastOptions.pageGap ?? DEFAULTS.pageGap;
491
+ let yOffset = 0;
492
+ for (let i = 0; i < point.pageIndex; i++) {
493
+ const page = this.lastLayout.pages[i];
494
+ if (!page) return null;
495
+ yOffset += page.height + gap;
496
+ }
497
+ return { x: point.x * zoom, y: (yOffset + point.y) * zoom };
498
+ }
499
+ /** Return the cached image for `src`, kicking off a load (and a repaint on
500
+ * completion) the first time. Returns undefined where Image is unavailable
501
+ * (SSR / tests) — the image is simply skipped. */
502
+ requestImage(src) {
503
+ const cached = this.images.get(src);
504
+ if (cached) return cached;
505
+ if (typeof Image === "undefined") return void 0;
506
+ const el = new Image();
507
+ el.onload = () => {
508
+ if (this.lastLayout) {
509
+ this.paint(this.lastLayout, {
510
+ ...this.lastOptions,
511
+ caret: this.lastOverlay.caret,
512
+ selection: this.lastOverlay.selection
513
+ });
514
+ }
515
+ };
516
+ el.src = src;
517
+ this.images.set(src, el);
518
+ return el;
519
+ }
520
+ };
521
+ export {
522
+ CanvasPainter
523
+ };
@@ -0,0 +1,119 @@
1
+ import type { CaretRect, PagePoint, PaintDecoration, ResolvedLayout, SelectionRect } from '@shadow-garden/bapbong-contracts';
2
+ export interface PaintOptions {
3
+ /** Zoom factor (1 = 100%). */
4
+ zoom?: number;
5
+ /** Vertical gap between pages, in layout px. */
6
+ pageGap?: number;
7
+ /** Device pixel ratio override. Defaults to `window.devicePixelRatio`, capped at 2. */
8
+ devicePixelRatio?: number;
9
+ pageBackground?: string;
10
+ pageBorder?: string;
11
+ tableBorder?: string;
12
+ /** Fallback text color for segments without an explicit color. */
13
+ textColor?: string;
14
+ /** Caret to draw (page-local coords), e.g. from bapbong-selection. */
15
+ caret?: CaretRect | null;
16
+ /** Selection highlight rects (page-local coords), drawn under the text. */
17
+ selection?: SelectionRect[];
18
+ caretColor?: string;
19
+ selectionColor?: string;
20
+ /** Plugin-contributed decorations, pre-resolved to page-local rects. Background
21
+ * kinds paint behind the text; underline/strike paint over it. */
22
+ decorations?: PaintDecoration[];
23
+ /** Visible region in container CSS px (the scroll window onto the stack).
24
+ * Only pages intersecting it (plus a margin) get a canvas + content; the
25
+ * rest are unmounted to keep memory bounded. Omit to render every page. */
26
+ viewport?: {
27
+ top: number;
28
+ height: number;
29
+ };
30
+ }
31
+ /** Injected so the painter can be unit-tested without a DOM. */
32
+ export interface PainterDeps {
33
+ /** Creates a blank canvas element (defaults to document.createElement). */
34
+ createCanvas?: () => HTMLCanvasElement;
35
+ }
36
+ /**
37
+ * Paints a ResolvedLayout into a scroll container, one `<canvas>` per page.
38
+ *
39
+ * A single canvas can't represent a long document: browsers cap a canvas at
40
+ * 65535 px per side, so a tall doc (≈57+ A4 pages) silently renders blank. One
41
+ * canvas per page keeps every backing store small, and only the pages near the
42
+ * viewport are allocated — the rest are unmounted, so memory stays bounded no
43
+ * matter how long the document is.
44
+ *
45
+ * The painter consumes pre-computed coordinates only — it never measures or
46
+ * re-flows text. Inline images load asynchronously: the painter caches them and
47
+ * repaints once an image becomes available.
48
+ */
49
+ export declare class CanvasPainter {
50
+ private readonly container;
51
+ private readonly createCanvas;
52
+ private readonly images;
53
+ /** pageIndex → its mounted canvas; idle canvases wait in `pool`. */
54
+ private readonly mounted;
55
+ private readonly pool;
56
+ /** The 2D context of the page currently being drawn (paint* read this). */
57
+ private ctx;
58
+ private lastLayout;
59
+ /** Last paint options, minus caret/selection (those live in lastOverlay). */
60
+ private lastOptions;
61
+ private lastOverlay;
62
+ private lastFrame;
63
+ /** Top edge (layout px) of each page in the stacked document. */
64
+ private pageY;
65
+ /** Pages currently showing caret/selection (so an overlay change can clear them). */
66
+ private overlayPages;
67
+ constructor(container: HTMLElement, deps?: PainterDeps);
68
+ paint(layout: ResolvedLayout, options?: PaintOptions): void;
69
+ /** Redraw just the pages whose caret/selection changed — the cheap path for
70
+ * blink and drag (one page for a blink, a handful for a drag). */
71
+ paintOverlay(overlay?: {
72
+ caret?: CaretRect | null;
73
+ selection?: SelectionRect[];
74
+ }): void;
75
+ /** Mount (or reuse) page `i`'s canvas, size + position it, and draw it. */
76
+ private drawPage;
77
+ /** Pick the header/footer band for page `i`: the first variant on page 1 when
78
+ * titlePg is set, the even variant on even pages when evenAndOdd is set, else
79
+ * the default. A selected-but-absent variant means a blank band (no fallback
80
+ * to the default — that's Word's behavior for title/even pages). */
81
+ private chromeFor;
82
+ /** Get page `i`'s slot, reusing a pooled canvas or creating one. */
83
+ private mountPage;
84
+ /** Detach page `i`, freeing its backing store (kept in the pool for reuse). */
85
+ private unmountPage;
86
+ /** Only resize when needed: assigning width/height — even the same value —
87
+ * clears and reallocates the backing store. */
88
+ private sizeCanvas;
89
+ private paintPage;
90
+ /** Run `draw` rotated `deg` clockwise around the center of the given box —
91
+ * the paint-only rotation of images/shapes (the layout box stays put). */
92
+ private withRotation;
93
+ /** One anchored float: vector shape or bitmap, then any textbox text laid
94
+ * out inside it (box-local lines — translate to the float's origin, and
95
+ * clip to the box the way Word hides textbox overflow). */
96
+ private paintFloat;
97
+ private paintLine;
98
+ /** Vector shape in an image box, per ShapeSpec.kind. The path is built with
99
+ * primitive calls (no Path2D) and filled then stroked; strokes stay inside
100
+ * the box so thick outlines don't bleed into text. */
101
+ private drawShape;
102
+ private paintTable;
103
+ /** Stroke one border edge with its width / style / colour. The edge is always
104
+ * horizontal or vertical (table grid lines). */
105
+ private strokeBorder;
106
+ /** Container CSS-px point → page-local point. Points in the gap between pages
107
+ * clamp to the nearer page edge; null before the first paint. */
108
+ canvasToPage(cssX: number, cssY: number): PagePoint | null;
109
+ /** Page-local point → container CSS-px point; null before the first paint. */
110
+ pageToCanvas(point: PagePoint): {
111
+ x: number;
112
+ y: number;
113
+ } | null;
114
+ /** Return the cached image for `src`, kicking off a load (and a repaint on
115
+ * completion) the first time. Returns undefined where Image is unavailable
116
+ * (SSR / tests) — the image is simply skipped. */
117
+ private requestImage;
118
+ }
119
+ //# sourceMappingURL=painter-canvas.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"painter-canvas.d.ts","sourceRoot":"","sources":["../../src/lib/painter-canvas.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,SAAS,EAGT,SAAS,EACT,eAAe,EAGf,cAAc,EAGd,aAAa,EAEd,MAAM,kCAAkC,CAAC;AAE1C,MAAM,WAAW,YAAY;IAC3B,8BAA8B;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,gDAAgD;IAChD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,uFAAuF;IACvF,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,kEAAkE;IAClE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,sEAAsE;IACtE,KAAK,CAAC,EAAE,SAAS,GAAG,IAAI,CAAC;IACzB,2EAA2E;IAC3E,SAAS,CAAC,EAAE,aAAa,EAAE,CAAC;IAC5B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;uEACmE;IACnE,WAAW,CAAC,EAAE,eAAe,EAAE,CAAC;IAChC;;gFAE4E;IAC5E,QAAQ,CAAC,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;CAC5C;AAED,gEAAgE;AAChE,MAAM,WAAW,WAAW;IAC1B,2EAA2E;IAC3E,YAAY,CAAC,EAAE,MAAM,iBAAiB,CAAC;CACxC;AA+CD;;;;;;;;;;;;GAYG;AACH,qBAAa,aAAa;IAuBtB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAtB5B,OAAO,CAAC,QAAQ,CAAC,YAAY,CAA0B;IACvD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAuC;IAC9D,oEAAoE;IACpE,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA+B;IACvD,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAkB;IACvC,2EAA2E;IAC3E,OAAO,CAAC,GAAG,CAA4B;IAEvC,OAAO,CAAC,UAAU,CAA+B;IACjD,6EAA6E;IAC7E,OAAO,CAAC,WAAW,CAAoB;IACvC,OAAO,CAAC,WAAW,CAGjB;IACF,OAAO,CAAC,SAAS,CAAoD;IACrE,iEAAiE;IACjE,OAAO,CAAC,KAAK,CAAgB;IAC7B,qFAAqF;IACrF,OAAO,CAAC,YAAY,CAAqB;gBAGtB,SAAS,EAAE,WAAW,EACvC,IAAI,GAAE,WAAgB;IAMxB,KAAK,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,GAAE,YAAiB,GAAG,IAAI;IA2C/D;uEACmE;IACnE,YAAY,CAAC,OAAO,GAAE;QAAE,KAAK,CAAC,EAAE,SAAS,GAAG,IAAI,CAAC;QAAC,SAAS,CAAC,EAAE,aAAa,EAAE,CAAA;KAAO,GAAG,IAAI;IAc3F,2EAA2E;IAC3E,OAAO,CAAC,QAAQ;IAuBhB;;;yEAGqE;IACrE,OAAO,CAAC,SAAS;IAcjB,oEAAoE;IACpE,OAAO,CAAC,SAAS;IAmBjB,+EAA+E;IAC/E,OAAO,CAAC,WAAW;IAUnB;oDACgD;IAChD,OAAO,CAAC,UAAU;IASlB,OAAO,CAAC,SAAS;IA+DjB;+EAC2E;IAC3E,OAAO,CAAC,YAAY;IAcpB;;gEAE4D;IAC5D,OAAO,CAAC,UAAU;IAuBlB,OAAO,CAAC,SAAS;IAuDjB;;2DAEuD;IACvD,OAAO,CAAC,SAAS;IAoGjB,OAAO,CAAC,UAAU;IAmElB;qDACiD;IACjD,OAAO,CAAC,YAAY;IA+BpB;sEACkE;IAClE,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI;IAqB1D,8EAA8E;IAC9E,YAAY,CAAC,KAAK,EAAE,SAAS,GAAG;QAAE,CAAC,EAAE,MAAM,CAAC;QAAC,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI;IAa/D;;uDAEmD;IACnD,OAAO,CAAC,YAAY;CAkBrB"}
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@shadow-garden/bapbong-painter-canvas",
3
+ "version": "0.1.0",
4
+ "description": "bapbong — paints ResolvedLayout onto a Canvas 2D context",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/shadowgarden-app/bapbong.git",
9
+ "directory": "packages/painter-canvas"
10
+ },
11
+ "type": "module",
12
+ "main": "./dist/index.cjs",
13
+ "module": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
15
+ "exports": {
16
+ "./package.json": "./package.json",
17
+ ".": {
18
+ "@shadow-garden/source": "./src/index.ts",
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js",
21
+ "require": "./dist/index.cjs",
22
+ "default": "./dist/index.js"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "!**/*.tsbuildinfo"
28
+ ],
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "nx": {
33
+ "tags": [
34
+ "scope:painter"
35
+ ],
36
+ "targets": {
37
+ "build": {
38
+ "executor": "@nx/esbuild:esbuild",
39
+ "outputs": [
40
+ "{options.outputPath}"
41
+ ],
42
+ "options": {
43
+ "outputPath": "packages/painter-canvas/dist",
44
+ "main": "packages/painter-canvas/src/index.ts",
45
+ "tsConfig": "packages/painter-canvas/tsconfig.lib.json",
46
+ "format": [
47
+ "esm",
48
+ "cjs"
49
+ ],
50
+ "declarationRootDir": "packages/painter-canvas/src",
51
+ "external": [
52
+ "@shadow-garden/bapbong-contracts"
53
+ ]
54
+ }
55
+ }
56
+ }
57
+ },
58
+ "dependencies": {
59
+ "@shadow-garden/bapbong-contracts": "^0.1.0"
60
+ }
61
+ }