Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
14 changes: 7 additions & 7 deletions apps/web/src/components/CanvasStage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,23 +27,23 @@ 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,
canvas: HTMLCanvasElement,
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 }) {
Expand Down Expand Up @@ -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)
}
Expand All @@ -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,
})
}
})
Expand Down
56 changes: 56 additions & 0 deletions apps/web/src/services/rasterAssets.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
19 changes: 17 additions & 2 deletions apps/web/src/services/rasterAssets.ts
Original file line number Diff line number Diff line change
@@ -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<string, Promise<HTMLImageElement>>()
const layerAssetCache = new WeakMap<DrawingOperation[], string[]>()

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<string>()
for (const layer of document.layers) {
for (const id of assetsForOperations(layer.operations)) ids.add(id)
}
return [...ids]
}

function decodeBlob(blob: Blob) {
Expand Down
162 changes: 162 additions & 0 deletions apps/web/src/state/documentHistory.test.ts
Original file line number Diff line number Diff line change
@@ -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 })
})
})
Loading
Loading