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/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/src/note/notebook-service.ts b/src/note/notebook-service.ts index 8982b23..6abac3e 100644 --- a/src/note/notebook-service.ts +++ b/src/note/notebook-service.ts @@ -1414,21 +1414,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/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-runtime.ts b/src/note/notebook-worker-runtime.ts index d6fec09..c6c266f 100644 --- a/src/note/notebook-worker-runtime.ts +++ b/src/note/notebook-worker-runtime.ts @@ -1,4 +1,5 @@ import { SupernoteX } from "supernote-typescript/lib/parsing"; +import { renderVectorPage } from "./notebook-vector-render"; import SparkMD5 from "spark-md5"; import { @@ -44,7 +45,7 @@ const PROPERTY_SLOT_BYTES = 16; const STRING_HEADER_BYTES = 16; const estimateParsedMetadataBytes = ( - root: object, + root: unknown, sourceBuffer: ArrayBuffer, ): number => { const seenObjects = new WeakSet(); @@ -139,6 +140,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" ]; @@ -371,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/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/src/viewer/note-reader.ts b/src/viewer/note-reader.ts index d65321a..e939734 100644 --- a/src/viewer/note-reader.ts +++ b/src/viewer/note-reader.ts @@ -194,6 +194,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"]; @@ -330,6 +338,9 @@ export class NoteReader { case "pages": this.renderGrid(); break; + case "toggle-fit-width": + this.toggleFitWidth(); + break; case "zoom-out": this.changeZoomByStep(-1); break; @@ -460,6 +471,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", }); @@ -1290,12 +1302,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; @@ -1433,6 +1464,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 }, ); @@ -1761,10 +1815,7 @@ export class NoteReader { }; } - private setTransformAnimation( - canvas: HTMLCanvasElement, - animate: boolean, - ): void { + private setTransformAnimation(canvas: HTMLElement, animate: boolean): void { if (!animate) { if ( this.transformAnimationTimer !== null || 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( 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/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/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, 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/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", 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), + ), }, }, });