Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): add the Excalidraw stroke Pressure setting (PRD-8471) (#4027)
Andrew Mikofalvyd9f059f9e7c3
diff --git a/.changeset/excalidraw-pressure-setting.md b/.changeset/excalidraw-pressure-setting.mdnew file mode 100644index 000000000..52b32cd32--- /dev/null+++ b/.changeset/excalidraw-pressure-setting.md@@ -0,0 +1,13 @@+---+'@inkeep/open-knowledge': patch+---++Excalidraw boards gain the stroke Pressure setting. The properties panel now offers Constant and Variable pressure for freehand strokes.++Freehand strokes you draw from now on are half the width they used to be at the same setting. Upstream halved the width scale for freehand strokes specifically, and it applies whichever Pressure setting you use. Picking the bold width restores the previous default exactly.++New strokes also default to Constant, an even line that holds one width end to end, and it is narrower again because the renderer that draws it scales differently from the one that tapers. The first time you draw with a pen, Variable is selected instead: there the width follows how hard you press, which is how freehand strokes have always been drawn here, though a pen stroke now tracks your hand a little more closely than it used to. Switch between them in the properties panel. Strokes already on your boards keep the width and the look they have.++The first time you open each board, its file is rewritten once to pick up the new format fields. Your drawings are unchanged by that rewrite. If your content directory is tracked in git, expect each board to appear as modified as you open it; boards you have not opened stay untouched, and a board that has been rewritten is stable from then on.++Sharing a board is safe. Excalidraw builds older than this upstream change do not know the Constant setting, so a stroke set to Constant draws with their variable-width renderer, and the VS Code extension and older Open Knowledge builds are the ones you are most likely to meet. They do not discard the setting: reopen the board here and the stroke is Constant again. Builds that already track the change, excalidraw.com and the Obsidian plugin among them, draw it as Constant.diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 9e7dbca9c..6415a2e7d 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -869,7 +869,7 @@ Homepage: https://github.com/gr2m/before-after-hookCopyright 2018 Gregor Martynus and other contributors.-### `[email protected]`+### `[email protected]`Homepage: https://github.com/GoogleChromeLabs/browser-fs-access#readme_(LICENSE template present but no copyright line filled in; refer to the package source for canonical attribution.)_@@ -1351,7 +1351,17 @@ Homepage: https://github.com/clauderic/dnd-kitCopyright (c) 2021, Claudéric Demers-### `@excalidraw/[email protected]`+### `@excalidraw/[email protected]`+Homepage: https://github.com/excalidraw/excalidraw++_(No LICENSE file in package; SPDX identifier in `package.json` is the sole declared grant.)_++### `@excalidraw/[email protected]`+Homepage: https://github.com/excalidraw/excalidraw++_(No LICENSE file in package; SPDX identifier in `package.json` is the sole declared grant.)_++### `@excalidraw/[email protected]`Homepage: https://github.com/excalidraw/excalidraw/tree/master/packages/excalidraw_(No LICENSE file in package; SPDX identifier in `package.json` is the sole declared grant.)_@@ -1365,6 +1375,11 @@ Homepage: https://github.com/danestves/markdown-to-text.gitCopyright (c) 2020 Daniel Esteves+### `@excalidraw/[email protected]`+Homepage: https://github.com/excalidraw/excalidraw++_(No LICENSE file in package; SPDX identifier in `package.json` is the sole declared grant.)_+### `@excalidraw/[email protected]`Copyright (c) 2023 Excalidraw@@ -4729,11 +4744,6 @@ Homepage: https://github.com/sindresorhus/openCopyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)-### `[email protected]`-Homepage: https://github.com/yeun/open-color--Copyright (c) 2016 heeyeun-### `[email protected]`Homepage: https://github.com/sindresorhus/ora@@ -6634,7 +6644,7 @@ Copyright (c) 2015, Yeoman teamThe following packages are under licenses that do not require attribution (BlueOak-1.0.0, 0BSD, WTFPL, Unlicense, CC0-1.0). Listed for completeness and traceability.-- `[email protected]` — CC0-1.0+- `@excalidraw/[email protected]` — CC0-1.0- `[email protected]` — BlueOak-1.0.0- `[email protected]` — BlueOak-1.0.0- `[email protected]` — Unlicensediff --git a/packages/app/BUNDLE-SIZE.md b/packages/app/BUNDLE-SIZE.mdindex 6e31c2d22..31a69add2 100644--- a/packages/app/BUNDLE-SIZE.md+++ b/packages/app/BUNDLE-SIZE.md@@ -84,3 +84,7 @@ Combined-chunks 6.6->8.4 MB for `@pierre/[email protected]`, the merge-conflict and diThe eager budgets did not move, and that is the load-bearing fact. Main app bundle stays at 487 kB and CSS at 59 kB. The first revision of this work did put Pierre in the eager chunk — every surface was statically imported from always-mounted chrome, measuring 459.28 kB — which was then code-split behind the boundaries that already gate those surfaces (`DiffViewBoundary` on `lifecycle.status`, the two Skill dialogs on user action). Measured after: **437.42 kB against main's own 438.38 kB**, so the swap costs the eager bundle nothing.Transitive additions worth attributing: `@pierre/[email protected]`, `@pierre/[email protected]`, `@shikijs/transformers`, `diff@9`, `lru_map` arrive while `@shikijs/themes` leaves `dependencies`, so the gross Pierre cost exceeds the 1.85 MB delta. **Reclamation lever:** alias the bare `shiki` specifier to a shim exporting `bundledLanguages = {}` and register only the grammars a diff needs through Pierre's `RegisteredCustomLanguages`. The app's own highlighter imports `shiki/core` plus individual `@shikijs/langs/*` entries and never the full-bundle entry, so such a shim would not touch it. Deliberately not done here: it caps which languages highlight inside a diff, and the bytes it reclaims are ones no session downloads.++Combined-chunks 8.4->8.8 MB for the `@excalidraw/excalidraw` bump to `0.18.0-abeeaeb`, the release-branch snapshot that carries the stroke Pressure setting. Measured against the merged tree: 8,588,202 B locally, ~8.71 MB projected in CI at the ~1.4% local->CI ratio, roughly 190 kB over the 8.4 ceiling. An intermediate 8.65 was set first and would have landed red — it clears the local number but not the projection, which is the reason this file records the ratio at all. The snapshot is about 99 upstream commits ahead of `0.18.1`, and the delta is not attributed here. It is not new third-party weight: `@excalidraw/[email protected]`, which the constant-width renderer draws through, was already a declared dependency of `0.18.1`, so the Pressure work adds first-party renderer code rather than a library. Ninety-nine commits is a wide enough window that pinning the bytes on any one of them would need a per-commit build, which was not run.++The eager budgets did not move. The main app bundle measures 437.95 kB against its 487 kB limit and CSS 8.36 kB against 59 kB, because both surfaces that load a board — the standalone `.excalidraw` editor and the in-document snapshot embed — still reach the package through a dynamic import. Nobody downloads any of this unless they open a board. **Reclamation lever:** none worth taking here; the weight is upstream's own renderer and the chunk is already gated behind the two board surfaces. Headroom at the new ceiling is ~90 kB against the CI projection, in line with the margins above.diff --git a/packages/app/package.json b/packages/app/package.jsonindex e900b5751..d4c1883f7 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -55,7 +55,7 @@{"name": "all JS chunks combined (gzipped)","path": "dist/assets/*.js",- "limit": "8.4 MB",+ "limit": "8.8 MB","gzip": true,"running": false},@@ -87,7 +87,7 @@"@dnd-kit/core": "^6.3.1","@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2",- "@excalidraw/excalidraw": "0.18.1",+ "@excalidraw/excalidraw": "0.18.0-abeeaeb","@fellow/prosemirror-recreate-transform": "^1.2.3","@floating-ui/dom": "^1.7.6","@fontsource-variable/inter": "^5.2.8",diff --git a/packages/app/src/components/ExcalidrawDocEditor.tsx b/packages/app/src/components/ExcalidrawDocEditor.tsxindex 56e91e457..2e64fc5d6 100644--- a/packages/app/src/components/ExcalidrawDocEditor.tsx+++ b/packages/app/src/components/ExcalidrawDocEditor.tsx@@ -1,4 +1,5 @@-import { CaptureUpdateAction, Excalidraw, restore, serializeAsJSON } from '@excalidraw/excalidraw';+import * as excalidraw from '@excalidraw/excalidraw';+import { CaptureUpdateAction, Excalidraw } from '@excalidraw/excalidraw';import '@excalidraw/excalidraw/index.css';import type { HocuspocusProvider } from '@hocuspocus/provider';import { useLingui } from '@lingui/react/macro';@@ -6,24 +7,22 @@ import { type ComponentProps, useEffect, useRef, useState } from 'react';import { replaceYText } from './MermaidDocEditor';import '@/lib/excalidraw-env';+import { type ExcalidrawScene, restoreScene, serializeScene } from '@/lib/excalidraw-scene.ts';type ExcalidrawProps = ComponentProps<typeof Excalidraw>;-type ExcalidrawImperativeAPI = Parameters<NonNullable<ExcalidrawProps['excalidrawAPI']>>[0];-type RestoreResult = {- elements: ReturnType<typeof restore>['elements'];- appState: ReturnType<typeof restore>['appState'];- files: ReturnType<typeof restore>['files'];-};+type ExcalidrawImperativeAPI = NonNullable<+ Parameters<NonNullable<ExcalidrawProps['onExcalidrawAPI']>>[0]+>;-type ParseOutcome = { ok: true; scene: RestoreResult } | { ok: false; scene: RestoreResult };+type ParseOutcome = { ok: true; scene: ExcalidrawScene } | { ok: false; scene: ExcalidrawScene };function parseSnapshot(str: string): ParseOutcome {- if (str.trim() === '') return { ok: true, scene: restore(null, null, null) };+ if (str.trim() === '') return { ok: true, scene: restoreScene(excalidraw, null) };try {const parsed: unknown = JSON.parse(str);- return { ok: true, scene: restore(parsed as Parameters<typeof restore>[0], null, null) };+ return { ok: true, scene: restoreScene(excalidraw, parsed) };} catch {- return { ok: false, scene: restore(null, null, null) };+ return { ok: false, scene: restoreScene(excalidraw, null) };}}@@ -74,7 +73,7 @@ export function ExcalidrawDocEditor({ provider }: { provider: HocuspocusProviderif (elements.length === 0) return;blockBlankOverwriteRef.current = false;}- const str = serializeAsJSON(elements, appState, files, 'local');+ const str = serializeScene(excalidraw, elements, appState, files);if (str === lastSavedRef.current) return;lastSavedRef.current = str;replaceYText(ytext, str);@@ -88,7 +87,7 @@ export function ExcalidrawDocEditor({ provider }: { provider: HocuspocusProvider><div className="absolute inset-0 z-0"><Excalidraw- excalidrawAPI={setExcalidrawAPI}+ onExcalidrawAPI={setExcalidrawAPI}initialData={initialOutcome.scene}onChange={handleChange}/>diff --git a/packages/app/src/editor/components/ExcalidrawEmbed.dom.test.tsx b/packages/app/src/editor/components/ExcalidrawEmbed.dom.test.tsxindex b8b622276..6d97843a9 100644--- a/packages/app/src/editor/components/ExcalidrawEmbed.dom.test.tsx+++ b/packages/app/src/editor/components/ExcalidrawEmbed.dom.test.tsx@@ -6,13 +6,10 @@ import { renderLinguiTemplate } from '@/test-utils/lingui-mock';const exportToSvg = vi.fn(async (_opts: Record<string, unknown>) =>document.createElementNS('http://www.w3.org/2000/svg', 'svg'),);-const restore = vi.fn((data: unknown) => ({- elements: (data as { elements?: unknown[] })?.elements ?? [],- appState: {},- files: {},-}));+const restoreElements = vi.fn((elements: unknown) => (elements as unknown[] | undefined) ?? []);+const restoreAppState = vi.fn(() => ({}));-vi.doMock('@excalidraw/excalidraw', () => ({ exportToSvg, restore }));+vi.doMock('@excalidraw/excalidraw', () => ({ exportToSvg, restoreElements, restoreAppState }));vi.doMock('@lingui/react/macro', () => ({...actualLinguiMacro,@@ -66,7 +63,8 @@ function snapshotImg(): HTMLImageElement | null {describe('ExcalidrawEmbed', () => {beforeEach(() => {exportToSvg.mockClear();- restore.mockClear();+ restoreElements.mockClear();+ restoreAppState.mockClear();useLiveDocText.mockClear();createObjectURL.mockClear();revokeObjectURL.mockClear();@@ -86,11 +84,7 @@ describe('ExcalidrawEmbed', () => {await waitFor(() => expect(snapshotImg()).not.toBeNull());expect(useLiveDocText).toHaveBeenCalledWith('tests/board.excalidraw', 0);- expect(restore).toHaveBeenCalledWith(- expect.objectContaining({ elements: [{ id: 'a' }] }),- null,- null,- );+ expect(restoreElements).toHaveBeenCalledWith([{ id: 'a' }], null);expect(exportToSvg.mock.calls.at(-1)?.[0]?.appState).toMatchObject({exportBackground: false,exportWithDarkMode: false,@@ -104,7 +98,7 @@ describe('ExcalidrawEmbed', () => {renderEmbed({ src: '/tests/board.excalidraw' });await waitFor(() => expect(snapshotImg()).not.toBeNull());const exportsBefore = exportToSvg.mock.calls.length;- const parsesBefore = restore.mock.calls.length;+ const parsesBefore = restoreElements.mock.calls.length;const firstUrl = snapshotImg()?.src;act(() => {@@ -115,7 +109,7 @@ describe('ExcalidrawEmbed', () => {expect(exportToSvg.mock.calls.at(-1)?.[0]?.appState).toMatchObject({exportWithDarkMode: true,});- expect(restore.mock.calls.length).toBe(parsesBefore);+ expect(restoreElements.mock.calls.length).toBe(parsesBefore);expect(snapshotImg()).not.toBeNull();await waitFor(() => expect(revokeObjectURL).toHaveBeenCalledWith(firstUrl));});@@ -133,8 +127,8 @@ describe('ExcalidrawEmbed', () => {);await waitFor(() => expect(exportToSvg.mock.calls.length).toBeGreaterThan(exportsBefore));- const scene = restore.mock.calls.at(-1)?.[0] as { elements?: unknown[] };- expect(scene.elements?.length).toBe(2);+ const elements = restoreElements.mock.calls.at(-1)?.[0] as unknown[] | undefined;+ expect(elements?.length).toBe(2);});test('an unreachable board surfaces the banner with fixed copy and a working retry', async () => {@@ -180,7 +174,7 @@ describe('ExcalidrawEmbed', () => {);const { rerender } = render(view(false));await waitFor(() => expect(snapshotImg()).not.toBeNull());- const parses = restore.mock.calls.length;+ const parses = restoreElements.mock.calls.length;const exports = exportToSvg.mock.calls.length;const urls = createObjectURL.mock.calls.length;@@ -190,7 +184,7 @@ describe('ExcalidrawEmbed', () => {rerender(view(false));await act(async () => {});- expect(restore.mock.calls.length).toBe(parses);+ expect(restoreElements.mock.calls.length).toBe(parses);expect(exportToSvg.mock.calls.length).toBe(exports);expect(createObjectURL.mock.calls.length).toBe(urls);expect(snapshotImg()).not.toBeNull();@@ -267,7 +261,7 @@ describe('ExcalidrawEmbed', () => {const { rerender } = renderEmbed({ src: '/tests/board.excalidraw' });await waitFor(() => expect(resolvers.length).toBe(1));- let parses = restore.mock.calls.length;+ let parses = restoreElements.mock.calls.length;for (const text of [JSON.stringify({ elements: [{ id: 'a' }, { id: 'b' }] }),JSON.stringify({ elements: [{ id: 'a' }, { id: 'b' }, { id: 'c' }] }),@@ -278,7 +272,7 @@ describe('ExcalidrawEmbed', () => {<ExcalidrawEmbed src="/tests/board.excalidraw" /></TooltipProvider>,);- await waitFor(() => expect(restore.mock.calls.length).toBe(parses + 1));+ await waitFor(() => expect(restoreElements.mock.calls.length).toBe(parses + 1));parses += 1;}expect(resolvers.length).toBe(1);diff --git a/packages/app/src/editor/components/ExcalidrawEmbed.tsx b/packages/app/src/editor/components/ExcalidrawEmbed.tsxindex acd7fd17e..0d6450e87 100644--- a/packages/app/src/editor/components/ExcalidrawEmbed.tsx+++ b/packages/app/src/editor/components/ExcalidrawEmbed.tsx@@ -7,6 +7,7 @@ import { Button } from '@/components/ui/button';import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog';import { hashFromDocName } from '@/lib/doc-hash';import '@/lib/excalidraw-env';+import { type ExcalidrawScene, restoreScene } from '@/lib/excalidraw-scene.ts';import { createRetryingLoader } from '@/lib/retrying-loader.ts';import { cn } from '@/lib/utils.ts';import { useLiveDocText } from './live-doc-pool.ts';@@ -15,7 +16,6 @@ import { releaseSnapshotUrl, retainSnapshotUrl } from './snapshot-url-pool.ts';import { useAppColorMode } from './use-app-color-mode.ts';type ExcalidrawModule = typeof import('@excalidraw/excalidraw');-type ExcalidrawScene = ReturnType<ExcalidrawModule['restore']>;const loadExcalidraw = createRetryingLoader(() => import('@excalidraw/excalidraw'));@@ -124,7 +124,7 @@ export function ExcalidrawEmbed({setError({ docName: boardDocName, kind: 'module-load' });return;}- const value = mod.restore(parsed as Parameters<ExcalidrawModule['restore']>[0], null, null);+ const value = restoreScene(mod, parsed);if (cancelled) return;setScene({ docName: boardDocName, text: live.text, value });setError(null);diff --git a/packages/app/src/editor/extensions/JsxComponentView.mermaid-expand.dom.test.tsx b/packages/app/src/editor/extensions/JsxComponentView.mermaid-expand.dom.test.tsxindex b9928a40b..1d3a06500 100644--- a/packages/app/src/editor/extensions/JsxComponentView.mermaid-expand.dom.test.tsx+++ b/packages/app/src/editor/extensions/JsxComponentView.mermaid-expand.dom.test.tsx@@ -8,11 +8,8 @@ vi.doMock('../components/live-doc-pool.ts', () => ({}));vi.doMock('@excalidraw/excalidraw', () => ({exportToSvg: async () => document.createElementNS('http://www.w3.org/2000/svg', 'svg'),- restore: (data: unknown) => ({- elements: (data as { elements?: unknown[] })?.elements ?? [],- appState: {},- files: {},- }),+ restoreElements: (elements: unknown) => (elements as unknown[] | undefined) ?? [],+ restoreAppState: () => ({}),}));let blobUrlCounter = 0;diff --git a/packages/app/src/lib/excalidraw-scene.roundtrip.dom.test.ts b/packages/app/src/lib/excalidraw-scene.roundtrip.dom.test.tsnew file mode 100644index 000000000..5b8f07e3c--- /dev/null+++ b/packages/app/src/lib/excalidraw-scene.roundtrip.dom.test.ts@@ -0,0 +1,174 @@+import * as excalidraw from '@excalidraw/excalidraw';+import { describe, expect, test } from 'vitest';+import { restoreScene, serializeScene } from './excalidraw-scene.ts';++type Element = ExcalidrawSceneElement;+type ExcalidrawSceneElement = ReturnType<typeof excalidraw.restoreElements>[number];++function board(elements: unknown[]) {+ return { type: 'excalidraw', version: 2, source: 'test', elements, appState: {}, files: {} };+}++function freedraw(id: string, extra: Record<string, unknown> = {}) {+ return {+ id,+ type: 'freedraw',+ x: 0,+ y: 0,+ width: 10,+ height: 10,+ points: [+ [0, 0],+ [10, 10],+ ],+ pressures: [],+ simulatePressure: true,+ ...extra,+ };+}++function arrowElement(extra: Record<string, unknown> = {}) {+ return {+ id: 'arrow',+ type: 'arrow',+ x: 0,+ y: 0,+ width: 10,+ height: 10,+ points: [+ [0, 0],+ [10, 10],+ ],+ ...extra,+ };+}++function serialize(elements: readonly Element[], appState: Parameters<typeof serializeScene>[2]) {+ return serializeScene(excalidraw, elements, appState, {});+}++describe('a board round-trips through the real package', () => {+ test('writes a document the format recognises', () => {+ const scene = restoreScene(excalidraw, board([freedraw('a')]));++ const doc = JSON.parse(serialize(scene.elements, scene.appState));++ expect(doc.type).toBe('excalidraw');+ expect(doc.elements.map((element: { id: string }) => element.id)).toEqual(['a']);+ });++ test('erased strokes do not reach the file', () => {+ const scene = restoreScene(+ excalidraw,+ board([freedraw('live'), freedraw('erased', { isDeleted: true })]),+ );++ const doc = JSON.parse(serialize(scene.elements, scene.appState));++ expect(doc.elements.map((element: { id: string }) => element.id)).toEqual(['live']);+ });++ test('is a fixpoint: restoring our own output and re-serializing is byte-stable', () => {+ const first = serialize(+ restoreScene(excalidraw, board([freedraw('a')])).elements,+ restoreScene(excalidraw, board([freedraw('a')])).appState,+ );++ const reloaded = restoreScene(excalidraw, JSON.parse(first));+ const second = serialize(reloaded.elements, reloaded.appState);++ expect(second).toBe(first);+ });++ test('a board holding an arrow is a fixpoint too', () => {+ const arrow = arrowElement();+ const first = serialize(+ restoreScene(excalidraw, board([arrow])).elements,+ restoreScene(excalidraw, board([arrow])).appState,+ );++ const reloaded = restoreScene(excalidraw, JSON.parse(first));++ expect(serialize(reloaded.elements, reloaded.appState)).toBe(first);+ });++ test('a blank board restores to an empty element list', () => {+ const scene = restoreScene(excalidraw, null);++ const doc = JSON.parse(serialize(scene.elements, scene.appState));++ expect(doc.elements).toEqual([]);+ });++ test('this build never invents lastCommittedPoint on a linear element', () => {+ const scene = restoreScene(excalidraw, board([arrowElement()]));++ const doc = JSON.parse(serialize(scene.elements, scene.appState));++ expect(doc.elements).toHaveLength(1);+ expect(Object.hasOwn(doc.elements[0], 'lastCommittedPoint')).toBe(false);+ });++ test('a legacy lastCommittedPoint is still null after a round trip', () => {+ const legacy = board([arrowElement({ lastCommittedPoint: null })]);++ const first = serialize(+ restoreScene(excalidraw, legacy).elements,+ restoreScene(excalidraw, legacy).appState,+ );+ const reloaded = restoreScene(excalidraw, JSON.parse(first));++ expect(serialize(reloaded.elements, reloaded.appState)).toBe(first);+ expect(JSON.parse(first).elements[0].lastCommittedPoint).toBeNull();+ });++ test('freedraw keeps the legacy pressure encoding beside the new stroke options', () => {+ const scene = restoreScene(+ excalidraw,+ board([+ freedraw('a', {+ simulatePressure: false,+ pressures: [0.5, 0.7],+ strokeOptions: { variability: 'constant', streamline: 0.3 },+ }),+ ]),+ );++ const doc = JSON.parse(serialize(scene.elements, scene.appState));++ expect(doc.elements[0]).toMatchObject({+ simulatePressure: false,+ pressures: [0.5, 0.7],+ strokeOptions: { variability: 'constant', streamline: 0.3 },+ });+ });++ test("a freedraw with no strokeOptions restores the defaults, 'variable' and 0.5", () => {+ const scene = restoreScene(excalidraw, board([freedraw('a')]));++ const doc = JSON.parse(serialize(scene.elements, scene.appState));++ expect(doc.elements[0].strokeOptions.variability).toBe('variable');+ expect(doc.elements[0].strokeOptions.streamline).toBe(0.5);+ });++ test('files pass through to the written document', () => {+ const files = {+ 'file-1': { id: 'file-1', mimeType: 'image/png', dataURL: 'data:image/png;base64,AAAA' },+ };+ const image = {+ id: 'img',+ type: 'image',+ x: 0,+ y: 0,+ width: 10,+ height: 10,+ fileId: 'file-1',+ };+ const scene = restoreScene(excalidraw, { ...board([image]), files });++ const doc = JSON.parse(serializeScene(excalidraw, scene.elements, scene.appState, scene.files));++ expect(doc.files).toEqual(files);+ });+});diff --git a/packages/app/src/lib/excalidraw-scene.test.ts b/packages/app/src/lib/excalidraw-scene.test.tsnew file mode 100644index 000000000..c37513810--- /dev/null+++ b/packages/app/src/lib/excalidraw-scene.test.ts@@ -0,0 +1,96 @@+import { describe, expect, test, vi } from 'vitest';+import { restoreScene, serializeScene } from './excalidraw-scene.ts';++type StubModule = Parameters<typeof restoreScene>[0];++function stubModule() {+ const restoreElements = vi.fn((elements: unknown) => (elements as unknown[] | undefined) ?? []);+ const restoreAppState = vi.fn(() => ({ viewBackgroundColor: '#fff' }));+ const serializeAsJSON = vi.fn(+ (elements: unknown, appState: unknown, files: unknown, type: unknown) =>+ JSON.stringify({ elements, appState, files, type }),+ );+ const getNonDeletedElements = vi.fn((elements: readonly { isDeleted?: boolean }[]) =>+ elements.filter((element) => !element.isDeleted),+ );+ const mod = {+ restoreElements,+ restoreAppState,+ serializeAsJSON,+ getNonDeletedElements,+ } as unknown as StubModule;+ return { mod, restoreElements, restoreAppState, serializeAsJSON, getNonDeletedElements };+}++describe('restoreScene', () => {+ test('routes each part of the scene through its own upstream restorer', () => {+ const { mod, restoreElements, restoreAppState } = stubModule();+ const files = { 'file-1': { id: 'file-1' } };++ const scene = restoreScene(mod, {+ elements: [{ id: 'a' }],+ appState: { viewBackgroundColor: '#eee' },+ files,+ });++ expect(restoreElements).toHaveBeenCalledWith([{ id: 'a' }], null);+ expect(restoreAppState).toHaveBeenCalledWith({ viewBackgroundColor: '#eee' }, null);+ expect(scene.elements).toEqual([{ id: 'a' }]);+ expect(scene.appState).toEqual({ viewBackgroundColor: '#fff' });+ expect(scene.files).toBe(files);+ });++ test('yields a blank scene for null, and defaults files to an empty map', () => {+ const { mod, restoreElements, restoreAppState } = stubModule();++ const scene = restoreScene(mod, null);++ expect(restoreElements).toHaveBeenCalledWith(undefined, null);+ expect(restoreAppState).toHaveBeenCalledWith(undefined, null);+ expect(scene.files).toEqual({});+ });++ test('repairs a partial board rather than throwing', () => {+ const { mod } = stubModule();++ expect(restoreScene(mod, { elements: [{ id: 'a' }] }).files).toEqual({});+ expect(restoreScene(mod, 'not a board').elements).toEqual([]);+ });+});++describe('serializeScene', () => {+ test('drops soft-deleted elements before they reach the file', () => {+ const { mod, serializeAsJSON } = stubModule();+ const live = { id: 'live' };++ const written = serializeScene(+ mod,+ [live, { id: 'erased', isDeleted: true }] as never,+ {} as never,+ {} as never,+ );++ expect(serializeAsJSON.mock.calls[0]?.[0]).toEqual([live]);+ expect(JSON.parse(written).elements).toEqual([live]);+ });++ test("keeps every element the user can still see, and writes the file-tagged 'local' shape", () => {+ const { mod, serializeAsJSON } = stubModule();+ const elements = [{ id: 'a' }, { id: 'b', isDeleted: false }];++ const written = serializeScene(+ mod,+ elements as never,+ { name: 'board' } as never,+ {+ 'file-1': {},+ } as never,+ );++ expect(JSON.parse(written).elements).toEqual(elements);+ expect(serializeAsJSON.mock.calls[0]?.[0]).toEqual(elements);+ expect(serializeAsJSON.mock.calls[0]?.[1]).toEqual({ name: 'board' });+ expect(serializeAsJSON.mock.calls[0]?.[2]).toEqual({ 'file-1': {} });+ expect(serializeAsJSON.mock.calls[0]?.[3]).toBe('local');+ });+});diff --git a/packages/app/src/lib/excalidraw-scene.ts b/packages/app/src/lib/excalidraw-scene.tsnew file mode 100644index 000000000..c7750f419--- /dev/null+++ b/packages/app/src/lib/excalidraw-scene.ts@@ -0,0 +1,29 @@+type ExcalidrawModule = typeof import('@excalidraw/excalidraw');++export type ExcalidrawScene = {+ elements: ReturnType<ExcalidrawModule['restoreElements']>;+ appState: ReturnType<ExcalidrawModule['restoreAppState']>;+ files: NonNullable<Parameters<ExcalidrawModule['serializeAsJSON']>[2]>;+};++export function restoreScene(mod: ExcalidrawModule, data: unknown): ExcalidrawScene {+ const imported = (data ?? null) as {+ elements?: Parameters<ExcalidrawModule['restoreElements']>[0];+ appState?: Parameters<ExcalidrawModule['restoreAppState']>[0];+ files?: ExcalidrawScene['files'];+ } | null;+ return {+ elements: mod.restoreElements(imported?.elements, null),+ appState: mod.restoreAppState(imported?.appState, null),+ files: imported?.files ?? {},+ };+}++export function serializeScene(+ mod: ExcalidrawModule,+ elements: Parameters<ExcalidrawModule['serializeAsJSON']>[0],+ appState: Parameters<ExcalidrawModule['serializeAsJSON']>[1],+ files: Parameters<ExcalidrawModule['serializeAsJSON']>[2],+): string {+ return mod.serializeAsJSON(mod.getNonDeletedElements(elements), appState, files, 'local');+}diff --git a/packages/app/vitest.dom.config.ts b/packages/app/vitest.dom.config.tsindex 0de36db6f..b6960a73f 100644--- a/packages/app/vitest.dom.config.ts+++ b/packages/app/vitest.dom.config.ts@@ -23,6 +23,19 @@ const jsdomSetupPath = fileURLToPath(new URL('./tests/dom/jsdom-preload.ts', impexport const appDomVitestConfig = {...appVitestConfig,+ resolve: {+ ...appVitestConfig.resolve,+ alias: [+ ...appVitestConfig.resolve.alias,+ // Excalidraw's dev bundle imports `roughjs/bin/rough` without the+ // extension, which Vite's Node resolver rejects. The browser build+ // resolves it through bundling, so this only bites the one tier that+ // imports the real package rather than stubbing it+ // (`excalidraw-scene.roundtrip.dom.test.ts`). Drop this alias if a+ // future Excalidraw ships the extension.+ { find: /^roughjs\/bin\/rough$/, replacement: 'roughjs/bin/rough.js' },+ ],+ },test: {...appVitestConfig.test,environment: 'jsdom',@@ -43,6 +56,11 @@ export const appDomVitestConfig = {testTimeout: 30_000,hookTimeout: 30_000,isolate: true,+ // Route the real Excalidraw through Vite's transform rather than Node's+ // resolver, so the `roughjs/bin/rough` alias above is honoured. Only the+ // round-trip suite imports the package for real; every other Excalidraw+ // test stubs it via `vi.doMock`, which intercepts ahead of resolution.+ server: { deps: { inline: [/@excalidraw[/\\]excalidraw/] } },},} satisfies ViteUserConfig;diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 3b2f3d3ef..373410ca7 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -403,8 +403,8 @@ importers:specifier: ^3.2.2version: 3.2.2([email protected])'@excalidraw/excalidraw':- specifier: 0.18.1- version: 0.18.1(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ specifier: 0.18.0-abeeaeb+ version: 0.18.0-abeeaeb(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])'@fellow/prosemirror-recreate-transform':specifier: ^1.2.3version: 1.2.3@@ -2262,18 +2262,31 @@ packages:cpu: [x64]os: [win32]- '@excalidraw/[email protected]':- resolution: {integrity: sha512-6i5Gt7IDTOH//qa0Z315Ly5iVRhjWpu2whrlQFqkuwrkKUWgRsMk0P5qdE7bpyDpai7jeLeWYkyj1eVAfni1lw==}+ '@excalidraw/[email protected]':+ resolution: {integrity: sha512-st3TJlmlR46yxoQ9IEOalL7MAUaGaA0RfwwHMjG33lx+sc6ZD2xUSs7oz2RFcY3JkHRWf2qsjXfjiUusaeavfA==}++ '@excalidraw/[email protected]':+ resolution: {integrity: sha512-wwfWBB3XDAeY45DXtyGFCijlYAOuxwwfHZ9GqhFAMc3KORWjZKNqYTOwr5zFj6RPyhbTebMYFJ6Rvzx81FM7BQ==}++ '@excalidraw/[email protected]':+ resolution: {integrity: sha512-0Lv/Fg27S+SyP+HEJTY1dWafMsW2IWiyR7Igxv1QVyu0rPKsqsnvyLENCn0yACbTGdK4ZTvE9cV+WFuBNYYkDQ==}peerDependencies:react: 19.2.5react-dom: 19.2.5+ '@excalidraw/[email protected]':+ resolution: {integrity: sha512-BaNc4cPJKQ5bywsCeFqmegoXgvYQpGrpx02UGCyw94CDVTdkPGkbxyHCdXlnnwdCwq0J00pt7PPRuSSc6t+c3A==}+ engines: {node: ^14.13.1 || >=16.0.0}+'@excalidraw/[email protected]':resolution: {integrity: sha512-psA1z1N2qeAfsORdXc9JmD2y4CmDwmuMRxnNdJHZexIcPwaNEyIpNcelw+QkL9rz9tosaN9krXuKaRqYpRAR6g==}'@excalidraw/[email protected]':resolution: {integrity: sha512-1nDXBNAojfi3oSFwJswKREkFm5wrSjqay81QlyRv2pkITG/XYB5v+oChENVBQLcxQwX4IUATWvXM5BcaNhPiIg==}+ '@excalidraw/[email protected]':+ resolution: {integrity: sha512-Xc0vR/7KmHoEhZItjwEbMKSbEgcnZaNQWyQ87OFQ/L37Yr0OcWCdij4E80asrlhUvcs+6SqmhxidP+Euqx2+0A==}+'@excalidraw/[email protected]':resolution: {integrity: sha512-5VKQq5CdRocC82vOIUpQ5ufJOVV9FpBTdHGA+ULqazeIVV+cr299877omQCibsdS3Bpitz2fsnTwnIXEmLVDSg==}@@ -6534,8 +6547,8 @@ packages:resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}engines: {node: '>=8'}- resolution: {integrity: sha512-LSvVX5e21LRrXqVMhqtAwj5xPgDb+fXAIH80NsnCQ9xuZPs2xWsOREi24RKgZa1XOiQRbcmVrv87+ulOKsgjxw==}+ resolution: {integrity: sha512-JveqW2w6pEZqFEEfMgCszXzYpE89dG+nPsmOdcs741mFFAROeL+iqjGEpR07RI+s0YY0EFr+4KnOoACprJTpOw==}resolution: {integrity: sha512-FQBYNK15VMslhLHpA7+n+n1GOlF1kId2xcCg7/j95f24AOF6VDYMNH4mFxF7KuaTdv627faazpOAjFzMrfJOUw==}@@ -7799,10 +7812,6 @@ packages:resolution: {integrity: sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==}engines: {node: '>= 0.6'}- resolution: {integrity: sha512-PcOxmqwYCW7O2ovKRU8OoQQj2yqTfEB/yeTYk4gPid6dN5ODRfU1hXd9tTVZzax/0NkO7AxpHykvZnT1aYp/BQ==}- engines: {node: ^14.13.1 || >=16.0.0}-resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==}engines: {node: '>= 0.8'}@@ -9481,9 +9490,6 @@ packages:resolution: {integrity: sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==}- resolution: {integrity: sha512-vCseG/EQ6/RcvxhUcGJiHViOgrtz4x0XbZepXvKik66TMGkvbmjeJrKFyBEx6daG5rNyyd14zYXhz0hZVwQFOw==}-resolution: {integrity: sha512-smsWv2LzFjP03xmvFoJ331ss6h+jixfA4UUV/Bsiyuu4YJPfN+FIQGOIiv4w9/+MoHkfkJ22UIaQWRVFRfH6Vw==}engines: {node: '>=20'}@@ -12652,20 +12658,35 @@ snapshots:'@esbuild/[email protected]':optional: true- '@excalidraw/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':+ '@excalidraw/[email protected]':+ dependencies:+ tinycolor2: 1.6.0++ '@excalidraw/[email protected]':+ dependencies:+ '@excalidraw/common': 0.18.0-abeeaeb+ '@excalidraw/fractional-indexing': 0.18.0-abeeaeb+ '@excalidraw/math': 0.18.0-abeeaeb++ '@excalidraw/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':dependencies:'@braintree/sanitize-url': 6.0.2+ '@codemirror/commands': 6.10.4+ '@codemirror/language': 6.12.4+ '@codemirror/state': 6.7.1+ '@codemirror/view': 6.43.3+ '@excalidraw/common': 0.18.0-abeeaeb+ '@excalidraw/element': 0.18.0-abeeaeb'@excalidraw/laser-pointer': 1.3.1+ '@excalidraw/math': 0.18.0-abeeaeb'@excalidraw/mermaid-to-excalidraw': 2.2.2'@excalidraw/random-username': 1.1.0- '@radix-ui/react-popover': 1.1.17(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-tabs': 1.1.13(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- browser-fs-access: 0.29.1+ '@lezer/highlight': 1.2.3+ browser-fs-access: 0.38.0canvas-roundrect-polyfill: 0.0.1clsx: 1.1.1cross-env: 7.0.3es6-promise-pool: 2.5.0- fractional-indexing: 3.2.0fuzzy: 0.1.3image-blob-reduce: 3.0.1jotai: 2.11.0(@types/[email protected])([email protected])@@ -12673,7 +12694,6 @@ snapshots:lodash.debounce: 4.0.8lodash.throttle: 4.1.1nanoid: 3.3.18- open-color: 1.9.1pako: 2.0.3perfect-freehand: 1.2.0pica: 7.1.1@@ -12682,6 +12702,7 @@ snapshots:png-chunks-extract: 1.0.0points-on-curve: 1.0.1pwacompat: 2.0.17+ radix-ui: 1.4.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])react: 19.2.5react-dom: 19.2.5([email protected])roughjs: 4.6.4@@ -12692,10 +12713,16 @@ snapshots:- '@types/react-dom'- immer+ '@excalidraw/[email protected]': {}+'@excalidraw/[email protected]': {}'@excalidraw/[email protected]': {}+ '@excalidraw/[email protected]':+ dependencies:+ '@excalidraw/common': 0.18.0-abeeaeb+'@excalidraw/[email protected]':dependencies:'@excalidraw/markdown-to-text': 0.1.2@@ -16889,7 +16916,7 @@ snapshots:dependencies:fill-range: 7.1.1- [email protected]: {}+ [email protected]: {}dependencies:@@ -18356,8 +18383,6 @@ snapshots:- [email protected]: {}-@@ -20459,8 +20484,6 @@ snapshots:regex: 6.1.0regex-recursion: 6.0.2- [email protected]: {}-dependencies:default-browser: 5.5.0diff --git a/scripts/check-excalidraw-pin.test.mjs b/scripts/check-excalidraw-pin.test.mjsnew file mode 100644index 000000000..a9b0d7a3a--- /dev/null+++ b/scripts/check-excalidraw-pin.test.mjs@@ -0,0 +1,36 @@+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { describe, expect, test } from 'vitest';++const OK_ROOT = fileURLToPath(new URL('..', import.meta.url));+const PINNED = '0.18.0-abeeaeb';++describe('the Excalidraw pin', () => {+ test('is declared as the exact prerelease snapshot, not a range and not the released version', () => {+ const manifest = JSON.parse(+ readFileSync(new URL('packages/app/package.json', `file://${OK_ROOT}`), 'utf8'),+ );++ const declared = manifest.dependencies['@excalidraw/excalidraw'];++ expect(+ declared,+ `@excalidraw/excalidraw must stay pinned to the exact snapshot ${PINNED}, not ${declared}. It is built from the head of upstream's release branch, so it sorts BELOW the released 0.18.1 under semver while carrying ~99 commits more, including the stroke Pressure control this app ships and the board-format fields it writes to disk. Moving to a semver-greater release is a DOWNGRADE that removes a shipped feature and changes user data at rest, and a caret or tilde range resolves 0.18.1 in preference to this snapshot. Retire this file only when a stable release contains excalidraw/excalidraw#11507; at that point re-check packages/app/src/lib/excalidraw-scene.ts by hand, because restore() may be exported again and serializeAsJSON('local') may filter deleted elements again, and no test in this tree can detect either.`,+ ).toBe(PINNED);+ });++ test('resolves to that same snapshot, so no override or second declaration can move it', () => {+ const lock = readFileSync(new URL('pnpm-lock.yaml', `file://${OK_ROOT}`), 'utf8');++ const resolved = [+ ...new Set(+ [...lock.matchAll(/^ {2}'@excalidraw\/excalidraw@([^'(]+)/gm)].map((match) => match[1]),+ ),+ ];++ expect(+ resolved,+ `the lockfile must resolve @excalidraw/excalidraw to exactly [${PINNED}], not [${resolved.join(', ')}]. A pnpm-workspace.yaml overrides: entry, which is the remedy .github/dependabot.yml documents for a security advisory on this package, moves the resolved version while leaving packages/app/package.json untouched, so the declared-specifier assertion above stays green through a downgrade that removes the shipped Pressure control.`,+ ).toEqual([PINNED]);+ });+});diff --git a/vitest.scripts.config.ts b/vitest.scripts.config.tsnew file mode 100644index 000000000..aabc077ba--- /dev/null+++ b/vitest.scripts.config.ts@@ -0,0 +1,16 @@+import { defineConfig } from 'vitest/config';+import { okVitestBase } from './test-support/vitest.base';++export default defineConfig({+ ...okVitestBase,+ test: {+ ...okVitestBase.test,+ include: [+ 'scripts/**/*.test.mjs',+ '.github/scripts/**/*.test.mjs',+ 'lint-plugins/**/*.test.mjs',+ 'test-support/**/*.test.ts',+ 'test-support/**/*.test.mjs',+ ],+ },+});