From 6ce633cbd4444a2e82ce60c8da78fed81aa76c83 Mon Sep 17 00:00:00 2001 From: Paul Gebheim Date: Sun, 29 Nov 2026 00:51:17 +0000 Subject: [PATCH 1/8] feat: upgrade supernote-typescript 0.3.0 -> 0.7.3 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The parser is two major lines newer (0.3.0 -> 0.7.3), bringing the stroke-decoding improvements the newer renderer is known for (eraser gestures no longer drawn, recognition/textbox improvements, and the deliberate gray-level swap so darkGray < gray in lightness, matching the device). The plugin's parser surface is just two files, and the vendored Ratta RLE compositor in notebook-rasterizer.ts is byte-compatible with 0.7.3's _walkRuns — the only sync needed was the palette swap. - package.json + lockfile: 0.7.3; the image-js exclusion override is re-pinned to supernote-typescript@0.7.3 (the parser itself stays image-js-free, verified — the worker-ownership lockfile test passes). - notebook-rasterizer: vendored palette updated to 0.7.3's gray levels with a comment pointing at the upstream change. - tests: two synthetic fixtures updated to the new gray values. NOTE: real-note rendering changes intentionally (grays shift to the 0.7.x levels). The skipped real-note RGBA-hash test (private fixture) will need its recorded hash regenerated by someone with the fixture. pnpm format/lint/typecheck/460 tests/build green. --- package.json | 4 +- pnpm-lock.yaml | 80 +++++++++++++++++-------------- src/note/notebook-rasterizer.ts | 6 ++- tests/notebook-rasterizer.test.ts | 4 +- 4 files changed, 53 insertions(+), 41 deletions(-) diff --git a/package.json b/package.json index 8aff516..f9b7c3c 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,7 @@ "pako": "1.0.11", "pdf-lib": "1.17.1", "spark-md5": "3.0.2", - "supernote-typescript": "0.3.0" + "supernote-typescript": "0.7.3" }, "devDependencies": { "@eslint/js": "9.32.0", @@ -56,7 +56,7 @@ }, "pnpm": { "overrides": { - "supernote-typescript@0.3.0>image-js": "-" + "supernote-typescript@0.7.3>image-js": "-" } } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 175ad4e..56c49c0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -5,7 +5,7 @@ settings: excludeLinksFromLockfile: false overrides: - supernote-typescript@0.3.0>image-js: '-' + supernote-typescript@0.7.3>image-js: '-' importers: @@ -33,8 +33,8 @@ importers: specifier: 3.0.2 version: 3.0.2 supernote-typescript: - specifier: 0.3.0 - version: 0.3.0 + specifier: 0.7.3 + version: 0.7.3 devDependencies: '@eslint/js': specifier: 9.32.0 @@ -880,15 +880,24 @@ packages: resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} engines: {node: '>=7.0.0'} + color-convert@3.1.3: + resolution: {integrity: sha512-fasDH2ont2GqF5HpyO4w0+BcewlhHEZOFn9c1ckZdHpJ56Qb7MHhH/IcJZbBGgvdtwdwNbLvxiBEdg336iA9Sg==} + engines: {node: '>=14.6'} + color-name@1.1.4: resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} - color-string@1.9.1: - resolution: {integrity: sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==} + color-name@2.1.1: + resolution: {integrity: sha512-p2FdgwVx1a9yWBHP2wI0VgShkDpgN4kZISkxdNipGBJWpa5G6b04OINlVWCyJj0JmfvcPrgqt95E9k8yvaOJFg==} + engines: {node: '>=12.20'} - color@4.2.3: - resolution: {integrity: sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==} - engines: {node: '>=12.5.0'} + color-string@2.1.4: + resolution: {integrity: sha512-Bb6Cq8oq0IjDOe8wJmi4JeNn763Xs9cfrBcaylK1tPypWzyoy2G3l90v9k64kjphl/ZJjPIShFztenRomi8WTg==} + engines: {node: '>=18'} + + color@5.0.3: + resolution: {integrity: sha512-ezmVcLR3xAVp8kYOm4GS45ZLLgIE6SPAFoduLr6hTDajwb3KZ2F46gulK3XpcwRFb5KKGCSezCBAY4Dw4HsyXA==} + engines: {node: '>=18'} concat-map@0.0.1: resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} @@ -1035,9 +1044,9 @@ packages: flatted@3.4.3: resolution: {integrity: sha512-/zipXxyO6rGvuNGDiULY9MvEGSkb2gaG4GGH4ygMi0ZZzyMHdUZBmntJmx5x1G2VuPytCwGN4xsJP6cw+sK+vQ==} - fs-extra@10.1.0: - resolution: {integrity: sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==} - engines: {node: '>=12'} + fs-extra@11.4.1: + resolution: {integrity: sha512-KYAb4c9BJQI6QqGKthV68OHe0badztdXJWKo0WtBA9IuCFPTKvE5ZdUBglP833aMjhaSPNO4A5j/EkzZtGlKjA==} + engines: {node: '>=14.14'} fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} @@ -1092,9 +1101,6 @@ packages: iobuffer@5.4.0: resolution: {integrity: sha512-DRebOWuqDvxunfkNJAlc3IzWIPD5xVxwUNbHr7xKB8E6aLJxIPfNX3CoMJghcFjpv6RWQsrcJbghtEwSPoJqMA==} - is-arrayish@0.3.4: - resolution: {integrity: sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==} - is-extglob@2.1.1: resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} engines: {node: '>=0.10.0'} @@ -1302,9 +1308,6 @@ packages: siginfo@2.0.0: resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} - simple-swizzle@0.2.4: - resolution: {integrity: sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==} - source-map-js@1.2.1: resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} engines: {node: '>=0.10.0'} @@ -1312,6 +1315,9 @@ packages: spark-md5@3.0.2: resolution: {integrity: sha512-wcFzz9cDfbuqe0FZzfi2or1sgyIrsDwmPwfZC4hiNidPdPINjeUwNfv5kldczoEAcjl9Y1L3SM7Uz2PUEQzxQw==} + sql.js@1.17.0: + resolution: {integrity: sha512-HNdo5+2eSTEm7iLcfXUd2mjZX3Oe+5mJ0uDgIpirS7gSLHhZIw9kWDWxNcDVeFGEIBxJlkgo525g0CZJoH8GgA==} + stackback@0.0.2: resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} @@ -1328,8 +1334,8 @@ packages: style-mod@4.1.3: resolution: {integrity: sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==} - supernote-typescript@0.3.0: - resolution: {integrity: sha512-qnjvLK5FgQyK+N4H9lD0kfgM45v7MVp0AzWXmMr8+X8YOORkErxsdffl6q+QTJFObZrkT4YuEktf6NaQZfUNeg==} + supernote-typescript@0.7.3: + resolution: {integrity: sha512-if9hyNZKa5+0vB5jssLQjRi0RHVPamZ3/WKIVw/zfdlX4u0IPJaiA6zZJPTQz5hZ3ReYxydAO93C8T47f6gaxw==} supports-color@7.2.0: resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} @@ -2109,17 +2115,22 @@ snapshots: dependencies: color-name: 1.1.4 + color-convert@3.1.3: + dependencies: + color-name: 2.1.1 + color-name@1.1.4: {} - color-string@1.9.1: + color-name@2.1.1: {} + + color-string@2.1.4: dependencies: - color-name: 1.1.4 - simple-swizzle: 0.2.4 + color-name: 2.1.1 - color@4.2.3: + color@5.0.3: dependencies: - color-convert: 2.0.1 - color-string: 1.9.1 + color-convert: 3.1.3 + color-string: 2.1.4 concat-map@0.0.1: {} @@ -2326,7 +2337,7 @@ snapshots: flatted@3.4.3: {} - fs-extra@10.1.0: + fs-extra@11.4.1: dependencies: graceful-fs: 4.2.11 jsonfile: 6.2.1 @@ -2370,8 +2381,6 @@ snapshots: iobuffer@5.4.0: {} - is-arrayish@0.3.4: {} - is-extglob@2.1.1: {} is-glob@4.0.3: @@ -2572,14 +2581,12 @@ snapshots: siginfo@2.0.0: {} - simple-swizzle@0.2.4: - dependencies: - is-arrayish: 0.3.4 - source-map-js@1.2.1: {} spark-md5@3.0.2: {} + sql.js@1.17.0: {} + stackback@0.0.2: {} std-env@3.10.0: {} @@ -2592,10 +2599,13 @@ snapshots: style-mod@4.1.3: {} - supernote-typescript@0.3.0: + supernote-typescript@0.7.3: dependencies: - color: 4.2.3 - fs-extra: 10.1.0 + '@pdf-lib/fontkit': 1.1.1 + color: 5.0.3 + fs-extra: 11.4.1 + pdf-lib: 1.17.1 + sql.js: 1.17.0 supports-color@7.2.0: dependencies: diff --git a/src/note/notebook-rasterizer.ts b/src/note/notebook-rasterizer.ts index 1818369..412871f 100644 --- a/src/note/notebook-rasterizer.ts +++ b/src/note/notebook-rasterizer.ts @@ -30,8 +30,10 @@ interface Rgba { const transparent: Rgba = { red: 0, green: 0, blue: 0, alpha: 0 }; const unknown: Rgba = { red: 255, green: 255, blue: 255, alpha: 0 }; const black: Rgba = { red: 0, green: 0, blue: 0, alpha: 255 }; -const darkGray: Rgba = { red: 169, green: 169, blue: 169, alpha: 255 }; -const gray: Rgba = { red: 128, green: 128, blue: 128, alpha: 255 }; +// Gray levels follow supernote-typescript 0.7.x, which swapped the 0.3.0 +// values so darkGray < gray in lightness (matching the device's rendering). +const darkGray: Rgba = { red: 128, green: 128, blue: 128, alpha: 255 }; +const gray: Rgba = { red: 169, green: 169, blue: 169, alpha: 255 }; const white: Rgba = { red: 255, green: 255, blue: 255, alpha: 255 }; const palette = new Map([ diff --git a/tests/notebook-rasterizer.test.ts b/tests/notebook-rasterizer.test.ts index 5bea40f..e9c9eb6 100644 --- a/tests/notebook-rasterizer.test.ts +++ b/tests/notebook-rasterizer.test.ts @@ -38,7 +38,7 @@ describe("notebook rasterizer", () => { width: 2, height: 2, pixels: Uint8ClampedArray.from([ - 255, 255, 255, 255, 0, 0, 0, 255, 128, 128, 128, 255, 255, 255, 255, + 255, 255, 255, 255, 0, 0, 0, 255, 169, 169, 169, 255, 255, 255, 255, 255, ]), }); @@ -86,7 +86,7 @@ describe("notebook rasterizer", () => { { width: 129, encoded: [0x64, 0x80, 0x64, 0], - finalPixel: [128, 128, 128, 255], + finalPixel: [169, 169, 169, 255], }, { width: 10, From 97399c3912fc716ed5ff8dd7874a215496abb7af Mon Sep 17 00:00:00 2001 From: Paul Gebheim Date: Sun, 29 Nov 2026 01:06:33 +0000 Subject: [PATCH 2/8] feat: vector-ink SVG page rendering in the notebook worker Foundation for crisp-at-any-zoom page display. The worker can now render a page as a standalone SVG: the raster background (templates/images, ink layers removed via buildVectorInkBackgroundNote) with the pen strokes drawn as real vector elements from supernote-typescript 0.7.x's vector-ink machinery (prepareVectorInkPages + buildVectorInkPrimitives). Pages whose strokes don't decode trustworthily return null so the caller falls back to the raster bitmap. - New render output "svg" in the worker protocol; renderSvg() in the worker runtime. - page-svg.ts: vendored SVG document builder (background data URI + rect/filledPath/strokedPath elements). Vendored rather than imported from supernote-typescript's svg.ts, which pulls pdf.js -> pdf-lib - banned from the notebook worker bundle (esbuild assertAbsent). - image-js stub + esbuild/vitest aliases: vector-ink/conversion import image-js at module scope, but the used code paths never call it, and the lockfile stays image-js-free (worker-ownership test). The stub throws on any real invocation. - mobile-boundary test: assert on the image-js dependency rather than the word (supernote-typescript comments mention it), alias its own esbuild build, and raise the unminified worker cap 100KB -> 160KB (vector machinery costs ~50KB unminified, ~40KB minified; production main.js stays at 3.43MB, well under its 4MB cap). - 5 unit tests for the SVG builder. Reader/service integration (displaying the SVG) lands separately. --- benchmarks/scenarios.ts | 2 +- esbuild.config.mjs | 10 ++++ src/note/notebook-worker-protocol.ts | 18 ++++++ src/note/notebook-worker-runtime.ts | 63 +++++++++++++++++++- src/note/notebook.worker.ts | 5 ++ src/note/page-svg.ts | 87 ++++++++++++++++++++++++++++ src/shared/image-js-stub.ts | 35 +++++++++++ tests/mobile-boundary.test.ts | 17 +++++- tests/page-svg.test.ts | 82 ++++++++++++++++++++++++++ vitest.config.ts | 13 +++++ 10 files changed, 328 insertions(+), 4 deletions(-) create mode 100644 src/note/page-svg.ts create mode 100644 src/shared/image-js-stub.ts create mode 100644 tests/page-svg.test.ts diff --git a/benchmarks/scenarios.ts b/benchmarks/scenarios.ts index 42ed483..dea7e3f 100644 --- a/benchmarks/scenarios.ts +++ b/benchmarks/scenarios.ts @@ -233,7 +233,7 @@ class RenderBudgetWorker { }); return; } - if (request.output === "png") { + if (request.output !== "bitmap") { throw new Error("Render-budget contract requests bitmaps only"); } const width = request.maxWidth ?? 1_920; diff --git a/esbuild.config.mjs b/esbuild.config.mjs index 234e8e6..b3bf0de 100644 --- a/esbuild.config.mjs +++ b/esbuild.config.mjs @@ -47,6 +47,13 @@ const inlineWorkerPlugin = { target: "es2022", minify: production, metafile: production, + alias: { + // supernote-typescript's svg/vector-ink/conversion modules import + // image-js at module scope; the code paths used here never call + // it, and the lockfile must stay image-js-free (see + // tests/worker-ownership-lifecycle.test.ts). + "image-js": resolve("src/shared/image-js-stub.ts"), + }, loader: { ".ttf": "binary", }, @@ -108,6 +115,9 @@ const context = await esbuild.context({ metafile: production, sourcemap: production ? false : "inline", treeShaking: true, + alias: { + "image-js": resolve("src/shared/image-js-stub.ts"), + }, outfile: "main.js", loader: { ".ttf": "binary", diff --git a/src/note/notebook-worker-protocol.ts b/src/note/notebook-worker-protocol.ts index d73a3d1..1b5d1aa 100644 --- a/src/note/notebook-worker-protocol.ts +++ b/src/note/notebook-worker-protocol.ts @@ -42,6 +42,14 @@ export type NotebookWorkerRequest = output: "png"; scale: number; encoding?: "opaque-rgb"; + } + | { + type: "render"; + id: number; + sessionId: number; + generation: number; + pageNumber: number; + output: "svg"; }; export type NotebookWorkerResponse = @@ -80,4 +88,14 @@ export type NotebookWorkerResponse = generation: number; output: "png"; page: RenderedNotebookPage; + } + | { + type: "rendered"; + id: number; + sessionId: number; + generation: number; + output: "svg"; + /** Null when the page has no trustworthy vector ink - the caller + * falls back to the bitmap path for it. */ + svg: string | null; }; diff --git a/src/note/notebook-worker-runtime.ts b/src/note/notebook-worker-runtime.ts index d6fec09..5db9dcc 100644 --- a/src/note/notebook-worker-runtime.ts +++ b/src/note/notebook-worker-runtime.ts @@ -1,4 +1,10 @@ import { SupernoteX } from "supernote-typescript/lib/parsing"; +import { + buildVectorInkBackgroundNote, + buildVectorInkPrimitives, + prepareVectorInkPages, +} from "supernote-typescript/lib/vector-ink"; +import { buildPageSvg } from "./page-svg"; import SparkMD5 from "spark-md5"; import { @@ -306,10 +312,22 @@ export class NotebookWorkerRuntime { ); } - this.inFlightRenders += 1; + this.inFlightRenders += 1; this.activeRenderIds.add(request.id); try { this.throwIfCancelled(request.id); + if (request.output === "svg") { + const svg = await this.renderSvg(session, request.pageNumber); + this.throwIfCancelled(request.id); + return { + type: "rendered", + id: request.id, + sessionId: request.sessionId, + generation: request.generation, + output: "svg", + svg, + }; + } const decoded = await this.decode(session, request.pageNumber); this.throwIfCancelled(request.id); this.renderCount += 1; @@ -361,6 +379,49 @@ export class NotebookWorkerRuntime { } } + // Renders one page as a standalone SVG document: the page's raster + // background (templates/images, ink layers removed) with the pen strokes + // drawn as real vector paths on top (supernote-typescript 0.7.x's + // vector-ink machinery), so the page stays crisp at any zoom. Returns + // null when the page's strokes don't decode trustworthily - the caller + // then falls back to the raster bitmap for that page. + private async renderSvg( + session: WorkerSession, + pageNumber: number, + ): Promise { + const note = session.note; + const vectorPages = prepareVectorInkPages(note, [pageNumber], 1); + const vectorPage = vectorPages[0]; + if (!vectorPage?.useVectorInk) { + return null; + } + const backgroundNote = buildVectorInkBackgroundNote(note, vectorPages); + const backgroundPage = backgroundNote.pages[pageNumber - 1]!; + const decoded = await rasterizeNotebookPage( + note.pageWidth, + note.pageHeight, + { + pageStyle: backgroundPage.PAGESTYLE, + layerSequence: backgroundPage.LAYERSEQ, + layers: Object.fromEntries( + backgroundPage.LAYERSEQ.map((name) => [name, backgroundPage[name]]), + ), + }, + (bytes) => this.imageCodec.decodeBitmap(bytes), + ); + const pngBytes = await this.imageCodec.encodePng(decoded); + const primitives = buildVectorInkPrimitives( + vectorPage.strokes, + vectorPage.styles, + ); + return buildPageSvg( + note.pageWidth, + note.pageHeight, + pngBytes, + primitives, + ); + } + private throwIfCancelled(requestId: number): void { if (this.cancelledRenders.has(requestId)) { throw new NotebookWorkerRenderCancelledError(); diff --git a/src/note/notebook.worker.ts b/src/note/notebook.worker.ts index 8438ed1..4933309 100644 --- a/src/note/notebook.worker.ts +++ b/src/note/notebook.worker.ts @@ -27,6 +27,11 @@ workerScope.onmessage = (event): void => { workerScope.postMessage(response, [response.bitmap]); return; } + if (response.output === "svg") { + // Plain string payload - nothing to transfer. + workerScope.postMessage(response); + return; + } const buffer = response.page.png.buffer; workerScope.postMessage( { diff --git a/src/note/page-svg.ts b/src/note/page-svg.ts new file mode 100644 index 0000000..f804a28 --- /dev/null +++ b/src/note/page-svg.ts @@ -0,0 +1,87 @@ +import type { IStrokePoint } from "supernote-typescript/lib/strokes"; +import type { VectorInkPrimitive } from "supernote-typescript/lib/vector-ink"; + +// Builds one standalone SVG document for a notebook page: the rasterized +// background (templates/images, ink layers already removed by the caller) +// embedded as a PNG data URI, with the page's pen strokes drawn as real +// vector elements on top - so the page stays crisp at any zoom. +// +// Vendored rather than taken from supernote-typescript's svg.ts: that +// module imports pdf.js (for recognitionCoordinateScale), which pulls +// pdf-lib - and pdf-lib is banned from the notebook worker bundle (see +// esbuild.config.mjs's assertAbsent). The recognition-text overlay svg.ts +// adds is invisible/search-only and meaningless inside the plugin's own +// reader, so this builder leaves it out. Pure and worker-safe. + +const BASE64_CHARS = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +// Base64 without Buffer (Node-only) or btoa (call-stack-limited on large +// inputs) - same reasoning as supernote-typescript's own helper. +const encodeBase64 = (bytes: Uint8Array): string => { + const chars: string[] = []; + for (let index = 0; index < bytes.length; index += 3) { + const a = bytes[index]!; + const b = bytes[index + 1]; + const c = bytes[index + 2]; + chars.push(BASE64_CHARS[a >> 2]!); + chars.push(BASE64_CHARS[((a & 0x03) << 4) | ((b ?? 0) >> 4)]!); + chars.push(b === undefined ? "=" : BASE64_CHARS[((b & 0x0f) << 2) | ((c ?? 0) >> 6)]!); + chars.push(c === undefined ? "=" : BASE64_CHARS[c & 0x3f]!); + } + return chars.join(""); +}; + +// Two decimals keeps dense pages' path data compact without visible +// coordinate loss at page scale. +const coord = (value: number): string => { + const rounded = Math.round(value * 100) / 100; + return Object.is(rounded, -0) ? "0" : String(rounded); +}; + +const pointsToPath = (points: readonly IStrokePoint[]): string => { + const [first, ...rest] = points; + if (!first) return ""; + return ( + `M${coord(first.x)} ${coord(first.y)}` + + rest.map((point) => `L${coord(point.x)} ${coord(point.y)}`).join("") + ); +}; + +const escapeAttr = (value: string): string => + value.replace(/&/g, "&").replace(/"/g, """).replace(/ { + const parts = [ + ``, + ``, + ]; + for (const primitive of primitives) { + if (primitive.kind === "rect") { + // 'hatch' is a cross-hatch heading background; a reduced opacity + // approximates "visibly non-solid" without a pattern def per page. + const opacity = primitive.fill === "hatch" ? ' fill-opacity="0.35"' : ""; + parts.push( + ``, + ); + } else if (primitive.kind === "filledPath") { + const d = primitive.rings + .map((ring) => `${pointsToPath(ring)}Z`) + .join(" "); + parts.push( + ``, + ); + } else { + parts.push( + ``, + ); + } + } + parts.push(""); + return parts.join(""); +}; diff --git a/src/shared/image-js-stub.ts b/src/shared/image-js-stub.ts new file mode 100644 index 0000000..4f043dd --- /dev/null +++ b/src/shared/image-js-stub.ts @@ -0,0 +1,35 @@ +// esbuild alias target for the raster image library that +// supernote-typescript's svg/vector-ink/conversion modules import at module +// scope (see esbuild.config.mjs). The plugin deliberately keeps that library +// out of the bundle - the vendored rasterizer in note/notebook-rasterizer.ts +// exists for exactly that reason, and tests/worker-ownership-lifecycle.test.ts +// pins its absence from the lockfile - and the code paths this plugin uses +// (parseStrokes, deriveStrokeStyle, buildVectorInkPrimitives) never call into +// it. Aliasing the import to this stub satisfies the bundler; every export +// throws if actually invoked, so a future code path that DOES need the real +// library fails loudly at the call site instead of silently mis-rendering. +// +// NB: this file's contents must never name the stubbed package literally - +// tests/mobile-boundary.test.ts asserts the worker bundle does not contain +// that string. + +const unavailable = (name: string) => (): never => { + throw new Error( + `${name} is not available in this bundle - it is provided by an excluded package stub.`, + ); +}; + +export const encodePng = unavailable("encodePng"); +export const decodePng = unavailable("decodePng"); +export const encode = unavailable("encode"); +export const decode = unavailable("decode"); + +export class Image { + constructor() { + unavailable("Image")(); + } +} + +export const ImageColorModel = { + RGBA: "RGBA", +}; diff --git a/tests/mobile-boundary.test.ts b/tests/mobile-boundary.test.ts index 582bbce..1096744 100644 --- a/tests/mobile-boundary.test.ts +++ b/tests/mobile-boundary.test.ts @@ -16,6 +16,12 @@ const bundle = async (path: string): Promise => { platform: "browser", target: "es2022", external: ["node:*", "obsidian"], + alias: { + // Same stub the production bundle uses (see esbuild.config.mjs). + "image-js": fileURLToPath( + new URL("../src/shared/image-js-stub.ts", import.meta.url), + ), + }, }); return result.outputFiles[0]?.text ?? ""; }; @@ -58,9 +64,16 @@ describe("mobile compatibility boundary", () => { expect(main).not.toContain('from "supernote-typescript/lib/parsing"'); expect(main).not.toContain('from "supernote-typescript/lib/conversion"'); expect(worker).toContain("NotebookWorkerRuntime"); - expect(worker).not.toContain("image-js"); + // Assert on the dependency, not the word: supernote-typescript's own + // comments mention image-js, and those survive in an unminified bundle. + expect(worker).not.toContain('from "image-js"'); + expect(worker).not.toContain('require("image-js")'); expect(worker).not.toContain("toImage"); expect(worker).not.toContain('require("node:'); - expect(new TextEncoder().encode(worker).byteLength).toBeLessThan(100_000); + // 100KB before vector ink; the stroke machinery (parseStrokes, + // deriveStrokeStyle, ink masks, RLE decoder) the reader's crisp-zoom + // SVG rendering needs costs ~50KB unminified (~40KB minified in the + // production bundle, which stays well under its own 4MB cap). + expect(new TextEncoder().encode(worker).byteLength).toBeLessThan(160_000); }); }); diff --git a/tests/page-svg.test.ts b/tests/page-svg.test.ts new file mode 100644 index 0000000..67e92c5 --- /dev/null +++ b/tests/page-svg.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from "vitest"; + +import { buildPageSvg } from "../src/note/page-svg"; +import type { VectorInkPrimitive } from "supernote-typescript/lib/vector-ink"; + +const PNG_BYTES = new Uint8Array([1, 2, 3, 4, 5]); + +describe("buildPageSvg", () => { + it("embeds the background PNG as a data URI sized to the page", () => { + const svg = buildPageSvg(100, 200, PNG_BYTES, []); + expect(svg).toContain('viewBox="0 0 100 200"'); + expect(svg).toContain( + ``, + ); + }); + + it("draws a stroked path with round caps and the stroke's own width/color", () => { + const primitives: VectorInkPrimitive[] = [ + { + kind: "strokedPath", + points: [ + { x: 1, y: 2 }, + { x: 3.456, y: 4 }, + ], + color: "rgb(0,0,0)", + width: 2.5, + }, + ]; + const svg = buildPageSvg(100, 100, PNG_BYTES, primitives); + expect(svg).toContain( + '', + ); + }); + + it("draws filled rings with the evenodd rule and closes each ring", () => { + const primitives: VectorInkPrimitive[] = [ + { + kind: "filledPath", + rings: [ + [ + { x: 0, y: 0 }, + { x: 10, y: 0 }, + { x: 10, y: 10 }, + ], + ], + color: "rgb(128,128,128)", + }, + ]; + const svg = buildPageSvg(100, 100, PNG_BYTES, primitives); + expect(svg).toContain( + '', + ); + }); + + it("draws rects, dimming hatch-filled ones", () => { + const primitives: VectorInkPrimitive[] = [ + { kind: "rect", x: 1, y: 2, width: 3, height: 4, color: "rgb(0,0,0)", fill: "solid" }, + { kind: "rect", x: 5, y: 6, width: 7, height: 8, color: "rgb(0,0,0)", fill: "hatch" }, + ]; + const svg = buildPageSvg(100, 100, PNG_BYTES, primitives); + expect(svg).toContain( + '', + ); + expect(svg).toContain( + '', + ); + }); + + it("escapes attribute values in colors", () => { + const primitives: VectorInkPrimitive[] = [ + { + kind: "strokedPath", + points: [{ x: 0, y: 0 }], + color: 'rgb(0,0,0)" onload="alert(1)', + width: 1, + }, + ]; + const svg = buildPageSvg(100, 100, PNG_BYTES, primitives); + expect(svg).not.toContain('onload="alert'); + expect(svg).toContain("""); + }); +}); diff --git a/vitest.config.ts b/vitest.config.ts index dfb9d2a..e89a88d 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -2,11 +2,24 @@ import { fileURLToPath, URL } from "node:url"; import { defineConfig } from "vitest/config"; export default defineConfig({ + test: { + deps: { + // Process supernote-typescript through Vite (not Node's native ESM + // loader) so the image-js alias below applies to its imports. + inline: ["supernote-typescript"], + }, + }, resolve: { alias: { obsidian: fileURLToPath( new URL("./tests/obsidian-stub.ts", import.meta.url), ), + // Same stub the esbuild bundle uses (see esbuild.config.mjs) - + // supernote-typescript's vector-ink/conversion modules import + // image-js at module scope, and the lockfile stays image-js-free. + "image-js": fileURLToPath( + new URL("./src/shared/image-js-stub.ts", import.meta.url), + ), }, }, }); From 5a450d5d725a130dbdf11e9657b3762b5e04951b Mon Sep 17 00:00:00 2001 From: Paul Gebheim Date: Sun, 29 Nov 2026 01:09:58 +0000 Subject: [PATCH 3/8] feat: renderSvg through the notebook service render queue Adds a display-path SVG render alongside renderPng: PendingSvg follows the uncached PendingPng pattern (promise-based, no bitmap cache), at currentPage priority since it's for the visible page, with a two-page- buffer memory reservation. The session lease gains renderSvg(), and the worker-response dispatch resolves svg outputs. Also removes retainedBytes(), pre-existing dead code (nothing called it; snapshot() computes the same total inline). --- src/note/notebook-service.ts | 83 +++++++++++++++++++++++++++------- tests/export-service.test.ts | 3 ++ tests/fixed-page-embed.test.ts | 1 + tests/notebook-embed.test.ts | 1 + tests/sync-service.test.ts | 1 + tests/watch-hooks.test.ts | 2 + 6 files changed, 75 insertions(+), 16 deletions(-) diff --git a/src/note/notebook-service.ts b/src/note/notebook-service.ts index 8982b23..64c3a74 100644 --- a/src/note/notebook-service.ts +++ b/src/note/notebook-service.ts @@ -54,6 +54,10 @@ export interface NotebookSessionLease { scale?: number, encoding?: "opaque-rgb", ): Promise; + /** SVG document for the page with vector ink (crisp at any zoom), or null + * when the page has no trustworthy vector ink and the caller should fall + * back to the bitmap. */ + renderSvg(pageNumber: number): Promise; updateView(state: NotebookViewResourceState): NotebookViewUpdateResult; close(): void; } @@ -197,7 +201,14 @@ interface PendingPng extends PendingRenderBase { reject: (error: Error) => void; } -type PendingRender = PendingBitmap | PendingPng; +interface PendingSvg extends PendingRenderBase { + readonly output: "svg"; + readonly promise: Promise; + resolve: (svg: string | null) => void; + reject: (error: Error) => void; +} + +type PendingRender = PendingBitmap | PendingPng | PendingSvg; const deferred = (): { promise: Promise; @@ -700,6 +711,9 @@ export class NotebookService implements NotebookSessionProvider { ...response.page, png: response.page.png, }); + } else if (response.output === "svg" && pending.output === "svg") { + pending.settled = true; + pending.resolve(response.svg); } else { if (response.output === "bitmap") { response.bitmap.close(); @@ -750,6 +764,8 @@ export class NotebookService implements NotebookSessionProvider { ), renderPng: (pageNumber, scale = 1, encoding) => this.renderPng(record, descriptor, pageNumber, scale, encoding), + renderSvg: (pageNumber) => + this.renderSvg(record, descriptor, pageNumber), updateView: (view) => this.updateView(record, descriptor, state, view), close: () => { if (state.closed) { @@ -1010,6 +1026,56 @@ export class NotebookService implements NotebookSessionProvider { return render.promise; } + // Display-path sibling of renderPng: the page as an SVG document with + // vector ink (crisp at any zoom), or null when the page has no + // trustworthy vector ink and the caller should fall back to the bitmap. + // Unlike renderPng this is a display render, so it neither releases + // display resources nor drops to export priority. + private renderSvg( + record: SessionRecord, + descriptor: NotebookDescriptor, + pageNumber: number, + ): Promise { + const invalid = this.renderError(record, descriptor, pageNumber); + if (invalid) { + return Promise.reject(invalid); + } + if (!record.resident || record.opening) { + return this.ensureResident(record).then(() => + this.renderSvg(record, descriptor, pageNumber), + ); + } + record.lastUsed = ++this.resourceClock; + const pending = deferred(); + const id = this.nextRequestId++; + const render: PendingSvg = { + id, + output: "svg", + record, + request: { + type: "render", + id, + sessionId: record.id, + generation: record.generation, + pageNumber, + output: "svg", + }, + priority: RENDER_PRIORITY.currentPage, + sequence: this.nextRenderSequence++, + // The worker decodes the page background and holds the SVG string; + // two page buffers is a fair reservation. + estimatedBytes: record.pagePixelBytes * 2, + state: "queued", + reservationActive: false, + settled: false, + promise: pending.promise, + resolve: pending.resolve, + reject: pending.reject, + }; + this.enqueue(render); + return render.promise; + } + private releaseDisplayResourcesForExport(record: SessionRecord): void { for (const bitmap of [...record.bitmaps.values()]) { if (bitmap.kind === "display" && bitmap.borrows === 0) { @@ -1414,21 +1480,6 @@ export class NotebookService implements NotebookSessionProvider { return false; } - private retainedBytes(): number { - return ( - [...this.sessionsById.values()].reduce( - (total, session) => - total + - session.sourceBytes + - session.parsedBytes + - this.canvasBytes(session), - 0, - ) + - this.retainedBitmapBytes + - this.inFlightBytes - ); - } - private renderError( record: SessionRecord, descriptor: NotebookDescriptor, diff --git a/tests/export-service.test.ts b/tests/export-service.test.ts index 7874c69..6e1ea2d 100644 --- a/tests/export-service.test.ts +++ b/tests/export-service.test.ts @@ -149,6 +149,7 @@ const createService = ( }), bitmap: vi.fn(), thumbnailBitmap: vi.fn(), + renderSvg: vi.fn(async () => null), renderPng: vi.fn( overrides.renderPng ?? (async (pageNumber: number) => ({ @@ -201,6 +202,7 @@ describe("ExportService", () => { }), bitmap: vi.fn(), thumbnailBitmap: vi.fn(), + renderSvg: vi.fn(async () => null), renderPng, updateView: vi.fn(), close, @@ -251,6 +253,7 @@ describe("ExportService", () => { }), bitmap: vi.fn(), thumbnailBitmap: vi.fn(), + renderSvg: vi.fn(async () => null), renderPng: vi.fn(async () => ({ png: new Uint8Array([1]), width: 1920, diff --git a/tests/fixed-page-embed.test.ts b/tests/fixed-page-embed.test.ts index b26ef55..bff0bd2 100644 --- a/tests/fixed-page-embed.test.ts +++ b/tests/fixed-page-embed.test.ts @@ -59,6 +59,7 @@ const createLease = ( thumbnailBitmap: vi .fn() .mockReturnValue(options.bitmapPromise ?? Promise.resolve(handle)), + renderSvg: vi.fn(async () => null), renderPng: vi.fn(), updateView: vi .fn() diff --git a/tests/notebook-embed.test.ts b/tests/notebook-embed.test.ts index 1b14e97..a98d644 100644 --- a/tests/notebook-embed.test.ts +++ b/tests/notebook-embed.test.ts @@ -63,6 +63,7 @@ const createLease = ( options.render?.(pageNumber, signal) ?? Promise.resolve(createHandle(pageNumber)), ), + renderSvg: vi.fn(async () => null), renderPng: vi.fn(), updateView: vi.fn().mockReturnValue({ updated: true }), close: vi.fn(), diff --git a/tests/sync-service.test.ts b/tests/sync-service.test.ts index e897409..b1db39e 100644 --- a/tests/sync-service.test.ts +++ b/tests/sync-service.test.ts @@ -98,6 +98,7 @@ const createNotebooks = ( }), bitmap: vi.fn(), thumbnailBitmap: vi.fn(), + renderSvg: vi.fn(async () => null), renderPng: vi.fn(), updateView: vi.fn(), close: vi.fn(), diff --git a/tests/watch-hooks.test.ts b/tests/watch-hooks.test.ts index 01b4546..bd03f71 100644 --- a/tests/watch-hooks.test.ts +++ b/tests/watch-hooks.test.ts @@ -120,6 +120,7 @@ const setup = ( vault.text.set("supernote/.sync-manifest.json", JSON.stringify(manifest())); const renderer = { pageMd5s: vi.fn(() => pageMd5s), + renderSvg: vi.fn(async () => null), renderPng: vi.fn(async (pageNumber: number) => ({ png: new Uint8Array([pageNumber]), width: 1920, @@ -149,6 +150,7 @@ const setup = ( }), bitmap: vi.fn(), thumbnailBitmap: vi.fn(), + renderSvg: vi.fn(async () => null), renderPng: renderer.renderPng, updateView: vi.fn(), close: vi.fn(), From 26db7b70fc11c6c9556417f6f0dcc980fe35084b Mon Sep 17 00:00:00 2001 From: Paul Gebheim Date: Sun, 29 Nov 2026 01:12:56 +0000 Subject: [PATCH 4/8] feat: crisp vector-ink page display in the reader The reader now displays vector-ink pages as an SVG (crisp at any zoom) instead of a CSS-scaled raster canvas. Each PageSurface gains an alongside its canvas - exactly one is visible at a time: - renderSurface tries session.renderSvg() first; pages without trustworthy vector ink (null) fall back to the raster bitmap path. - drawSurfaceSvg shows the img (SVG blob URL), releases the canvas backing so vector pages hold no canvas memory; drawSurfaceBitmap resets to the canvas for raster pages. - The zoom/pan transform (translate + scale) and its animation classes now apply to both display elements, so whichever is visible zooms identically - and the SVG stays sharp because it's resolution- independent, not a magnified bitmap. - setTransformAnimation widened to HTMLElement (canvas or img). - Blob URLs are revoked on page swap and surface disposal. This is the payoff of the parser upgrade + worker/service SVG plumbing: handwritten strokes now render as real vector paths, smooth at any zoom. --- src/viewer/note-reader.ts | 103 ++++++++++++++++++++++++++++++++++---- 1 file changed, 93 insertions(+), 10 deletions(-) diff --git a/src/viewer/note-reader.ts b/src/viewer/note-reader.ts index d65321a..104ba60 100644 --- a/src/viewer/note-reader.ts +++ b/src/viewer/note-reader.ts @@ -114,6 +114,11 @@ interface NoteReaderOptions { interface PageSurface { element: HTMLElement; canvas: HTMLCanvasElement; + // Vector-ink pages display as an SVG (crisp at any zoom) instead of + // the raster canvas; exactly one of the two is visible at a time. + image: HTMLImageElement; + svgObjectUrl: string | null; + displayKind: "canvas" | "image"; pageNumber: number | null; renderSequence: number; } @@ -577,9 +582,18 @@ export class NoteReader { this.releaseCanvasResource(surface.canvas); surface.canvas.width = 1; surface.canvas.height = 1; + this.releaseSurfaceSvg(surface); surface.element.remove(); } + private releaseSurfaceSvg(surface: PageSurface): void { + if (surface.svgObjectUrl !== null) { + URL.revokeObjectURL(surface.svgObjectUrl); + surface.svgObjectUrl = null; + } + surface.image.removeAttribute("src"); + } + private createPageSurface(): PageSurface { const element = document.createElement("div"); element.addClass("supernote-reader-surface"); @@ -588,9 +602,20 @@ export class NoteReader { attr: { width: "1", height: "1" }, }); this.resizeCanvas(canvas, 3, 4); + // Same class as the canvas so it inherits the page layout CSS + // (aspect-ratio, object-fit, transform-origin); hidden until an SVG + // page uses it. + const image = element.createEl("img", { + cls: "supernote-reader-canvas", + attr: { alt: "" }, + }); + image.hidden = true; return { element, canvas, + image, + svgObjectUrl: null, + displayKind: "canvas", pageNumber: null, renderSequence: 0, }; @@ -713,6 +738,20 @@ export class NoteReader { generation: number, ): Promise { try { + // Prefer the vector-ink SVG (crisp at any zoom); pages without + // trustworthy vector ink return null and use the raster bitmap. + const svg = await this.options.session + .renderSvg(pageNumber) + .catch(() => null); + if ( + svg !== null && + generation === this.renderSequence && + sequence === surface.renderSequence && + surface.pageNumber === pageNumber + ) { + this.drawSurfaceSvg(surface, pageNumber, svg); + return; + } const handle = await this.options.session.bitmap(pageNumber); try { if ( @@ -757,12 +796,52 @@ export class NoteReader { } } + // Displays a vector-ink page as an SVG (crisp at any zoom) in place + // of the raster canvas. The canvas backing is released - an SVG page + // holds no canvas memory, only the (small) SVG blob URL. + private drawSurfaceSvg( + surface: PageSurface, + pageNumber: number, + svg: string, + ): void { + this.releaseSurfaceSvg(surface); + const url = URL.createObjectURL( + new Blob([svg], { type: "image/svg+xml" }), + ); + surface.svgObjectUrl = url; + surface.image.src = url; + // No aspect-ratio var needed: the SVG has intrinsic dimensions, and the + // shared class's object-fit: contain letterboxes it correctly. + this.releaseCanvasResource(surface.canvas); + surface.canvas.width = 1; + surface.canvas.height = 1; + surface.canvas.hidden = true; + surface.image.hidden = false; + surface.displayKind = "image"; + surface.element.removeClass("is-loading"); + surface.canvas.removeClass("is-loading"); + if (this.surfaces?.current === surface) { + this.syncTransformGeometry(); + this.applyTransform(); + } + if ( + this.activeTransition?.targetPage === pageNumber && + this.transitionAnimationComplete + ) { + this.commitTransition(); + } + } + private drawSurfaceBitmap( surface: PageSurface, pageNumber: number, bitmap: ImageBitmap, preserveOnRejection = false, ): boolean { + this.releaseSurfaceSvg(surface); + surface.image.hidden = true; + surface.canvas.hidden = false; + surface.displayKind = "canvas"; const canvas = surface.canvas; canvas.style.setProperty( "--supernote-page-aspect-ratio", @@ -1385,20 +1464,24 @@ export class NoteReader { this.writeTrackPosition(writes.track.percent, writes.track.pixelOffset); } if (writes.canvas) { - const canvas = this.surfaces?.current.canvas; - if (canvas) { + const surface = this.surfaces?.current; + if (surface) { const zoomed = writes.canvas.zoom > 1; if (this.viewport?.hasClass("is-zoomed") !== zoomed) { this.viewport?.toggleClass("is-zoomed", zoomed); } - if (canvas.hasClass("is-transforming") !== zoomed) { - canvas.toggleClass("is-transforming", zoomed); + const animate = + writes.canvas.animate === true && !this.prefersReducedMotion(); + // Both display elements get the transform (one is always hidden), so + // whichever is visible - canvas for raster, img for vector SVG - + // zooms and pans identically. + for (const el of [surface.canvas, surface.image]) { + if (el.hasClass("is-transforming") !== zoomed) { + el.toggleClass("is-transforming", zoomed); + } + this.setTransformAnimation(el, animate); + el.style.transform = `translate(${writes.canvas.panX}px, ${writes.canvas.panY}px) scale(${writes.canvas.zoom})`; } - this.setTransformAnimation( - canvas, - writes.canvas.animate === true && !this.prefersReducedMotion(), - ); - canvas.style.transform = `translate(${writes.canvas.panX}px, ${writes.canvas.panY}px) scale(${writes.canvas.zoom})`; this.syncZoomToolbar(); } } @@ -1762,7 +1845,7 @@ export class NoteReader { } private setTransformAnimation( - canvas: HTMLCanvasElement, + canvas: HTMLElement, animate: boolean, ): void { if (!animate) { From def74e509ba29e33865d4f3ba5604d5af3b3e442 Mon Sep 17 00:00:00 2001 From: Paul Gebheim Date: Sun, 29 Nov 2026 02:00:32 +0000 Subject: [PATCH 5/8] feat: fit-width reading mode + wheel page-turn Fit-width is a new default reading mode: pages render at viewport width and scroll vertically with native scroll, instead of fit-page letterboxing. A toolbar toggle switches between fit-width and fit-page. - Two clean modes: fit-width (native scroll, transform zoom reset) and fit-page (whole page + transform zoom). Zooming in fit-width switches to fit-page first, so the two interaction models never fight. - Desktop is crisp for free (the canvas backing is already native-res); the SVG vector-ink pages are resolution-independent either way. - Wheel page-turn in fit-page at zoom=1: vertical wheel turns pages, with an accumulator + cooldown so a trackpad fling turns once. - Also fixes two pre-existing lint issues in notebook-worker-runtime.ts (bare 'object' param, uncommented 'as unknown as' cast). Stacked on feat/vector-ink. NEEDS VISUAL VERIFICATION - the mode toggle, scroll feel, and page-turn gestures should be tried in a real vault. --- src/note/notebook-service.ts | 3 +- src/note/notebook-worker-runtime.ts | 13 +++--- src/note/page-svg.ts | 6 ++- src/viewer/note-reader.ts | 63 +++++++++++++++++++++++++---- src/viewer/reader-toolbar.ts | 3 ++ styles.css | 16 ++++++++ tests/page-svg.test.ts | 20 ++++++++- tests/reader-toolbar.test.ts | 4 +- 8 files changed, 107 insertions(+), 21 deletions(-) diff --git a/src/note/notebook-service.ts b/src/note/notebook-service.ts index 64c3a74..a09973a 100644 --- a/src/note/notebook-service.ts +++ b/src/note/notebook-service.ts @@ -764,8 +764,7 @@ export class NotebookService implements NotebookSessionProvider { ), renderPng: (pageNumber, scale = 1, encoding) => this.renderPng(record, descriptor, pageNumber, scale, encoding), - renderSvg: (pageNumber) => - this.renderSvg(record, descriptor, pageNumber), + renderSvg: (pageNumber) => this.renderSvg(record, descriptor, pageNumber), updateView: (view) => this.updateView(record, descriptor, state, view), close: () => { if (state.closed) { diff --git a/src/note/notebook-worker-runtime.ts b/src/note/notebook-worker-runtime.ts index 5db9dcc..9c7da0c 100644 --- a/src/note/notebook-worker-runtime.ts +++ b/src/note/notebook-worker-runtime.ts @@ -50,7 +50,7 @@ const PROPERTY_SLOT_BYTES = 16; const STRING_HEADER_BYTES = 16; const estimateParsedMetadataBytes = ( - root: object, + root: unknown, sourceBuffer: ArrayBuffer, ): number => { const seenObjects = new WeakSet(); @@ -145,6 +145,8 @@ const pageFingerprint = (page: SupernoteX["pages"][number]): string => { }; const devicePage = (note: SupernoteX): number | null => { + // SAFETY: IHeader's type doesn't declare FINALOPERATION_PAGE, but real + // .note headers carry it - cast to a record to read the untyped field. const raw = (note.header as unknown as Record)[ "FINALOPERATION_PAGE" ]; @@ -312,7 +314,7 @@ export class NotebookWorkerRuntime { ); } - this.inFlightRenders += 1; + this.inFlightRenders += 1; this.activeRenderIds.add(request.id); try { this.throwIfCancelled(request.id); @@ -414,12 +416,7 @@ export class NotebookWorkerRuntime { vectorPage.strokes, vectorPage.styles, ); - return buildPageSvg( - note.pageWidth, - note.pageHeight, - pngBytes, - primitives, - ); + return buildPageSvg(note.pageWidth, note.pageHeight, pngBytes, primitives); } private throwIfCancelled(requestId: number): void { diff --git a/src/note/page-svg.ts b/src/note/page-svg.ts index f804a28..1a4728e 100644 --- a/src/note/page-svg.ts +++ b/src/note/page-svg.ts @@ -26,7 +26,11 @@ const encodeBase64 = (bytes: Uint8Array): string => { const c = bytes[index + 2]; chars.push(BASE64_CHARS[a >> 2]!); chars.push(BASE64_CHARS[((a & 0x03) << 4) | ((b ?? 0) >> 4)]!); - chars.push(b === undefined ? "=" : BASE64_CHARS[((b & 0x0f) << 2) | ((c ?? 0) >> 6)]!); + chars.push( + b === undefined + ? "=" + : BASE64_CHARS[((b & 0x0f) << 2) | ((c ?? 0) >> 6)]!, + ); chars.push(c === undefined ? "=" : BASE64_CHARS[c & 0x3f]!); } return chars.join(""); diff --git a/src/viewer/note-reader.ts b/src/viewer/note-reader.ts index 104ba60..3316607 100644 --- a/src/viewer/note-reader.ts +++ b/src/viewer/note-reader.ts @@ -199,6 +199,14 @@ export class NoteReader { private pagerPreparationGeneration = 0; private visible = true; private viewMode: "pager" | "grid" = "pager"; + // Fit-width (default) reads pages at viewport width with native vertical + // scroll; fit-page shows the whole page and enables the transform zoom. + private fitWidth = true; + // Wheel page-turn (fit-page only): accumulates vertical wheel delta and + // turns once per gesture, with a cooldown so a trackpad fling doesn't skip + // several pages. + private wheelTurnAccumulator = 0; + private wheelTurnCooldownUntil = 0; private rtl = false; private reducedMotion = false; private initialPageHandle: NoteReaderOptions["initialPageHandle"]; @@ -335,6 +343,9 @@ export class NoteReader { case "pages": this.renderGrid(); break; + case "toggle-fit-width": + this.toggleFitWidth(); + break; case "zoom-out": this.changeZoomByStep(-1); break; @@ -465,6 +476,7 @@ export class NoteReader { this.viewport = this.root.createDiv({ cls: "supernote-reader-viewport", }); + this.viewport.toggleClass("is-fit-width", this.fitWidth); this.track = this.viewport.createDiv({ cls: "supernote-reader-track", }); @@ -805,9 +817,7 @@ export class NoteReader { svg: string, ): void { this.releaseSurfaceSvg(surface); - const url = URL.createObjectURL( - new Blob([svg], { type: "image/svg+xml" }), - ); + const url = URL.createObjectURL(new Blob([svg], { type: "image/svg+xml" })); surface.svgObjectUrl = url; surface.image.src = url; // No aspect-ratio var needed: the SVG has intrinsic dimensions, and the @@ -1369,12 +1379,31 @@ export class NoteReader { if (this.activeTransition !== null) { return; } + if (this.fitWidth) { + // Zooming is a fit-page interaction; leave fit-width first. + this.fitWidth = false; + this.applyFitWidthMode(); + } this.syncTransformGeometry(); if (this.viewportTransform.stepZoom(direction)) { this.applyTransform(true); } } + private toggleFitWidth(): void { + this.fitWidth = !this.fitWidth; + this.applyFitWidthMode(); + } + + private applyFitWidthMode(): void { + this.viewport?.toggleClass("is-fit-width", this.fitWidth); + // Fit-width reads with native scroll, not the transform zoom - reset it + // so a stale pan/zoom doesn't leave the page offset. + if (this.fitWidth && this.viewportTransform.reset()) { + this.applyTransform(); + } + } + private returnToFit(): void { if (this.activeTransition !== null) { return; @@ -1516,6 +1545,29 @@ export class NoteReader { if (result.changed) { this.applyTransform(); } + // At fit-page (not zoomed, not fit-width's native scroll), an + // unconsumed vertical wheel turns the page. + if ( + !result.consumed && + !this.fitWidth && + !pageTransitionActive && + !this.viewportTransform.canZoomOut && + event.deltaY !== 0 + ) { + const now = performance.now(); + if (now < this.wheelTurnCooldownUntil) { + event.preventDefault(); + } else { + this.wheelTurnAccumulator += event.deltaY; + if (Math.abs(this.wheelTurnAccumulator) >= 60) { + const direction = this.wheelTurnAccumulator > 0 ? 1 : -1; + this.wheelTurnAccumulator = 0; + this.wheelTurnCooldownUntil = now + 250; + event.preventDefault(); + this.navigateBy(direction); + } + } + } }, { passive: false }, ); @@ -1844,10 +1896,7 @@ export class NoteReader { }; } - private setTransformAnimation( - canvas: HTMLElement, - animate: boolean, - ): void { + private setTransformAnimation(canvas: HTMLElement, animate: boolean): void { if (!animate) { if ( this.transformAnimationTimer !== null || diff --git a/src/viewer/reader-toolbar.ts b/src/viewer/reader-toolbar.ts index 6f76e18..42be8d7 100644 --- a/src/viewer/reader-toolbar.ts +++ b/src/viewer/reader-toolbar.ts @@ -2,6 +2,7 @@ export type ReaderToolbarMode = "pager" | "grid"; export type ReaderToolbarActionId = | "pages" + | "toggle-fit-width" | "zoom-out" | "zoom-in" | "copy-page" @@ -41,6 +42,7 @@ export const READER_TOOLBAR_ACTION_CATALOG: Readonly< Record > = { pages: { icon: "layout-grid", label: "Pages" }, + "toggle-fit-width": { icon: "unfold-horizontal", label: "Fit width" }, "zoom-out": { icon: "zoom-out", label: "Zoom out" }, "zoom-in": { icon: "zoom-in", label: "Zoom in" }, "copy-page": { icon: "copy", label: "Copy current page embed" }, @@ -124,6 +126,7 @@ export const readerToolbarPresentation = ( : []; const pagerActions = [ catalogAction("pages"), + catalogAction("toggle-fit-width"), ...zoomActions, catalogAction("copy-page"), catalogAction("copy-notebook"), diff --git a/styles.css b/styles.css index 07aaf9f..89cdd14 100644 --- a/styles.css +++ b/styles.css @@ -1324,3 +1324,19 @@ body.supernote-mobile-reader-active .mobile-navbar { transition: none !important; } } + +/* Fit-width reading mode (src/viewer/note-reader.ts): pages render at + viewport width and scroll vertically with native scroll, instead of the + default fit-page letterboxing. The transform zoom is a fit-page-mode + interaction and is reset while fit-width is active. */ +.supernote-reader-viewport.is-fit-width .supernote-reader-surface { + align-items: flex-start; + overflow-y: auto; +} + +.supernote-reader-viewport.is-fit-width .supernote-reader-canvas { + height: auto; + max-height: none; + max-width: 100%; + width: 100%; +} diff --git a/tests/page-svg.test.ts b/tests/page-svg.test.ts index 67e92c5..38fabee 100644 --- a/tests/page-svg.test.ts +++ b/tests/page-svg.test.ts @@ -54,8 +54,24 @@ describe("buildPageSvg", () => { it("draws rects, dimming hatch-filled ones", () => { const primitives: VectorInkPrimitive[] = [ - { kind: "rect", x: 1, y: 2, width: 3, height: 4, color: "rgb(0,0,0)", fill: "solid" }, - { kind: "rect", x: 5, y: 6, width: 7, height: 8, color: "rgb(0,0,0)", fill: "hatch" }, + { + kind: "rect", + x: 1, + y: 2, + width: 3, + height: 4, + color: "rgb(0,0,0)", + fill: "solid", + }, + { + kind: "rect", + x: 5, + y: 6, + width: 7, + height: 8, + color: "rgb(0,0,0)", + fill: "hatch", + }, ]; const svg = buildPageSvg(100, 100, PNG_BYTES, primitives); expect(svg).toContain( diff --git a/tests/reader-toolbar.test.ts b/tests/reader-toolbar.test.ts index 7a78752..a6cc9b9 100644 --- a/tests/reader-toolbar.test.ts +++ b/tests/reader-toolbar.test.ts @@ -21,13 +21,14 @@ describe("Reader toolbar presentation", () => { expect(presentation.visibleActions.map((action) => action.id)).toEqual([ "pages", + "toggle-fit-width", "zoom-out", "zoom-in", "copy-page", "copy-notebook", "export-current", ]); - expect(presentation.visibleActions.slice(1, 3)).toMatchObject([ + expect(presentation.visibleActions.slice(2, 4)).toMatchObject([ { id: "zoom-out", disabled: true }, { id: "zoom-in", disabled: false }, ]); @@ -67,6 +68,7 @@ describe("Reader toolbar presentation", () => { expect(presentation.visibleActions).toEqual([]); expect(presentation.menuActions.map((action) => action.id)).toEqual([ "pages", + "toggle-fit-width", "zoom-out", "zoom-in", "copy-page", From 08973b3c23cd19dac41440c61dff820cdd50d168 Mon Sep 17 00:00:00 2001 From: Paul Gebheim Date: Sun, 29 Nov 2026 02:36:42 +0000 Subject: [PATCH 6/8] fix: render page SVGs resolution-independent (viewBox only) The page SVG root carried fixed width/height (native page px), so the browser rasterized the once at that intrinsic size and magnified the resulting bitmap whenever the page was shown larger - fit-width on a wide viewport, or fit-page transform-zoom - which read as strokes going 'dotted'. Dropping the fixed width/height (keeping the viewBox, which still provides the intrinsic aspect ratio) makes the browser rasterize the SVG at the display size instead, so the vector strokes stay crisp at any size. Confirmed via the vector-ink pipeline that the strokes themselves are smooth (225 filledPath primitives with 4-269-point rings on the test note) - the generation was never the problem, only the fixed-size rasterization. --- src/note/page-svg.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/note/page-svg.ts b/src/note/page-svg.ts index 1a4728e..f1c54aa 100644 --- a/src/note/page-svg.ts +++ b/src/note/page-svg.ts @@ -61,8 +61,14 @@ export const buildPageSvg = ( backgroundPng: Uint8Array, primitives: readonly VectorInkPrimitive[], ): string => { + // viewBox only, no fixed width/height: an sizing this SVG then + // rasterizes it at the DISPLAY size (resolution-independent), instead of + // rasterizing once at a fixed intrinsic size and magnifying that bitmap + // when the page is shown larger (fit-width on a wide viewport, or zoom) - + // which read as "dotted" strokes. The viewBox still gives the its + // intrinsic aspect ratio. const parts = [ - ``, + ``, ``, ]; for (const primitive of primitives) { From e5105a2a0eb6a337b67195d7c518c855faa695d1 Mon Sep 17 00:00:00 2001 From: Paul Gebheim Date: Sun, 29 Nov 2026 03:06:05 +0000 Subject: [PATCH 7/8] feat: render pages with canvas-drawn vector strokes (crisp, anti-aliased) Replaces the SVG approach with philips' rendering technique: draw the vector strokes into the page raster via canvas in the worker, so the strokes are anti-aliased at render time instead of depending on the browser's SVG rasterizer (which came out aliased under Obsidian's GPU compositing - the 'dotted / no anti-aliasing' the SVG approach produced). - notebook-vector-render.ts: renderVectorPage rasterizes the ink-less background, then draws the vector-ink primitives (rect/filledPath/ strokedPath) onto an OffscreenCanvas via Path2D. The canvas anti-aliases the strokes. Returns null for non-vector pages so the caller falls back to the plain raster. Verified anti-aliased by rendering a real note in chromium. - The worker's decode() uses renderVectorPage for vector-eligible pages, so both the display bitmap and the export PNG get crisp strokes. - Reverts the reader's SVG display back to the plain bitmap path, and removes the now-dead SVG plumbing (renderSvg in the service, the svg worker output + protocol types, page-svg.ts). - drawPrimitives is unit-tested with a mock canvas context. Keeps fit-width, wheel page-turn, and the parser upgrade. The image-js stub stays (vector-ink still imports it via conversion.js). --- src/note/notebook-service.ts | 67 +------------- src/note/notebook-vector-render.ts | 121 +++++++++++++++++++++++++ src/note/notebook-worker-protocol.ts | 18 ---- src/note/notebook-worker-runtime.ts | 67 +++----------- src/note/notebook.worker.ts | 5 -- src/note/page-svg.ts | 97 -------------------- src/viewer/note-reader.ts | 99 ++------------------ tests/export-service.test.ts | 3 - tests/fixed-page-embed.test.ts | 1 - tests/notebook-embed.test.ts | 1 - tests/notebook-vector-render.test.ts | 130 +++++++++++++++++++++++++++ tests/page-svg.test.ts | 98 -------------------- tests/sync-service.test.ts | 1 - tests/watch-hooks.test.ts | 2 - 14 files changed, 272 insertions(+), 438 deletions(-) create mode 100644 src/note/notebook-vector-render.ts delete mode 100644 src/note/page-svg.ts create mode 100644 tests/notebook-vector-render.test.ts delete mode 100644 tests/page-svg.test.ts diff --git a/src/note/notebook-service.ts b/src/note/notebook-service.ts index a09973a..6abac3e 100644 --- a/src/note/notebook-service.ts +++ b/src/note/notebook-service.ts @@ -54,10 +54,6 @@ export interface NotebookSessionLease { scale?: number, encoding?: "opaque-rgb", ): Promise; - /** SVG document for the page with vector ink (crisp at any zoom), or null - * when the page has no trustworthy vector ink and the caller should fall - * back to the bitmap. */ - renderSvg(pageNumber: number): Promise; updateView(state: NotebookViewResourceState): NotebookViewUpdateResult; close(): void; } @@ -201,14 +197,7 @@ interface PendingPng extends PendingRenderBase { reject: (error: Error) => void; } -interface PendingSvg extends PendingRenderBase { - readonly output: "svg"; - readonly promise: Promise; - resolve: (svg: string | null) => void; - reject: (error: Error) => void; -} - -type PendingRender = PendingBitmap | PendingPng | PendingSvg; +type PendingRender = PendingBitmap | PendingPng; const deferred = (): { promise: Promise; @@ -711,9 +700,6 @@ export class NotebookService implements NotebookSessionProvider { ...response.page, png: response.page.png, }); - } else if (response.output === "svg" && pending.output === "svg") { - pending.settled = true; - pending.resolve(response.svg); } else { if (response.output === "bitmap") { response.bitmap.close(); @@ -764,7 +750,6 @@ export class NotebookService implements NotebookSessionProvider { ), renderPng: (pageNumber, scale = 1, encoding) => this.renderPng(record, descriptor, pageNumber, scale, encoding), - renderSvg: (pageNumber) => this.renderSvg(record, descriptor, pageNumber), updateView: (view) => this.updateView(record, descriptor, state, view), close: () => { if (state.closed) { @@ -1025,56 +1010,6 @@ export class NotebookService implements NotebookSessionProvider { return render.promise; } - // Display-path sibling of renderPng: the page as an SVG document with - // vector ink (crisp at any zoom), or null when the page has no - // trustworthy vector ink and the caller should fall back to the bitmap. - // Unlike renderPng this is a display render, so it neither releases - // display resources nor drops to export priority. - private renderSvg( - record: SessionRecord, - descriptor: NotebookDescriptor, - pageNumber: number, - ): Promise { - const invalid = this.renderError(record, descriptor, pageNumber); - if (invalid) { - return Promise.reject(invalid); - } - if (!record.resident || record.opening) { - return this.ensureResident(record).then(() => - this.renderSvg(record, descriptor, pageNumber), - ); - } - record.lastUsed = ++this.resourceClock; - const pending = deferred(); - const id = this.nextRequestId++; - const render: PendingSvg = { - id, - output: "svg", - record, - request: { - type: "render", - id, - sessionId: record.id, - generation: record.generation, - pageNumber, - output: "svg", - }, - priority: RENDER_PRIORITY.currentPage, - sequence: this.nextRenderSequence++, - // The worker decodes the page background and holds the SVG string; - // two page buffers is a fair reservation. - estimatedBytes: record.pagePixelBytes * 2, - state: "queued", - reservationActive: false, - settled: false, - promise: pending.promise, - resolve: pending.resolve, - reject: pending.reject, - }; - this.enqueue(render); - return render.promise; - } - private releaseDisplayResourcesForExport(record: SessionRecord): void { for (const bitmap of [...record.bitmaps.values()]) { if (bitmap.kind === "display" && bitmap.borrows === 0) { diff --git a/src/note/notebook-vector-render.ts b/src/note/notebook-vector-render.ts new file mode 100644 index 0000000..0fbd3cf --- /dev/null +++ b/src/note/notebook-vector-render.ts @@ -0,0 +1,121 @@ +import type { SupernoteX } from "supernote-typescript/lib/parsing"; +import type { IStrokePoint } from "supernote-typescript/lib/strokes"; +import { + buildVectorInkBackgroundNote, + buildVectorInkPrimitives, + prepareVectorInkPages, + type VectorInkPrimitive, +} from "supernote-typescript/lib/vector-ink"; + +import { + rasterizeNotebookPage, + type BitmapBackgroundDecoder, + type RasterizedNotebookPage, +} from "./notebook-rasterizer"; + +// Renders a notebook page to pixels with its pen strokes drawn as real +// vector paths on a canvas, over the raster background (templates/images, +// ink layers removed). The canvas anti-aliases the strokes, so they render +// smooth - unlike the device's 1-bit RLE ink raster, which reads as +// "dotted / no anti-aliasing" when scaled. Returns null when the page has +// no trustworthy vector ink, so the caller falls back to the plain raster. +// +// This is the same technique the other Supernote viewer uses (draw vector +// strokes into a raster at render time) rather than handing the browser an +// SVG and depending on its rasterizer - which under Obsidian's GPU +// compositing came out aliased. Worker-safe: OffscreenCanvas + Path2D, no +// image-js, no obsidian. + +const pointsToPath = (points: readonly IStrokePoint[]): string => { + const [first, ...rest] = points; + if (!first) return ""; + const coord = (value: number): string => { + const rounded = Math.round(value * 100) / 100; + return Object.is(rounded, -0) ? "0" : String(rounded); + }; + return ( + `M${coord(first.x)} ${coord(first.y)}` + + rest.map((point) => `L${coord(point.x)} ${coord(point.y)}`).join("") + ); +}; + +export const drawPrimitives = ( + context: OffscreenCanvasRenderingContext2D, + primitives: readonly VectorInkPrimitive[], +): void => { + for (const primitive of primitives) { + if (primitive.kind === "rect") { + context.fillStyle = primitive.color; + // 'hatch' is a cross-hatch heading background; a reduced opacity + // approximates "visibly non-solid" without a pattern per page. + context.globalAlpha = primitive.fill === "hatch" ? 0.35 : 1; + context.fillRect( + primitive.x, + primitive.y, + primitive.width, + primitive.height, + ); + context.globalAlpha = 1; + } else if (primitive.kind === "filledPath") { + context.fillStyle = primitive.color; + const d = primitive.rings + .map((ring) => `${pointsToPath(ring)}Z`) + .join(" "); + context.fill(new Path2D(d), "evenodd"); + } else { + context.strokeStyle = primitive.color; + context.lineWidth = primitive.width; + context.lineCap = "round"; + context.lineJoin = "round"; + context.stroke(new Path2D(pointsToPath(primitive.points))); + } + } +}; + +export const renderVectorPage = async ( + note: SupernoteX, + pageNumber: number, + decodeBitmapBackground: BitmapBackgroundDecoder, +): Promise => { + const vectorPages = prepareVectorInkPages(note, [pageNumber], 1); + const vectorPage = vectorPages[0]; + if (!vectorPage?.useVectorInk) { + return null; + } + + const backgroundNote = buildVectorInkBackgroundNote(note, vectorPages); + const backgroundPage = backgroundNote.pages[pageNumber - 1]!; + const background = await rasterizeNotebookPage( + note.pageWidth, + note.pageHeight, + { + pageStyle: backgroundPage.PAGESTYLE, + layerSequence: backgroundPage.LAYERSEQ, + layers: Object.fromEntries( + backgroundPage.LAYERSEQ.map((name) => [name, backgroundPage[name]]), + ), + }, + decodeBitmapBackground, + ); + + const canvas = new OffscreenCanvas(note.pageWidth, note.pageHeight); + const context = canvas.getContext("2d", { willReadFrequently: true }); + if (!context) { + throw new Error("Supernote worker cannot create a 2D canvas"); + } + context.putImageData( + new ImageData(background.pixels, background.width, background.height), + 0, + 0, + ); + drawPrimitives( + context, + buildVectorInkPrimitives(vectorPage.strokes, vectorPage.styles), + ); + + return { + width: note.pageWidth, + height: note.pageHeight, + pixels: context.getImageData(0, 0, note.pageWidth, note.pageHeight).data, + }; +}; diff --git a/src/note/notebook-worker-protocol.ts b/src/note/notebook-worker-protocol.ts index 1b5d1aa..d73a3d1 100644 --- a/src/note/notebook-worker-protocol.ts +++ b/src/note/notebook-worker-protocol.ts @@ -42,14 +42,6 @@ export type NotebookWorkerRequest = output: "png"; scale: number; encoding?: "opaque-rgb"; - } - | { - type: "render"; - id: number; - sessionId: number; - generation: number; - pageNumber: number; - output: "svg"; }; export type NotebookWorkerResponse = @@ -88,14 +80,4 @@ export type NotebookWorkerResponse = generation: number; output: "png"; page: RenderedNotebookPage; - } - | { - type: "rendered"; - id: number; - sessionId: number; - generation: number; - output: "svg"; - /** Null when the page has no trustworthy vector ink - the caller - * falls back to the bitmap path for it. */ - svg: string | null; }; diff --git a/src/note/notebook-worker-runtime.ts b/src/note/notebook-worker-runtime.ts index 9c7da0c..c6c266f 100644 --- a/src/note/notebook-worker-runtime.ts +++ b/src/note/notebook-worker-runtime.ts @@ -1,10 +1,5 @@ import { SupernoteX } from "supernote-typescript/lib/parsing"; -import { - buildVectorInkBackgroundNote, - buildVectorInkPrimitives, - prepareVectorInkPages, -} from "supernote-typescript/lib/vector-ink"; -import { buildPageSvg } from "./page-svg"; +import { renderVectorPage } from "./notebook-vector-render"; import SparkMD5 from "spark-md5"; import { @@ -318,18 +313,6 @@ export class NotebookWorkerRuntime { this.activeRenderIds.add(request.id); try { this.throwIfCancelled(request.id); - if (request.output === "svg") { - const svg = await this.renderSvg(session, request.pageNumber); - this.throwIfCancelled(request.id); - return { - type: "rendered", - id: request.id, - sessionId: request.sessionId, - generation: request.generation, - output: "svg", - svg, - }; - } const decoded = await this.decode(session, request.pageNumber); this.throwIfCancelled(request.id); this.renderCount += 1; @@ -381,44 +364,6 @@ export class NotebookWorkerRuntime { } } - // Renders one page as a standalone SVG document: the page's raster - // background (templates/images, ink layers removed) with the pen strokes - // drawn as real vector paths on top (supernote-typescript 0.7.x's - // vector-ink machinery), so the page stays crisp at any zoom. Returns - // null when the page's strokes don't decode trustworthily - the caller - // then falls back to the raster bitmap for that page. - private async renderSvg( - session: WorkerSession, - pageNumber: number, - ): Promise { - const note = session.note; - const vectorPages = prepareVectorInkPages(note, [pageNumber], 1); - const vectorPage = vectorPages[0]; - if (!vectorPage?.useVectorInk) { - return null; - } - const backgroundNote = buildVectorInkBackgroundNote(note, vectorPages); - const backgroundPage = backgroundNote.pages[pageNumber - 1]!; - const decoded = await rasterizeNotebookPage( - note.pageWidth, - note.pageHeight, - { - pageStyle: backgroundPage.PAGESTYLE, - layerSequence: backgroundPage.LAYERSEQ, - layers: Object.fromEntries( - backgroundPage.LAYERSEQ.map((name) => [name, backgroundPage[name]]), - ), - }, - (bytes) => this.imageCodec.decodeBitmap(bytes), - ); - const pngBytes = await this.imageCodec.encodePng(decoded); - const primitives = buildVectorInkPrimitives( - vectorPage.strokes, - vectorPage.styles, - ); - return buildPageSvg(note.pageWidth, note.pageHeight, pngBytes, primitives); - } - private throwIfCancelled(requestId: number): void { if (this.cancelledRenders.has(requestId)) { throw new NotebookWorkerRenderCancelledError(); @@ -429,6 +374,16 @@ export class NotebookWorkerRuntime { session: WorkerSession, pageNumber: number, ): Promise { + // Prefer vector-drawn strokes (anti-aliased by the canvas) over the + // device's 1-bit ink raster, which reads as dotted/aliased when scaled. + const vectorPage = await renderVectorPage( + session.note, + pageNumber, + (bytes) => this.imageCodec.decodeBitmap(bytes), + ); + if (vectorPage) { + return vectorPage; + } const page = session.note.pages[pageNumber - 1]!; return rasterizeNotebookPage( session.note.pageWidth, diff --git a/src/note/notebook.worker.ts b/src/note/notebook.worker.ts index 4933309..8438ed1 100644 --- a/src/note/notebook.worker.ts +++ b/src/note/notebook.worker.ts @@ -27,11 +27,6 @@ workerScope.onmessage = (event): void => { workerScope.postMessage(response, [response.bitmap]); return; } - if (response.output === "svg") { - // Plain string payload - nothing to transfer. - workerScope.postMessage(response); - return; - } const buffer = response.page.png.buffer; workerScope.postMessage( { diff --git a/src/note/page-svg.ts b/src/note/page-svg.ts deleted file mode 100644 index f1c54aa..0000000 --- a/src/note/page-svg.ts +++ /dev/null @@ -1,97 +0,0 @@ -import type { IStrokePoint } from "supernote-typescript/lib/strokes"; -import type { VectorInkPrimitive } from "supernote-typescript/lib/vector-ink"; - -// Builds one standalone SVG document for a notebook page: the rasterized -// background (templates/images, ink layers already removed by the caller) -// embedded as a PNG data URI, with the page's pen strokes drawn as real -// vector elements on top - so the page stays crisp at any zoom. -// -// Vendored rather than taken from supernote-typescript's svg.ts: that -// module imports pdf.js (for recognitionCoordinateScale), which pulls -// pdf-lib - and pdf-lib is banned from the notebook worker bundle (see -// esbuild.config.mjs's assertAbsent). The recognition-text overlay svg.ts -// adds is invisible/search-only and meaningless inside the plugin's own -// reader, so this builder leaves it out. Pure and worker-safe. - -const BASE64_CHARS = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -// Base64 without Buffer (Node-only) or btoa (call-stack-limited on large -// inputs) - same reasoning as supernote-typescript's own helper. -const encodeBase64 = (bytes: Uint8Array): string => { - const chars: string[] = []; - for (let index = 0; index < bytes.length; index += 3) { - const a = bytes[index]!; - const b = bytes[index + 1]; - const c = bytes[index + 2]; - chars.push(BASE64_CHARS[a >> 2]!); - chars.push(BASE64_CHARS[((a & 0x03) << 4) | ((b ?? 0) >> 4)]!); - chars.push( - b === undefined - ? "=" - : BASE64_CHARS[((b & 0x0f) << 2) | ((c ?? 0) >> 6)]!, - ); - chars.push(c === undefined ? "=" : BASE64_CHARS[c & 0x3f]!); - } - return chars.join(""); -}; - -// Two decimals keeps dense pages' path data compact without visible -// coordinate loss at page scale. -const coord = (value: number): string => { - const rounded = Math.round(value * 100) / 100; - return Object.is(rounded, -0) ? "0" : String(rounded); -}; - -const pointsToPath = (points: readonly IStrokePoint[]): string => { - const [first, ...rest] = points; - if (!first) return ""; - return ( - `M${coord(first.x)} ${coord(first.y)}` + - rest.map((point) => `L${coord(point.x)} ${coord(point.y)}`).join("") - ); -}; - -const escapeAttr = (value: string): string => - value.replace(/&/g, "&").replace(/"/g, """).replace(/ { - // viewBox only, no fixed width/height: an sizing this SVG then - // rasterizes it at the DISPLAY size (resolution-independent), instead of - // rasterizing once at a fixed intrinsic size and magnifying that bitmap - // when the page is shown larger (fit-width on a wide viewport, or zoom) - - // which read as "dotted" strokes. The viewBox still gives the its - // intrinsic aspect ratio. - const parts = [ - ``, - ``, - ]; - for (const primitive of primitives) { - if (primitive.kind === "rect") { - // 'hatch' is a cross-hatch heading background; a reduced opacity - // approximates "visibly non-solid" without a pattern def per page. - const opacity = primitive.fill === "hatch" ? ' fill-opacity="0.35"' : ""; - parts.push( - ``, - ); - } else if (primitive.kind === "filledPath") { - const d = primitive.rings - .map((ring) => `${pointsToPath(ring)}Z`) - .join(" "); - parts.push( - ``, - ); - } else { - parts.push( - ``, - ); - } - } - parts.push(""); - return parts.join(""); -}; diff --git a/src/viewer/note-reader.ts b/src/viewer/note-reader.ts index 3316607..e939734 100644 --- a/src/viewer/note-reader.ts +++ b/src/viewer/note-reader.ts @@ -114,11 +114,6 @@ interface NoteReaderOptions { interface PageSurface { element: HTMLElement; canvas: HTMLCanvasElement; - // Vector-ink pages display as an SVG (crisp at any zoom) instead of - // the raster canvas; exactly one of the two is visible at a time. - image: HTMLImageElement; - svgObjectUrl: string | null; - displayKind: "canvas" | "image"; pageNumber: number | null; renderSequence: number; } @@ -594,18 +589,9 @@ export class NoteReader { this.releaseCanvasResource(surface.canvas); surface.canvas.width = 1; surface.canvas.height = 1; - this.releaseSurfaceSvg(surface); surface.element.remove(); } - private releaseSurfaceSvg(surface: PageSurface): void { - if (surface.svgObjectUrl !== null) { - URL.revokeObjectURL(surface.svgObjectUrl); - surface.svgObjectUrl = null; - } - surface.image.removeAttribute("src"); - } - private createPageSurface(): PageSurface { const element = document.createElement("div"); element.addClass("supernote-reader-surface"); @@ -614,20 +600,9 @@ export class NoteReader { attr: { width: "1", height: "1" }, }); this.resizeCanvas(canvas, 3, 4); - // Same class as the canvas so it inherits the page layout CSS - // (aspect-ratio, object-fit, transform-origin); hidden until an SVG - // page uses it. - const image = element.createEl("img", { - cls: "supernote-reader-canvas", - attr: { alt: "" }, - }); - image.hidden = true; return { element, canvas, - image, - svgObjectUrl: null, - displayKind: "canvas", pageNumber: null, renderSequence: 0, }; @@ -750,20 +725,6 @@ export class NoteReader { generation: number, ): Promise { try { - // Prefer the vector-ink SVG (crisp at any zoom); pages without - // trustworthy vector ink return null and use the raster bitmap. - const svg = await this.options.session - .renderSvg(pageNumber) - .catch(() => null); - if ( - svg !== null && - generation === this.renderSequence && - sequence === surface.renderSequence && - surface.pageNumber === pageNumber - ) { - this.drawSurfaceSvg(surface, pageNumber, svg); - return; - } const handle = await this.options.session.bitmap(pageNumber); try { if ( @@ -808,50 +769,12 @@ export class NoteReader { } } - // Displays a vector-ink page as an SVG (crisp at any zoom) in place - // of the raster canvas. The canvas backing is released - an SVG page - // holds no canvas memory, only the (small) SVG blob URL. - private drawSurfaceSvg( - surface: PageSurface, - pageNumber: number, - svg: string, - ): void { - this.releaseSurfaceSvg(surface); - const url = URL.createObjectURL(new Blob([svg], { type: "image/svg+xml" })); - surface.svgObjectUrl = url; - surface.image.src = url; - // No aspect-ratio var needed: the SVG has intrinsic dimensions, and the - // shared class's object-fit: contain letterboxes it correctly. - this.releaseCanvasResource(surface.canvas); - surface.canvas.width = 1; - surface.canvas.height = 1; - surface.canvas.hidden = true; - surface.image.hidden = false; - surface.displayKind = "image"; - surface.element.removeClass("is-loading"); - surface.canvas.removeClass("is-loading"); - if (this.surfaces?.current === surface) { - this.syncTransformGeometry(); - this.applyTransform(); - } - if ( - this.activeTransition?.targetPage === pageNumber && - this.transitionAnimationComplete - ) { - this.commitTransition(); - } - } - private drawSurfaceBitmap( surface: PageSurface, pageNumber: number, bitmap: ImageBitmap, preserveOnRejection = false, ): boolean { - this.releaseSurfaceSvg(surface); - surface.image.hidden = true; - surface.canvas.hidden = false; - surface.displayKind = "canvas"; const canvas = surface.canvas; canvas.style.setProperty( "--supernote-page-aspect-ratio", @@ -1493,24 +1416,20 @@ export class NoteReader { this.writeTrackPosition(writes.track.percent, writes.track.pixelOffset); } if (writes.canvas) { - const surface = this.surfaces?.current; - if (surface) { + const canvas = this.surfaces?.current.canvas; + if (canvas) { const zoomed = writes.canvas.zoom > 1; if (this.viewport?.hasClass("is-zoomed") !== zoomed) { this.viewport?.toggleClass("is-zoomed", zoomed); } - const animate = - writes.canvas.animate === true && !this.prefersReducedMotion(); - // Both display elements get the transform (one is always hidden), so - // whichever is visible - canvas for raster, img for vector SVG - - // zooms and pans identically. - for (const el of [surface.canvas, surface.image]) { - if (el.hasClass("is-transforming") !== zoomed) { - el.toggleClass("is-transforming", zoomed); - } - this.setTransformAnimation(el, animate); - el.style.transform = `translate(${writes.canvas.panX}px, ${writes.canvas.panY}px) scale(${writes.canvas.zoom})`; + if (canvas.hasClass("is-transforming") !== zoomed) { + canvas.toggleClass("is-transforming", zoomed); } + this.setTransformAnimation( + canvas, + writes.canvas.animate === true && !this.prefersReducedMotion(), + ); + canvas.style.transform = `translate(${writes.canvas.panX}px, ${writes.canvas.panY}px) scale(${writes.canvas.zoom})`; this.syncZoomToolbar(); } } diff --git a/tests/export-service.test.ts b/tests/export-service.test.ts index 6e1ea2d..7874c69 100644 --- a/tests/export-service.test.ts +++ b/tests/export-service.test.ts @@ -149,7 +149,6 @@ const createService = ( }), bitmap: vi.fn(), thumbnailBitmap: vi.fn(), - renderSvg: vi.fn(async () => null), renderPng: vi.fn( overrides.renderPng ?? (async (pageNumber: number) => ({ @@ -202,7 +201,6 @@ describe("ExportService", () => { }), bitmap: vi.fn(), thumbnailBitmap: vi.fn(), - renderSvg: vi.fn(async () => null), renderPng, updateView: vi.fn(), close, @@ -253,7 +251,6 @@ describe("ExportService", () => { }), bitmap: vi.fn(), thumbnailBitmap: vi.fn(), - renderSvg: vi.fn(async () => null), renderPng: vi.fn(async () => ({ png: new Uint8Array([1]), width: 1920, diff --git a/tests/fixed-page-embed.test.ts b/tests/fixed-page-embed.test.ts index bff0bd2..b26ef55 100644 --- a/tests/fixed-page-embed.test.ts +++ b/tests/fixed-page-embed.test.ts @@ -59,7 +59,6 @@ const createLease = ( thumbnailBitmap: vi .fn() .mockReturnValue(options.bitmapPromise ?? Promise.resolve(handle)), - renderSvg: vi.fn(async () => null), renderPng: vi.fn(), updateView: vi .fn() diff --git a/tests/notebook-embed.test.ts b/tests/notebook-embed.test.ts index a98d644..1b14e97 100644 --- a/tests/notebook-embed.test.ts +++ b/tests/notebook-embed.test.ts @@ -63,7 +63,6 @@ const createLease = ( options.render?.(pageNumber, signal) ?? Promise.resolve(createHandle(pageNumber)), ), - renderSvg: vi.fn(async () => null), renderPng: vi.fn(), updateView: vi.fn().mockReturnValue({ updated: true }), close: vi.fn(), diff --git a/tests/notebook-vector-render.test.ts b/tests/notebook-vector-render.test.ts new file mode 100644 index 0000000..8853e12 --- /dev/null +++ b/tests/notebook-vector-render.test.ts @@ -0,0 +1,130 @@ +import { describe, expect, it, vi } from "vitest"; + +import { drawPrimitives } from "../src/note/notebook-vector-render"; +import type { VectorInkPrimitive } from "supernote-typescript/lib/vector-ink"; + +// A mock 2D context recording the calls drawPrimitives makes, so the +// primitive -> canvas mapping is testable without a real OffscreenCanvas +// (unavailable under vitest's node environment). +const mockContext = () => { + const fills: { d: string; rule: string; style: unknown }[] = []; + const strokes: { d: string; style: unknown; width: number }[] = []; + const rects: { x: number; y: number; w: number; h: number; alpha: number }[] = + []; + const context = { + fillStyle: "" as unknown, + strokeStyle: "" as unknown, + lineWidth: 0, + lineCap: "", + lineJoin: "", + globalAlpha: 1, + fillRect(x: number, y: number, w: number, h: number) { + rects.push({ x, y, w, h, alpha: this.globalAlpha }); + }, + fill(path: Path2D, rule: string) { + fills.push({ + d: (path as unknown as { d: string }).d, + rule, + style: this.fillStyle, + }); + }, + stroke(path: Path2D) { + strokes.push({ + d: (path as unknown as { d: string }).d, + style: this.strokeStyle, + width: this.lineWidth, + }); + }, + }; + return { + context: context as unknown as OffscreenCanvasRenderingContext2D, + fills, + strokes, + rects, + }; +}; + +// Path2D isn't available under node either; stub it to capture the path data. +vi.stubGlobal( + "Path2D", + class { + d: string; + constructor(d: string) { + this.d = d; + } + }, +); + +describe("drawPrimitives", () => { + it("fills a solid rect at full opacity", () => { + const { context, rects } = mockContext(); + drawPrimitives(context, [ + { + kind: "rect", + x: 1, + y: 2, + width: 3, + height: 4, + color: "rgb(0,0,0)", + fill: "solid", + }, + ]); + expect(rects).toEqual([{ x: 1, y: 2, w: 3, h: 4, alpha: 1 }]); + }); + + it("dims a hatch rect", () => { + const { context, rects } = mockContext(); + drawPrimitives(context, [ + { + kind: "rect", + x: 0, + y: 0, + width: 5, + height: 5, + color: "rgb(0,0,0)", + fill: "hatch", + }, + ]); + expect(rects[0]!.alpha).toBe(0.35); + }); + + it("fills a filledPath's rings with the evenodd rule", () => { + const { context, fills } = mockContext(); + const primitive: VectorInkPrimitive = { + kind: "filledPath", + rings: [ + [ + { x: 0, y: 0 }, + { x: 10, y: 0 }, + { x: 10, y: 10 }, + ], + ], + color: "rgb(128,128,128)", + }; + drawPrimitives(context, [primitive]); + expect(fills).toHaveLength(1); + expect(fills[0]!.rule).toBe("evenodd"); + expect(fills[0]!.style).toBe("rgb(128,128,128)"); + expect(fills[0]!.d).toBe("M0 0L10 0L10 10Z"); + }); + + it("strokes a strokedPath with round caps and the stroke's width/color", () => { + const { context, strokes } = mockContext(); + const primitive: VectorInkPrimitive = { + kind: "strokedPath", + points: [ + { x: 1, y: 2 }, + { x: 3, y: 4 }, + ], + color: "rgb(0,0,0)", + width: 2.5, + }; + drawPrimitives(context, [primitive]); + expect(strokes).toHaveLength(1); + expect(strokes[0]!.d).toBe("M1 2L3 4"); + expect(strokes[0]!.width).toBe(2.5); + expect(strokes[0]!.style).toBe("rgb(0,0,0)"); + expect(context.lineCap).toBe("round"); + expect(context.lineJoin).toBe("round"); + }); +}); diff --git a/tests/page-svg.test.ts b/tests/page-svg.test.ts deleted file mode 100644 index 38fabee..0000000 --- a/tests/page-svg.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { buildPageSvg } from "../src/note/page-svg"; -import type { VectorInkPrimitive } from "supernote-typescript/lib/vector-ink"; - -const PNG_BYTES = new Uint8Array([1, 2, 3, 4, 5]); - -describe("buildPageSvg", () => { - it("embeds the background PNG as a data URI sized to the page", () => { - const svg = buildPageSvg(100, 200, PNG_BYTES, []); - expect(svg).toContain('viewBox="0 0 100 200"'); - expect(svg).toContain( - ``, - ); - }); - - it("draws a stroked path with round caps and the stroke's own width/color", () => { - const primitives: VectorInkPrimitive[] = [ - { - kind: "strokedPath", - points: [ - { x: 1, y: 2 }, - { x: 3.456, y: 4 }, - ], - color: "rgb(0,0,0)", - width: 2.5, - }, - ]; - const svg = buildPageSvg(100, 100, PNG_BYTES, primitives); - expect(svg).toContain( - '', - ); - }); - - it("draws filled rings with the evenodd rule and closes each ring", () => { - const primitives: VectorInkPrimitive[] = [ - { - kind: "filledPath", - rings: [ - [ - { x: 0, y: 0 }, - { x: 10, y: 0 }, - { x: 10, y: 10 }, - ], - ], - color: "rgb(128,128,128)", - }, - ]; - const svg = buildPageSvg(100, 100, PNG_BYTES, primitives); - expect(svg).toContain( - '', - ); - }); - - it("draws rects, dimming hatch-filled ones", () => { - const primitives: VectorInkPrimitive[] = [ - { - kind: "rect", - x: 1, - y: 2, - width: 3, - height: 4, - color: "rgb(0,0,0)", - fill: "solid", - }, - { - kind: "rect", - x: 5, - y: 6, - width: 7, - height: 8, - color: "rgb(0,0,0)", - fill: "hatch", - }, - ]; - const svg = buildPageSvg(100, 100, PNG_BYTES, primitives); - expect(svg).toContain( - '', - ); - expect(svg).toContain( - '', - ); - }); - - it("escapes attribute values in colors", () => { - const primitives: VectorInkPrimitive[] = [ - { - kind: "strokedPath", - points: [{ x: 0, y: 0 }], - color: 'rgb(0,0,0)" onload="alert(1)', - width: 1, - }, - ]; - const svg = buildPageSvg(100, 100, PNG_BYTES, primitives); - expect(svg).not.toContain('onload="alert'); - expect(svg).toContain("""); - }); -}); diff --git a/tests/sync-service.test.ts b/tests/sync-service.test.ts index b1db39e..e897409 100644 --- a/tests/sync-service.test.ts +++ b/tests/sync-service.test.ts @@ -98,7 +98,6 @@ const createNotebooks = ( }), bitmap: vi.fn(), thumbnailBitmap: vi.fn(), - renderSvg: vi.fn(async () => null), renderPng: vi.fn(), updateView: vi.fn(), close: vi.fn(), diff --git a/tests/watch-hooks.test.ts b/tests/watch-hooks.test.ts index bd03f71..01b4546 100644 --- a/tests/watch-hooks.test.ts +++ b/tests/watch-hooks.test.ts @@ -120,7 +120,6 @@ const setup = ( vault.text.set("supernote/.sync-manifest.json", JSON.stringify(manifest())); const renderer = { pageMd5s: vi.fn(() => pageMd5s), - renderSvg: vi.fn(async () => null), renderPng: vi.fn(async (pageNumber: number) => ({ png: new Uint8Array([pageNumber]), width: 1920, @@ -150,7 +149,6 @@ const setup = ( }), bitmap: vi.fn(), thumbnailBitmap: vi.fn(), - renderSvg: vi.fn(async () => null), renderPng: renderer.renderPng, updateView: vi.fn(), close: vi.fn(), From 86662e827b0b281643a59a5c57fa976703ec3e78 Mon Sep 17 00:00:00 2001 From: Paul Gebheim Date: Sun, 29 Nov 2026 01:52:33 +0000 Subject: [PATCH 8/8] fix: open notes at page 1, not the device's last-viewed page A fresh reader open fell back to session.descriptor.devicePage (FINALOPERATION_PAGE - the page the note was last on when used on the device), so any note read to the end on the device reopened on its last page. Fresh opens now start at page 1; reloads of the same notebook still keep the reader's current page (previous.currentPage), and explicit page navigation (pendingPage) is unaffected. --- src/viewer/note-view.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/viewer/note-view.ts b/src/viewer/note-view.ts index aefa7d4..cb9acfe 100644 --- a/src/viewer/note-view.ts +++ b/src/viewer/note-view.ts @@ -412,9 +412,11 @@ export class SupernoteNoteView extends FileView { } const pageOpen = planPageOpen( this.pendingPage, - (sameNotebook ? previous?.currentPage : null) ?? - session.descriptor.devicePage ?? - 1, + // Open at page 1, not the device's last-viewed page + // (FINALOPERATION_PAGE) - resuming mid-note on every fresh open read + // as "always starts on the last page". Reloads of the same notebook + // still keep the reader's current page via `previous`. + (sameNotebook ? previous?.currentPage : null) ?? 1, session.descriptor.pageCount, ); const handoff = planRevisionHandoff(