diff --git a/apps/web/package.json b/apps/web/package.json index 85887c5..31a134c 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -8,6 +8,7 @@ "build": "tsc -b && vite build", "check": "tsc -b --pretty false", "test": "vitest run", + "test:perf": "vitest run src/state/documentStore.perf.test.ts", "test:e2e": "playwright test" }, "dependencies": { diff --git a/apps/web/src/components/CanvasStage.tsx b/apps/web/src/components/CanvasStage.tsx index e1ccfb2..4c47e36 100644 --- a/apps/web/src/components/CanvasStage.tsx +++ b/apps/web/src/components/CanvasStage.tsx @@ -27,14 +27,14 @@ interface PinchGesture { // Canvas identity is checked (not just layer ID) so a new DOM element forces a full rebuild. interface RenderedLayerState { canvas: HTMLCanvasElement - operationIds: string[] + operations: DrawingOperation[] } /** * Returns true when the previous render is a prefix of the new operation list * AND the canvas element is the same DOM node. - * Deliberately uses stable IDs instead of object identity because structuredClone() - * recreates every operation object on each store update. + * Relies on committed operations being immutable and shared by reference: the + * store appends without cloning, so a prefix comparison is exact. */ function isAppendOnly( previous: RenderedLayerState | undefined, @@ -42,8 +42,8 @@ function isAppendOnly( operations: DrawingOperation[], ): previous is RenderedLayerState { if (!previous || previous.canvas !== canvas) return false - if (previous.operationIds.length > operations.length) return false - return previous.operationIds.every((id, index) => operations[index]?.id === id) + if (previous.operations.length > operations.length) return false + return previous.operations.every((operation, index) => operations[index] === operation) } export function CanvasStage({ searchIntegration = 'fixture', readOnly = false }: { searchIntegration?: 'fixture' | 'disabled'; readOnly?: boolean }) { @@ -144,7 +144,7 @@ export function CanvasStage({ searchIntegration = 'fixture', readOnly = false }: if (isAppendOnly(previous, canvas, layer.operations)) { // Pure append path — draw only the new suffix, in document order. - const newOperations = layer.operations.slice(previous.operationIds.length) + const newOperations = layer.operations.slice(previous.operations.length) for (const operation of newOperations) { renderDrawingOperation(context, operation, rasterAssets) } @@ -156,7 +156,7 @@ export function CanvasStage({ searchIntegration = 'fixture', readOnly = false }: // Update baseline AFTER the draw so it describes pixels actually painted. renderedLayers.current.set(layer.id, { canvas, - operationIds: layer.operations.map((operation) => operation.id), + operations: layer.operations, }) } }) diff --git a/apps/web/src/services/rasterAssets.test.ts b/apps/web/src/services/rasterAssets.test.ts new file mode 100644 index 0000000..c1ee93c --- /dev/null +++ b/apps/web/src/services/rasterAssets.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from 'vitest' +import type { RasterOperation, StrokeOperation } from '../lib/types' +import { assetsForOperations, resolveRasterImages } from './rasterAssets' + +const stroke: StrokeOperation = { + id: 'stroke-1', + kind: 'stroke', + tool: 'pressure', + points: [{ x: 0, y: 0, pressure: 0.5, time: 0 }], + size: 8, + smoothing: 0.5, + streamline: 0.5, + simulatePressure: false, + createdAt: 0, +} + +const raster: RasterOperation = { + id: 'raster-1', + kind: 'raster', + assetId: 'asset-1', + x: 0, + y: 0, + width: 10, + height: 10, + createdAt: 0, +} + +describe('raster asset lookup', () => { + it('reports no assets for a vector-only operations array', () => { + expect(assetsForOperations([stroke, stroke])).toEqual([]) + }) + + it('collects unique raster asset ids', () => { + expect(assetsForOperations([stroke, raster, { ...raster, id: 'raster-2' }])).toEqual(['asset-1']) + }) + + it('caches per operations array so untouched layers are not rescanned', () => { + const operations = [raster] + const first = assetsForOperations(operations) + const second = assetsForOperations(operations) + expect(second).toBe(first) + expect(assetsForOperations([...operations])).not.toBe(first) + }) + + it('resolves an empty map for a pure-vector document', async () => { + const resolved = await resolveRasterImages({ + id: 'document-1', + title: 'Vector', + revision: 0, + updatedAt: 0, + layers: [{ id: 'layer-1', name: 'Layer 1', visible: true, opacity: 1, operations: [stroke] }], + trace: { assetId: null, imageUrl: null, visible: true, opacity: 0.3, scale: 1 }, + }) + expect(resolved.size).toBe(0) + }) +}) diff --git a/apps/web/src/services/rasterAssets.ts b/apps/web/src/services/rasterAssets.ts index 06e5ee9..f7b8642 100644 --- a/apps/web/src/services/rasterAssets.ts +++ b/apps/web/src/services/rasterAssets.ts @@ -1,10 +1,25 @@ -import type { DrawingDocument } from '../lib/types' +import type { DrawingDocument, DrawingOperation } from '../lib/types' import { loadRasterAsset } from './persistence' const imageCache = new Map>() +const layerAssetCache = new WeakMap() + +export function assetsForOperations(operations: DrawingOperation[]) { + const cached = layerAssetCache.get(operations) + if (cached) return cached + const ids = [...new Set(operations.flatMap((operation) => + operation.kind === 'raster' ? [operation.assetId] : [], + ))] + layerAssetCache.set(operations, ids) + return ids +} function referencedAssetIds(document: DrawingDocument) { - return [...new Set(document.layers.flatMap((layer) => layer.operations.flatMap((operation) => operation.kind === 'raster' ? [operation.assetId] : [])))] + const ids = new Set() + for (const layer of document.layers) { + for (const id of assetsForOperations(layer.operations)) ids.add(id) + } + return [...ids] } function decodeBlob(blob: Blob) { diff --git a/apps/web/src/state/documentHistory.test.ts b/apps/web/src/state/documentHistory.test.ts new file mode 100644 index 0000000..c10a243 --- /dev/null +++ b/apps/web/src/state/documentHistory.test.ts @@ -0,0 +1,162 @@ +import { describe, expect, it } from 'vitest' +import type { DrawingDocument, DrawingLayer, DrawingOperation, StrokeOperation } from '../lib/types' +import { + DEFAULT_HISTORY_LIMITS, + applyHistoryEntry, + estimateOperationBytes, + layerClearedEntry, + layerMovedEntry, + layerPropertiesChangedEntry, + operationAppendedEntry, + titleChangedEntry, + traceChangedEntry, + trimFuture, + trimPast, + type HistoryEntry, +} from './documentHistory' + +function layer(id: string, operations: DrawingOperation[] = []): DrawingLayer { + return { id, name: id, visible: true, opacity: 1, operations } +} + +function documentWith(layers: DrawingLayer[]): DrawingDocument { + return { + id: 'document-1', + title: 'Untitled drawing', + revision: 3, + updatedAt: 1, + layers, + trace: { assetId: null, imageUrl: null, visible: true, opacity: 0.3, scale: 1 }, + } +} + +function stroke(id: string, pointCount = 2): StrokeOperation { + return { + id, + kind: 'stroke', + tool: 'pressure', + points: Array.from({ length: pointCount }, (_, index) => ({ x: index, y: index, pressure: 0.5, time: index })), + size: 8, + smoothing: 0.5, + streamline: 0.5, + simulatePressure: false, + createdAt: 0, + } +} + +describe('document history entries', () => { + it('estimates operation bytes without walking point objects', () => { + expect(estimateOperationBytes(stroke('a', 10))).toBe(96 + 10 * 48) + expect(estimateOperationBytes({ id: 'r', kind: 'raster', assetId: 'asset', x: 0, y: 0, width: 1, height: 1, createdAt: 0 })).toBe(96 + 64) + }) + + it('appends on redo and removes on undo while sharing untouched layers', () => { + const first = stroke('first') + const second = stroke('second') + const base = documentWith([layer('layer-1', [first]), layer('layer-2')]) + const entry = operationAppendedEntry('layer-1', second) + + const appended = applyHistoryEntry(base, entry, 'redo') + expect(appended.layers[0]?.operations).toEqual([first, second]) + expect(appended.layers[1]).toBe(base.layers[1]) + expect(base.layers[0]?.operations).toEqual([first]) + + expect(applyHistoryEntry(appended, entry, 'redo')).toBe(appended) + + const removed = applyHistoryEntry(appended, entry, 'undo') + expect(removed.layers[0]?.operations).toEqual([first]) + expect(removed.layers[1]).toBe(base.layers[1]) + }) + + it('restores layer settings without touching operations', () => { + const operations = [stroke('a')] + const base = documentWith([layer('layer-1', operations)]) + const entry = layerPropertiesChangedEntry( + 'layer-1', + { name: 'layer-1', visible: true, opacity: 1 }, + { name: 'Inks', visible: false, opacity: 0.4 }, + ) + + const changed = applyHistoryEntry(base, entry, 'redo') + expect(changed.layers[0]).toMatchObject({ name: 'Inks', visible: false, opacity: 0.4 }) + expect(changed.layers[0]?.operations).toBe(operations) + + const restored = applyHistoryEntry(changed, entry, 'undo') + expect(restored.layers[0]).toMatchObject({ name: 'layer-1', visible: true, opacity: 1 }) + expect(restored.layers[0]?.operations).toBe(operations) + }) + + it('moves layers by index and reverses the move', () => { + const base = documentWith([layer('a'), layer('b'), layer('c')]) + const entry = layerMovedEntry('a', 0, 2) + const moved = applyHistoryEntry(base, entry, 'redo') + expect(moved.layers.map((item) => item.id)).toEqual(['b', 'c', 'a']) + expect(applyHistoryEntry(moved, entry, 'undo').layers.map((item) => item.id)).toEqual(['a', 'b', 'c']) + expect(applyHistoryEntry(base, layerMovedEntry('a', 0, 5), 'redo')).toBe(base) + }) + + it('retains the removed operations array for a clear', () => { + const operations = [stroke('a'), stroke('b')] + const base = documentWith([layer('layer-1', operations)]) + const entry = layerClearedEntry('layer-1', operations) + expect(entry.bytes).toBeGreaterThan(operations.reduce((sum, operation) => sum + estimateOperationBytes(operation), 0)) + + const cleared = applyHistoryEntry(base, entry, 'redo') + expect(cleared.layers[0]?.operations).toEqual([]) + const restored = applyHistoryEntry(cleared, entry, 'undo') + expect(restored.layers[0]?.operations).toBe(operations) + }) + + it('applies partial trace patches and leaves untouched fields alone', () => { + const base = documentWith([layer('layer-1')]) + const entry = traceChangedEntry({ opacity: 0.3 }, { opacity: 0.6 }) + const changed = applyHistoryEntry(base, entry, 'redo') + expect(changed.trace).toMatchObject({ opacity: 0.6, assetId: null, imageUrl: null, visible: true }) + expect(changed.layers).toBe(base.layers) + expect(applyHistoryEntry(changed, entry, 'undo').trace.opacity).toBe(0.3) + }) + + it('applies title changes and ignores unknown layers', () => { + const base = documentWith([layer('layer-1')]) + const entry = titleChangedEntry('Untitled drawing', 'Sketch') + const changed = applyHistoryEntry(base, entry, 'redo') + expect(changed.title).toBe('Sketch') + expect(changed.layers).toBe(base.layers) + expect(applyHistoryEntry(changed, entry, 'undo').title).toBe('Untitled drawing') + expect(applyHistoryEntry(base, operationAppendedEntry('missing', stroke('x')), 'redo')).toBe(base) + }) +}) + +describe('history trimming', () => { + const entry = (bytes: number): HistoryEntry => ({ + kind: 'operation_appended', + layerId: 'layer-1', + operation: stroke('a'), + bytes, +}) + + it('keeps the newest entries within the count limit', () => { + const entries = [entry(1), entry(2), entry(3), entry(4)] + expect(trimPast(entries, { maxEntries: 2, maxBytes: 100 })).toEqual([entries[2], entries[3]]) + }) + + it('evicts the oldest past entries to satisfy the byte budget', () => { + const entries = [entry(50), entry(50), entry(50)] + expect(trimPast(entries, { maxEntries: 10, maxBytes: 60 })).toEqual([entries[2]]) + }) + + it('always keeps the newest past entry even when it exceeds the budget alone', () => { + const entries = [entry(50), entry(500)] + expect(trimPast(entries, { maxEntries: 10, maxBytes: 100 })).toEqual([entries[1]]) + }) + + it('drops the deepest future entries first', () => { + const entries = [entry(1), entry(2), entry(3), entry(4)] + expect(trimFuture(entries, { maxEntries: 2, maxBytes: 100 })).toEqual([entries[0], entries[1]]) + expect(trimFuture(entries, { maxEntries: 10, maxBytes: 6 })).toEqual([entries[0], entries[1], entries[2]]) + }) + + it('exposes the documented default limits', () => { + expect(DEFAULT_HISTORY_LIMITS).toEqual({ maxEntries: 500, maxBytes: 32 * 1024 * 1024 }) + }) +}) diff --git a/apps/web/src/state/documentHistory.ts b/apps/web/src/state/documentHistory.ts new file mode 100644 index 0000000..a6b4b42 --- /dev/null +++ b/apps/web/src/state/documentHistory.ts @@ -0,0 +1,197 @@ +import type { DrawingDocument, DrawingLayer, DrawingOperation, TraceState } from '../lib/types' + +type LayerSettings = Pick +type TracePatch = Partial> + +export interface HistoryLimits { + maxEntries: number + maxBytes: number +} + +export const DEFAULT_HISTORY_LIMITS: HistoryLimits = { + maxEntries: 500, + maxBytes: 32 * 1024 * 1024, +} + +export type HistoryEntry = { bytes: number } & ( + | { kind: 'operation_appended'; layerId: string; operation: DrawingOperation } + | { kind: 'layer_properties_changed'; layerId: string; before: LayerSettings; after: LayerSettings } + | { kind: 'layer_moved'; layerId: string; from: number; to: number } + | { kind: 'layer_cleared'; layerId: string; operations: DrawingOperation[] } + | { kind: 'title_changed'; before: string; after: string } + | { + kind: 'trace_changed' + // Only the fields the command actually wrote. `imageUrl` is included for + // setTrace/clearTrace and deliberately excluded from updateTrace so a + // later setResolvedTraceImage() is not clobbered by redo. + before: TracePatch + after: TracePatch + } +) + +const POINT_BYTES = 48 // conservative: 4 numbers plus per-point object overhead +const OPERATION_OVERHEAD = 96 + +export function estimateOperationBytes(operation: DrawingOperation): number { + if (operation.kind === 'stroke') { + return OPERATION_OVERHEAD + operation.points.length * POINT_BYTES + } + return OPERATION_OVERHEAD + 64 +} + +function patchLength(patch: TracePatch): number { + return (patch.imageUrl?.length ?? 0) + (patch.assetId?.length ?? 0) +} + +export function operationAppendedEntry(layerId: string, operation: DrawingOperation): HistoryEntry { + return { + kind: 'operation_appended', + layerId, + operation, + bytes: estimateOperationBytes(operation), + } +} + +export function layerPropertiesChangedEntry( + layerId: string, + before: LayerSettings, + after: LayerSettings, +): HistoryEntry { + return { + kind: 'layer_properties_changed', + layerId, + before, + after, + bytes: 128 + 2 * (before.name.length + after.name.length), + } +} + +export function layerMovedEntry(layerId: string, from: number, to: number): HistoryEntry { + return { kind: 'layer_moved', layerId, from, to, bytes: 128 } +} + +export function layerClearedEntry(layerId: string, operations: DrawingOperation[]): HistoryEntry { + let bytes = 128 + for (const operation of operations) bytes += estimateOperationBytes(operation) + return { kind: 'layer_cleared', layerId, operations, bytes } +} + +export function titleChangedEntry(before: string, after: string): HistoryEntry { + return { + kind: 'title_changed', + before, + after, + bytes: 64 + 2 * (before.length + after.length), + } +} + +export function traceChangedEntry(before: TracePatch, after: TracePatch): HistoryEntry { + return { + kind: 'trace_changed', + before, + after, + bytes: 128 + 2 * (patchLength(before) + patchLength(after)), + } +} + +function findLayer(document: DrawingDocument, layerId: string) { + return document.layers.find((layer) => layer.id === layerId) +} + +function replaceLayer( + document: DrawingDocument, + layerId: string, + update: (layer: DrawingLayer) => DrawingLayer, +): DrawingDocument { + const index = document.layers.findIndex((layer) => layer.id === layerId) + const current = index >= 0 ? document.layers[index] : undefined + if (!current) return document + const next = update(current) + if (next === current) return document + const layers = document.layers.slice() + layers[index] = next + return { ...document, layers } +} + +function moveLayerTo(document: DrawingDocument, layerId: string, target: number): DrawingDocument { + const index = document.layers.findIndex((layer) => layer.id === layerId) + if (index < 0 || target < 0 || target >= document.layers.length || index === target) return document + const layers = document.layers.slice() + const [layer] = layers.splice(index, 1) + if (!layer) return document + layers.splice(target, 0, layer) + return { ...document, layers } +} + +export function applyHistoryEntry( + document: DrawingDocument, + entry: HistoryEntry, + direction: 'undo' | 'redo', +): DrawingDocument { + switch (entry.kind) { + case 'operation_appended': { + const layer = findLayer(document, entry.layerId) + if (!layer) return document + if (direction === 'redo') { + if (layer.operations.at(-1)?.id === entry.operation.id) return document + return replaceLayer(document, entry.layerId, (current) => ({ + ...current, + operations: [...current.operations, entry.operation], + })) + } + const operations = layer.operations.at(-1)?.id === entry.operation.id + ? layer.operations.slice(0, -1) + : layer.operations.filter((operation) => operation.id !== entry.operation.id) + return replaceLayer(document, entry.layerId, (current) => ({ ...current, operations })) + } + case 'layer_properties_changed': + return replaceLayer(document, entry.layerId, (layer) => ({ + ...layer, + ...(direction === 'redo' ? entry.after : entry.before), + })) + case 'layer_moved': + return moveLayerTo( + document, + entry.layerId, + direction === 'redo' ? entry.to : entry.from, + ) + case 'layer_cleared': + return replaceLayer(document, entry.layerId, (layer) => ({ + ...layer, + operations: direction === 'redo' ? [] : entry.operations, + })) + case 'title_changed': + return { ...document, title: direction === 'redo' ? entry.after : entry.before } + case 'trace_changed': + return { + ...document, + trace: { ...document.trace, ...(direction === 'redo' ? entry.after : entry.before) }, + } + default: { + const exhaustive: never = entry + return exhaustive + } + } +} + +export function trimPast(entries: HistoryEntry[], limits: HistoryLimits): HistoryEntry[] { + let total = entries.reduce((sum, entry) => sum + entry.bytes, 0) + let start = 0 + // Keep at least the newest entry even if it alone exceeds maxBytes. + while (entries.length - start > limits.maxEntries || (total > limits.maxBytes && entries.length - start > 1)) { + total -= entries[start]!.bytes + start += 1 + } + return start === 0 ? entries : entries.slice(start) +} + +export function trimFuture(entries: HistoryEntry[], limits: HistoryLimits): HistoryEntry[] { + let total = entries.reduce((sum, entry) => sum + entry.bytes, 0) + let end = entries.length + // Future is newest-first; drop from the end (oldest redo entries). + while (end > limits.maxEntries || (total > limits.maxBytes && end > 1)) { + end -= 1 + total -= entries[end]!.bytes + } + return end === entries.length ? entries : entries.slice(0, end) +} diff --git a/apps/web/src/state/documentStore.perf.test.ts b/apps/web/src/state/documentStore.perf.test.ts new file mode 100644 index 0000000..5eb21a7 --- /dev/null +++ b/apps/web/src/state/documentStore.perf.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from 'vitest' +import type { DrawPoint, StrokeOperation } from '../lib/types' +import { createDocumentStore } from './documentStore' +import { estimateOperationBytes } from './documentHistory' + +const STROKES = 200 +const POINTS_PER_STROKE = 500 + +function longStroke(index: number): StrokeOperation { + const points: DrawPoint[] = Array.from({ length: POINTS_PER_STROKE }, (_, point) => ({ + x: (index * 17 + point) % 2048, + y: (index * 29 + point * 3) % 2048, + pressure: 0.5, + time: point, + })) + return { + id: `stroke-${index}`, + kind: 'stroke', + tool: 'pressure', + points, + size: 12, + smoothing: 0.5, + streamline: 0.5, + simulatePressure: false, + createdAt: index, + } +} + +function percentile(values: number[], fraction: number) { + const sorted = [...values].sort((left, right) => left - right) + return sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * fraction))] ?? 0 +} + +describe('document store commit performance', () => { + it('retains stroke payload rather than full-document snapshots', () => { + const store = createDocumentStore() + const initialLayers = store.getState().document.layers + const strokes = Array.from({ length: STROKES }, (_, index) => longStroke(index)) + const commitMs: number[] = [] + + for (const operation of strokes) { + const start = performance.now() + store.getState().commitOperation(operation) + commitMs.push(performance.now() - start) + } + + const totalMs = commitMs.reduce((sum, value) => sum + value, 0) + const retainedBytes = store.getState().past.reduce((sum, entry) => sum + entry.bytes, 0) + const rawBytes = STROKES * estimateOperationBytes(longStroke(0)) + const finalCloneMs = (() => { + const start = performance.now() + structuredClone(store.getState().document) + return performance.now() - start + })() + + console.info('[document-store perf]', { + strokes: STROKES, + pointsPerStroke: POINTS_PER_STROKE, + p50Ms: percentile(commitMs, 0.5), + p95Ms: percentile(commitMs, 0.95), + totalMs, + retainedBytes, + rawBytes, + retainedRatio: retainedBytes / rawBytes, + finalCloneMs, + oldCommitVolumeMs: finalCloneMs * STROKES, + }) + + expect(store.getState().past).toHaveLength(STROKES) + expect(retainedBytes).toBeLessThanOrEqual(rawBytes * 2) + expect(totalMs).toBeLessThan(5000) + expect(store.getState().document.layers[1]).toBe(initialLayers[1]) + expect(store.getState().document.layers[2]).toBe(initialLayers[2]) + expect(store.getState().document.layers[3]).toBe(initialLayers[3]) + + const entry = store.getState().past[0] + expect(entry?.kind).toBe('operation_appended') + if (entry?.kind === 'operation_appended' && entry.operation.kind === 'stroke' && strokes[0]) { + expect(entry.operation.points).toBe(strokes[0].points) + } + }, 20000) +}) diff --git a/apps/web/src/state/documentStore.test.ts b/apps/web/src/state/documentStore.test.ts index bb7e0cf..6fc8373 100644 --- a/apps/web/src/state/documentStore.test.ts +++ b/apps/web/src/state/documentStore.test.ts @@ -1,6 +1,24 @@ import { beforeEach, describe, expect, it } from 'vitest' import { makeStrokeOperation } from '../lib/drawing' -import { createDocumentStore, useDocumentStore } from './documentStore' +import type { DrawingDocument, StrokeOperation } from '../lib/types' +import { documentsEquivalent, replaySequence } from '../services/recordingValidation' +import type { DrawingSequenceCurrent } from '../services/recordingTypes' +import { createDocumentStore, useDocumentStore, type DocumentCommand } from './documentStore' +import { estimateOperationBytes } from './documentHistory' + +const stroke = (id = 'stroke', points = 2): StrokeOperation => ({ + id, + kind: 'stroke', + tool: 'pressure', + points: Array.from({ length: points }, (_, index) => ({ x: index, y: index, pressure: 0.5, time: index })), + size: 8, + smoothing: 0.5, + streamline: 0.5, + simulatePressure: false, + createdAt: 0, +}) + +const operationsOf = (document: DrawingDocument, index: number) => document.layers[index]?.operations ?? [] describe('document store', () => { beforeEach(() => useDocumentStore.getState().newDocument()) @@ -57,3 +75,327 @@ describe('document store', () => { expect(commands).toEqual(['operation_committed']) }) }) + +describe('document store structural sharing', () => { + it('shares untouched layers and prior operations across a commit', () => { + const store = createDocumentStore() + const first = stroke('first') + store.getState().commitOperation(first) + const before = store.getState().document + store.getState().commitOperation(stroke('second')) + const after = store.getState().document + + expect(after).not.toBe(before) + expect(after.layers[0]).not.toBe(before.layers[0]) + for (let index = 1; index < 4; index += 1) { + expect(after.layers[index]).toBe(before.layers[index]) + } + expect(after.layers[0]?.operations[0]).toBe(before.layers[0]?.operations[0]) + }) + + it('shares the committed points array while copying the operation object', () => { + const store = createDocumentStore() + const first = stroke('first', 4) + store.getState().commitOperation(first) + const entry = store.getState().past[0] + expect(entry?.kind).toBe('operation_appended') + if (entry?.kind === 'operation_appended' && entry.operation.kind === 'stroke') { + expect(entry.operation).not.toBe(first) + expect(entry.operation.points).toBe(first.points) + } + }) + + it('keeps the layers array shared for metadata-only changes', () => { + const store = createDocumentStore() + const layers = store.getState().document.layers + + store.getState().setTitle('Sketch') + expect(store.getState().document.layers).toBe(layers) + + store.getState().updateTrace({ opacity: 0.5 }) + expect(store.getState().document.layers).toBe(layers) + + store.getState().setTrace('asset-1', 'blob:trace') + expect(store.getState().document.layers).toBe(layers) + + store.getState().setResolvedTraceImage('blob:resolved') + expect(store.getState().document.layers).toBe(layers) + }) + + it('shares sibling layers for a single-layer property edit', () => { + const store = createDocumentStore() + const before = store.getState().document.layers + store.getState().updateLayer('layer-2', { opacity: 0.4 }) + const after = store.getState().document.layers + expect(after[0]).toBe(before[0]) + expect(after[1]).not.toBe(before[1]) + expect(after[2]).toBe(before[2]) + expect(after[3]).toBe(before[3]) + }) + + it('never mutates the document passed to replaceDocument', () => { + const store = createDocumentStore() + const incoming = structuredClone(store.getState().document) + incoming.title = 'Imported' + const snapshot = structuredClone(incoming) + store.getState().replaceDocument(incoming) + expect(incoming).toEqual(snapshot) + expect(store.getState().document.title).toBe('Imported') + }) + + it('does not mutate previously committed operations', () => { + const store = createDocumentStore() + const first = stroke('first', 3) + store.getState().commitOperation(first) + const snapshot = structuredClone(first) + store.getState().commitOperation(stroke('second')) + expect(store.getState().document.layers[0]?.operations[0]).toEqual(snapshot) + }) +}) + +describe('document store history semantics', () => { + it('undoes and redoes a layer move in both directions', () => { + const store = createDocumentStore() + store.getState().moveLayer('layer-1', 1) + expect(store.getState().document.layers.map((layer) => layer.id)).toEqual(['layer-2', 'layer-1', 'layer-3', 'layer-4']) + store.getState().undo() + expect(store.getState().document.layers.map((layer) => layer.id)).toEqual(['layer-1', 'layer-2', 'layer-3', 'layer-4']) + store.getState().redo() + expect(store.getState().document.layers.map((layer) => layer.id)).toEqual(['layer-2', 'layer-1', 'layer-3', 'layer-4']) + }) + + it('restores every operation after clearing a layer', () => { + const store = createDocumentStore() + const first = stroke('first') + const second = stroke('second') + store.getState().commitOperation(first) + store.getState().commitOperation(second) + store.getState().clearLayer('layer-1') + expect(operationsOf(store.getState().document, 0)).toHaveLength(0) + store.getState().undo() + expect(operationsOf(store.getState().document, 0).map((operation) => operation.id)).toEqual([first.id, second.id]) + store.getState().redo() + expect(operationsOf(store.getState().document, 0)).toHaveLength(0) + }) + + it('restores truncated titles and ignores an unchanged title', () => { + const store = createDocumentStore() + const longTitle = 'x'.repeat(100) + store.getState().setTitle(longTitle) + expect(store.getState().document.title).toHaveLength(80) + const state = store.getState() + store.getState().setTitle(longTitle) + expect(store.getState()).toBe(state) + store.getState().undo() + expect(store.getState().document.title).toBe('Untitled drawing') + store.getState().redo() + expect(store.getState().document.title).toBe('x'.repeat(80)) + }) + + it('undoes and redoes trace commands without clobbering a resolved image', () => { + const store = createDocumentStore() + store.getState().setTrace('asset-1', 'blob:original') + store.getState().updateTrace({ opacity: 0.5 }) + const historyLength = store.getState().past.length + store.getState().setResolvedTraceImage('blob:resolved') + expect(store.getState().past).toHaveLength(historyLength) + expect(store.getState().document.trace.imageUrl).toBe('blob:resolved') + + store.getState().undo() + expect(store.getState().document.trace).toMatchObject({ opacity: 0.3, imageUrl: 'blob:resolved' }) + store.getState().redo() + expect(store.getState().document.trace).toMatchObject({ opacity: 0.5, imageUrl: 'blob:resolved' }) + + store.getState().clearTrace() + expect(store.getState().document.trace).toMatchObject({ assetId: null, imageUrl: null, visible: true }) + store.getState().undo() + expect(store.getState().document.trace).toMatchObject({ assetId: 'asset-1', imageUrl: 'blob:resolved' }) + store.getState().redo() + expect(store.getState().document.trace).toMatchObject({ assetId: null, imageUrl: null }) + }) + + it('undoes and redoes visibility and scale updates', () => { + const store = createDocumentStore() + store.getState().updateTrace({ visible: false }) + store.getState().updateTrace({ scale: 2 }) + store.getState().undo() + expect(store.getState().document.trace.scale).toBe(1) + store.getState().undo() + expect(store.getState().document.trace.visible).toBe(true) + store.getState().redo() + expect(store.getState().document.trace.visible).toBe(false) + store.getState().redo() + expect(store.getState().document.trace.scale).toBe(2) + }) + + it('resets history on replacement and creation', () => { + const store = createDocumentStore() + store.getState().commitOperation(stroke('first')) + const incoming = structuredClone(store.getState().document) + incoming.title = 'Restored' + store.getState().replaceDocument(incoming) + expect(store.getState().past).toHaveLength(0) + expect(store.getState().future).toHaveLength(0) + const replaced = store.getState() + store.getState().undo() + expect(store.getState()).toBe(replaced) + + store.getState().commitOperation(stroke('second')) + store.getState().newDocument() + expect(store.getState().past).toHaveLength(0) + expect(store.getState().future).toHaveLength(0) + expect(store.getState().document.layers.map((layer) => layer.id)).toEqual(['layer-1', 'layer-2', 'layer-3', 'layer-4']) + expect(store.getState().activeLayerId).toBe('layer-1') + }) + + it('caps past and future by entry count and keeps the newest entry', () => { + const store = createDocumentStore({ history: { maxEntries: 3 } }) + for (let index = 0; index < 5; index += 1) store.getState().commitOperation(stroke(`stroke-${index}`)) + expect(store.getState().past).toHaveLength(3) + const retained = store.getState().past.map((entry) => entry.kind === 'operation_appended' ? entry.operation.id : '') + expect(retained).toEqual(['stroke-2', 'stroke-3', 'stroke-4']) + + for (let index = 0; index < 5; index += 1) store.getState().undo() + expect(store.getState().past).toHaveLength(0) + expect(store.getState().future).toHaveLength(3) + const redoable = store.getState().future.map((entry) => entry.kind === 'operation_appended' ? entry.operation.id : '') + expect(redoable).toEqual(['stroke-2', 'stroke-3', 'stroke-4']) + }) + + it('enforces the byte budget while retaining the newest entry', () => { + const store = createDocumentStore({ history: { maxBytes: 200 } }) + store.getState().commitOperation(stroke('first', 10)) + store.getState().commitOperation(stroke('second', 10)) + expect(store.getState().past).toHaveLength(1) + const retained = store.getState().past[0] + expect(retained?.kind === 'operation_appended' ? retained.operation.id : null).toBe('second') + + const tiny = createDocumentStore({ history: { maxBytes: 1 } }) + tiny.getState().commitOperation(stroke('only')) + expect(tiny.getState().past).toHaveLength(1) + }) + + it('returns the same state for no-op actions', () => { + const store = createDocumentStore() + const state = store.getState() + store.getState().updateLayer('layer-1', { opacity: 1 }) + store.getState().moveLayer('layer-1', -1) + store.getState().moveLayer('missing', 1) + store.getState().clearLayer('layer-1') + store.getState().setTitle('Untitled drawing') + store.getState().setResolvedTraceImage(null) + store.getState().undo() + store.getState().redo() + expect(store.getState()).toBe(state) + }) +}) + +describe('document store round-trip equivalence', () => { + it('replays every entry kind back to the initial state and forward again', () => { + const store = createDocumentStore() + const initial = structuredClone(store.getState().document) + const snapshots: DrawingDocument[] = [] + + const capture = () => { + if (store.getState().past.length > snapshots.length) snapshots.push(structuredClone(store.getState().document)) + } + + for (let index = 0; index < 40; index += 1) { + const state = store.getState() + switch (index % 10) { + case 0: + store.getState().commitOperation(stroke(`stroke-${index}`)) + break + case 1: + store.getState().updateLayer('layer-1', { opacity: 0.1 + (index % 5) * 0.1 }) + break + case 2: { + const firstLayer = state.document.layers[0] + if (firstLayer) store.getState().moveLayer(firstLayer.id, 1) + break + } + case 3: + store.getState().setTitle(`Sketch ${index}`) + break + case 4: + store.getState().updateLayer('layer-2', { visible: index % 20 === 4 }) + break + case 5: + store.getState().commitOperation(stroke(`stroke-${index}`, 4)) + break + case 6: + store.getState().setTrace(`asset-${index}`, `blob:trace-${index}`) + break + case 7: + store.getState().updateTrace({ scale: 1 + (index % 3) }) + break + case 8: + store.getState().clearTrace() + break + case 9: + store.getState().clearLayer('layer-1') + break + } + capture() + } + + expect(snapshots.length).toBe(store.getState().past.length) + expect(snapshots.length).toBeGreaterThan(20) + + for (let index = snapshots.length - 1; index >= 1; index -= 1) { + store.getState().undo() + expect(documentsEquivalent(store.getState().document, snapshots[index - 1]!)).toBe(true) + } + store.getState().undo() + expect(documentsEquivalent(store.getState().document, initial)).toBe(true) + + for (let index = 0; index < snapshots.length; index += 1) { + store.getState().redo() + expect(documentsEquivalent(store.getState().document, snapshots[index]!)).toBe(true) + } + + store.getState().commitOperation(stroke('after-redo')) + expect(store.getState().future).toHaveLength(0) + const beforeRedo = store.getState() + store.getState().redo() + expect(store.getState()).toBe(beforeRedo) + }) +}) + +describe('document store and recording replay', () => { + it('produces the same document as replaying the emitted commands', () => { + const commands: DocumentCommand[] = [] + const store = createDocumentStore({ onCommand: (command) => commands.push(command) }) + + store.getState().setActiveLayer('layer-1') + store.getState().commitOperation(stroke('one')) + store.getState().updateLayer('layer-1', { opacity: 0.5 }) + store.getState().setActiveLayer('layer-2') + store.getState().commitOperation(stroke('two')) + store.getState().moveLayer('layer-2', -1) + store.getState().clearLayer('layer-1') + store.getState().undo() + store.getState().redo() + store.getState().commitOperation(stroke('three')) + + const bundle = { + document: structuredClone(store.getState().document), + events: commands.map((command, index) => ({ + seq: index, + atMs: index, + action: { type: 'document_mutation', command }, + })), + } as unknown as DrawingSequenceCurrent + + expect(documentsEquivalent(store.getState().document, replaySequence(bundle))).toBe(true) + }) + + it('keeps retained history proportional to committed strokes', () => { + const store = createDocumentStore() + const first = stroke('first', 50) + const perStroke = estimateOperationBytes(first) + for (let index = 0; index < 20; index += 1) store.getState().commitOperation(stroke(`stroke-${index}`, 50)) + const retained = store.getState().past.reduce((sum, entry) => sum + entry.bytes, 0) + expect(retained).toBeLessThanOrEqual(20 * perStroke * 2) + }) +}) diff --git a/apps/web/src/state/documentStore.ts b/apps/web/src/state/documentStore.ts index e5f5c80..64969e5 100644 --- a/apps/web/src/state/documentStore.ts +++ b/apps/web/src/state/documentStore.ts @@ -2,7 +2,21 @@ import { createStore, type StoreApi } from 'zustand/vanilla' import { useContext, createContext, createElement, type ReactNode } from 'react' import { useStore } from 'zustand' import { uid } from '../lib/drawing' -import type { DrawingDocument, StrokeOperation, Tool } from '../lib/types' +import type { DrawingDocument, DrawingLayer, StrokeOperation, Tool } from '../lib/types' +import { + DEFAULT_HISTORY_LIMITS, + applyHistoryEntry, + layerClearedEntry, + layerMovedEntry, + layerPropertiesChangedEntry, + operationAppendedEntry, + titleChangedEntry, + traceChangedEntry, + trimFuture, + trimPast, + type HistoryEntry, + type HistoryLimits, +} from './documentHistory' export type DocumentCommand = | { type: 'operation_committed'; layerId: string; operation: StrokeOperation } @@ -17,6 +31,7 @@ export type DocumentCommand = export interface DocumentStoreOptions { onCommand?: (command: DocumentCommand) => void + history?: Partial } const makeDocument = (): DrawingDocument => ({ @@ -40,14 +55,10 @@ const makeDocument = (): DrawingDocument => ({ }, }) -function cloneDocument(document: DrawingDocument): DrawingDocument { - return structuredClone(document) -} - export interface DocumentState { document: DrawingDocument - past: DrawingDocument[] - future: DrawingDocument[] + past: HistoryEntry[] + future: HistoryEntry[] activeLayerId: string activeTool: Tool brushSize: number @@ -75,41 +86,56 @@ export interface DocumentState { newDocument: () => void } -function mutateDocument( - state: DocumentState, - mutation: (document: DrawingDocument) => void, - affectsSearch = true, -): Pick { - const next = cloneDocument(state.document) - mutation(next) - if (affectsSearch) next.revision += 1 - next.updatedAt = Date.now() - return { - document: next, - past: [...state.past.slice(-499), state.document], - future: [], - } -} +const layerSettings = (layer: DrawingLayer) => ({ + name: layer.name, + visible: layer.visible, + opacity: layer.opacity, +}) export function createDocumentStore(options: DocumentStoreOptions = {}): StoreApi { const emit = options.onCommand ?? (() => undefined) + const limits = { ...DEFAULT_HISTORY_LIMITS, ...options.history } + + function commitEntry( + state: DocumentState, + entry: HistoryEntry, + affectsSearch: boolean, + ): Pick { + const next = applyHistoryEntry(state.document, entry, 'redo') + return { + document: { + ...next, + revision: state.document.revision + (affectsSearch ? 1 : 0), + updatedAt: Date.now(), + }, + past: trimPast([...state.past, entry], limits), + future: [], + } + } + return createStore((set) => ({ document: makeDocument(), - past: [], - future: [], - activeLayerId: 'layer-1', - activeTool: 'pressure', - brushSize: 12, - stabilization: 50, - simulatePressure: true, - hasHydrated: false, + past: [], + future: [], + activeLayerId: 'layer-1', + activeTool: 'pressure', + brushSize: 12, + stabilization: 50, + simulatePressure: true, + hasHydrated: false, setHydrated: (hasHydrated) => set({ hasHydrated }), + // A replacement is an ownership boundary: the incoming document may be + // shared with import/restore code, so clone once and reset history. replaceDocument: (document, activeLayerId) => set((state) => { - const next = { document: { ...cloneDocument(document), revision: state.document.revision + 1 }, past: [], future: [], activeLayerId: document.layers.some((layer) => layer.id === activeLayerId) ? activeLayerId! : document.layers[0]?.id ?? 'layer-1' } + const next = { document: { ...structuredClone(document), revision: state.document.revision + 1 }, past: [], future: [], activeLayerId: document.layers.some((layer) => layer.id === activeLayerId) ? activeLayerId! : document.layers[0]?.id ?? 'layer-1' } emit({ type: 'document_replaced' }) return next }), - setTitle: (title) => set((state) => mutateDocument(state, (document) => { document.title = title.slice(0, 80) }, false)), + setTitle: (title) => set((state) => { + const next = title.slice(0, 80) + if (next === state.document.title) return state + return commitEntry(state, titleChangedEntry(state.document.title, next), false) + }), setTool: (activeTool) => set({ activeTool }), setBrushSize: (brushSize) => set({ brushSize: Math.min(40, Math.max(1, brushSize)) }), setStabilization: (stabilization) => set({ stabilization: Math.min(100, Math.max(0, stabilization)) }), @@ -119,10 +145,13 @@ export function createDocumentStore(options: DocumentStoreOptions = {}): StoreAp const layerId = state.activeLayerId const layer = state.document.layers.find((candidate) => candidate.id === layerId) if (!layer) return state - emit({ type: 'operation_committed', layerId, operation: structuredClone(operation) }) - return mutateDocument(state, (document) => { - document.layers.find((candidate) => candidate.id === layerId)?.operations.push(operation) - }) + // Shallow copy keeps the ownership boundary cheap; `points` is shared and + // must be treated as immutable after commit. + const committed = { ...operation } + if (options.onCommand) { + options.onCommand({ type: 'operation_committed', layerId, operation: structuredClone(operation) }) + } + return commitEntry(state, operationAppendedEntry(layerId, committed), true) }), updateLayer: (id, update) => set((state) => { const current = state.document.layers.find((layer) => layer.id === id) @@ -136,64 +165,76 @@ export function createDocumentStore(options: DocumentStoreOptions = {}): StoreAp ...(update.visible === undefined ? {} : { visible: nextVisible }), ...(update.opacity === undefined ? {} : { opacity: nextOpacity }), } }) - return mutateDocument(state, (document) => { - const layer = document.layers.find((candidate) => candidate.id === id) - if (!layer) return - if (update.name !== undefined) layer.name = update.name.slice(0, 40) - if (update.visible !== undefined) layer.visible = update.visible - if (update.opacity !== undefined) layer.opacity = Math.min(1, Math.max(0, update.opacity)) - }, update.visible !== undefined || update.opacity !== undefined) + return commitEntry(state, layerPropertiesChangedEntry(id, layerSettings(current), { + name: nextName, + visible: nextVisible, + opacity: nextOpacity, + }), update.visible !== undefined || update.opacity !== undefined) }), moveLayer: (id, direction) => set((state) => { const index = state.document.layers.findIndex((layer) => layer.id === id) const target = index + direction if (index < 0 || target < 0 || target >= state.document.layers.length) return state emit({ type: 'layer_moved', layerId: id, direction }) - return mutateDocument(state, (document) => { - const [layer] = document.layers.splice(index, 1) - if (layer) document.layers.splice(target, 0, layer) - }) + return commitEntry(state, layerMovedEntry(id, index, target), true) }), clearLayer: (id) => set((state) => { const layer = state.document.layers.find((candidate) => candidate.id === id) if (!layer || layer.operations.length === 0) return state emit({ type: 'layer_cleared', layerId: id }) - return mutateDocument(state, (document) => { - const target = document.layers.find((candidate) => candidate.id === id) - if (target) target.operations = [] - }) + return commitEntry(state, layerClearedEntry(id, layer.operations), true) }), setTrace: (assetId, imageUrl) => set((state) => { emit({ type: 'trace_updated' }) - return mutateDocument(state, (document) => { - document.trace = { ...document.trace, assetId, imageUrl, visible: true } - }, false) + const trace = state.document.trace + return commitEntry(state, traceChangedEntry( + { assetId: trace.assetId, imageUrl: trace.imageUrl, visible: trace.visible }, + { assetId, imageUrl, visible: true }, + ), false) }), updateTrace: (update) => set((state) => { emit({ type: 'trace_updated' }) - return mutateDocument(state, (document) => { - document.trace = { ...document.trace, ...update } - }, false) + const trace = state.document.trace + const before: Partial> = {} + const after: Partial> = {} + if (update.visible !== undefined) { before.visible = trace.visible; after.visible = update.visible } + if (update.opacity !== undefined) { before.opacity = trace.opacity; after.opacity = update.opacity } + if (update.scale !== undefined) { before.scale = trace.scale; after.scale = update.scale } + return commitEntry(state, traceChangedEntry(before, after), false) }), clearTrace: () => set((state) => { emit({ type: 'trace_updated' }) - return mutateDocument(state, (document) => { - document.trace.assetId = null - document.trace.imageUrl = null - }, false) + const trace = state.document.trace + return commitEntry(state, traceChangedEntry( + { assetId: trace.assetId, imageUrl: trace.imageUrl }, + { assetId: null, imageUrl: null }, + ), false) + }), + setResolvedTraceImage: (imageUrl) => set((state) => { + if (state.document.trace.imageUrl === imageUrl) return state + return { document: { ...state.document, trace: { ...state.document.trace, imageUrl } } } }), - setResolvedTraceImage: (imageUrl) => set((state) => ({ document: { ...state.document, trace: { ...state.document.trace, imageUrl } } })), undo: () => set((state) => { - const previous = state.past.at(-1) - if (!previous) return state - emit({ type: 'undo' }) - return { document: { ...cloneDocument(previous), revision: state.document.revision + 1, updatedAt: Date.now() }, past: state.past.slice(0, -1), future: [state.document, ...state.future].slice(0, 500) } + const entry = state.past.at(-1) + if (!entry) return state + const next = applyHistoryEntry(state.document, entry, 'undo') + emit({ type: 'undo' }) + return { + document: { ...next, revision: state.document.revision + 1, updatedAt: Date.now() }, + past: state.past.slice(0, -1), + future: trimFuture([entry, ...state.future], limits), + } }), redo: () => set((state) => { - const next = state.future[0] - if (!next) return state - emit({ type: 'redo' }) - return { document: { ...cloneDocument(next), revision: state.document.revision + 1, updatedAt: Date.now() }, past: [...state.past, state.document].slice(-500), future: state.future.slice(1) } + const entry = state.future[0] + if (!entry) return state + const next = applyHistoryEntry(state.document, entry, 'redo') + emit({ type: 'redo' }) + return { + document: { ...next, revision: state.document.revision + 1, updatedAt: Date.now() }, + past: trimPast([...state.past, entry], limits), + future: state.future.slice(1), + } }), newDocument: () => set((state) => { emit({ type: 'document_created' })