AI-native design editor. Open-source Figma alternative.
refactor(scene-graph)!: name images by their SHA-1 (#1108)
Danila Poyarkovbca379c79a2c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c7f43165b..f8d875bf8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,12 +2,17 @@## Unreleased+### Breaking changes++- `computeImageHash` from `@open-pencil/core` and `@open-pencil/scene-graph` returns the hex SHA-1 of the bytes, the name Figma gives an image, instead of an OpenPencil-only hash of the same length. New images are stored under that name, so `.fig` files and the Figma clipboard carry it as it is; images in documents saved before keep their names.+### Changed- Trackpads and mouse wheels pan and zoom the canvas as in Figma. A two-finger pan moves the canvas twice as far, up to 120 px per scroll event. A pinch zooms as far in the desktop app and Safari as in other browsers, where it zooms a little less than before. In the desktop app and Safari, a pinch over Preview's live controls or comment pins now zooms the canvas, where it did nothing. On Windows each mouse wheel notch pans 16 px instead of 100 px, and notches less than 50 ms apart pan up to 120 px each.### Fixed+- Figma shows shader fills and images from older documents in `.fig` files OpenPencil writes: every image is stored under the SHA-1 of its bytes, the only name Figma reads, and a shader keeps its preset through `.fig` files and the Figma clipboard.- HTML, Vue, and React exports name a JPEG, GIF, or WebP image fill by its own type in the data URL instead of calling every image PNG.### Performancediff --git a/bun.lock b/bun.lockindex 117592fa6..9d07ab962 100644--- a/bun.lock+++ b/bun.lock@@ -457,6 +457,7 @@"name": "@open-pencil/scene-graph","version": "0.16.0-beta.2","dependencies": {+ "@noble/hashes": "^2.4.0","culori": "^4.0.2","es-toolkit": "^1.52.0","nanoevents": "^9.1.0",@@ -1405,6 +1406,8 @@"@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.4", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4" } }, "sha512-UMduMbqO5s5zF2NkNacMT/yK5Y5QiKvWr2+50bzIIxFDwVJ2h49b+oyjaCGPhJxd2/gC2x39EHv/gHVuu36x2Q=="],+ "@noble/hashes": ["@noble/[email protected]", "", {}, "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA=="],+"@nodable/entities": ["@nodable/[email protected]", "", {}, "sha512-8L9xFeTYKhm49xfIypoe2W5wV1m/3Z58kT+7kR9A8OyFxcPduI4VmxaUMQyKYrRjUoLLSXv6EKKID5Tvj9cUVw=="],"@nodelib/fs.scandir": ["@nodelib/[email protected]", "", { "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" } }, "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g=="],diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.tsindex 2bfa1e35f..36f2acd3a 100644--- a/packages/core/src/clipboard.ts+++ b/packages/core/src/clipboard.ts@@ -197,7 +197,7 @@ async function writeFigmaClipboardHTML(units: source.lineHeight ? 'PIXELS' : 'PERCENT'}}- await embedClipboardImages(nodeChanges, blobs, graph.images)+ embedClipboardImages(nodeChanges, blobs, graph.images)return encodeFigmaClipboard(nodeChanges, blobs, randomInt())}diff --git a/packages/core/src/io/formats/fig/export-setup.ts b/packages/core/src/io/formats/fig/export-setup.tsindex 525026040..aa8526d5d 100644--- a/packages/core/src/io/formats/fig/export-setup.ts+++ b/packages/core/src/io/formats/fig/export-setup.ts@@ -5,6 +5,7 @@ import { toUint8Array } from 'js-base64'import {buildComponentPropIndex,exportCanvasGuides,+ figImageEntries,importCanvasGuides,parseGuidOrNull,stringToGuid,@@ -55,14 +56,6 @@ export interface CanvasExportEntry {canvasNc: KiwiNodeChange}-function collectImageEntries(graph: SceneGraph): Array<{ name: string; data: Uint8Array }> {- const entries: Array<{ name: string; data: Uint8Array }> = []- for (const [hash, data] of graph.images) {- entries.push({ name: `images/${hash}`, data })- }- return entries-}-const THUMBNAIL_WIDTH = 512const THUMBNAIL_HEIGHT = 512@@ -502,9 +495,13 @@ export interface FigFileExtras {images: Array<{ name: string; data: Uint8Array }>}-/** The thumbnail, metadata and images a written `.fig` carries besides its records. */+/**+ * The thumbnail, metadata and images a written `.fig` carries besides its records, the images+ * under the names `nameImagesForFigma` gave them in those records.+ */export async function figFileExtras(graph: SceneGraph,+ imageNames: ReadonlyMap<string, string>,pageId: string | undefined,ck: CanvasKit | undefined,renderer: SkiaRenderer | undefined,@@ -523,5 +520,5 @@ export async function figFileExtras(app: 'OpenPencil',createdAt: new Date().toISOString()})- return { thumbnailPNG, metaJSON, images: collectImageEntries(graph) }+ return { thumbnailPNG, metaJSON, images: figImageEntries(graph.images, imageNames) }}diff --git a/packages/core/src/io/formats/fig/export.ts b/packages/core/src/io/formats/fig/export.tsindex d06ad3211..05dc9265a 100644--- a/packages/core/src/io/formats/fig/export.ts+++ b/packages/core/src/io/formats/fig/export.ts@@ -1,7 +1,11 @@import type { CanvasKit } from 'canvaskit-wasm'import { compressFigDataSync } from '@open-pencil/fig'-import { placeSlotContent, type FigNodeChangeExportRuntime } from '@open-pencil/fig/node-change'+import {+ nameImagesForFigma,+ placeSlotContent,+ type FigNodeChangeExportRuntime+} from '@open-pencil/fig/node-change'import { initCodec } from '@open-pencil/kiwi/fig/codec'import type { NodeChange } from '@open-pencil/kiwi/fig/codec'import type { SceneGraph } from '@open-pencil/scene-graph'@@ -19,7 +23,7 @@ import {type FigExportSetup,type KiwiNodeChange} from '#core/io/formats/fig/export-setup'-import { writePatchedFigFile } from '#core/io/formats/fig/patch-export'+import { archiveImagesNamedForFigma, writePatchedFigFile } from '#core/io/formats/fig/patch-export'import { sceneNodeToKiwi } from '#core/kiwi/fig/node-change/serialize'import { cloneSceneGraphForFigExport } from '#core/kiwi/fig/parse/transfer'import {@@ -106,18 +110,22 @@ export async function exportFigFile(pageId?: string,renderHeadlessThumbnail = false): Promise<Uint8Array> {- const originalArchive = await originalFigArchive(sourceGraph)+ // An archive whose images Figma cannot read is written whole rather than reused.+ const reuseArchive = await archiveImagesNamedForFigma(sourceGraph)+ const originalArchive = reuseArchive ? await originalFigArchive(sourceGraph) : nullif (originalArchive) return originalArchive.slice()return withFigExportRuntime(sourceGraph,ck,async (runtime) =>- (await writePatchedFigFile(sourceGraph, runtime, {- ck,- renderer,- pageId,- renderHeadlessThumbnail- })) ?? writeFigFile(sourceGraph, runtime, ck, renderer, pageId, renderHeadlessThumbnail)+ (reuseArchive+ ? await writePatchedFigFile(sourceGraph, runtime, {+ ck,+ renderer,+ pageId,+ renderHeadlessThumbnail+ })+ : null) ?? writeFigFile(sourceGraph, runtime, ck, renderer, pageId, renderHeadlessThumbnail))}@@ -188,8 +196,16 @@ async function writeFigFile(msg.blobs = blobs.map((bytes) => ({ bytes }))}+ const imageNames = nameImagesForFigma(nodeChanges, graph.images)const kiwiData = compiled.encodeMessage(msg)- const extras = await figFileExtras(graph, pageId, ck, renderer, renderHeadlessThumbnail)+ const extras = await figFileExtras(+ graph,+ imageNames,+ pageId,+ ck,+ renderer,+ renderHeadlessThumbnail+ )const version = graph.figKiwiVersion ?? undefineddiff --git a/packages/core/src/io/formats/fig/patch-export.ts b/packages/core/src/io/formats/fig/patch-export.tsindex 99b0897f9..1003350d8 100644--- a/packages/core/src/io/formats/fig/patch-export.ts+++ b/packages/core/src/io/formats/fig/patch-export.ts@@ -5,9 +5,14 @@ import {type FigArchiveRecordInfo,type FigRecordPatch} from '@open-pencil/fig'-import type { FigNodeChangeExportRuntime } from '@open-pencil/fig/node-change'+import { nameImagesForFigma, type FigNodeChangeExportRuntime } from '@open-pencil/fig/node-change'import { stringToGuid } from '@open-pencil/kiwi/fig/guid'-import { ownsSlotContent, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'+import {+ computeImageHash,+ ownsSlotContent,+ type SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'import { siblingOrderKeys } from '@open-pencil/scene-graph/order-keys'import type { GUID } from '@open-pencil/scene-graph/primitives'@@ -343,6 +348,31 @@ async function buildPatch(}}+const archiveImagesChecked = new WeakMap<FigArchiveAccess, Promise<boolean>>()++/**+ * Whether every image the archive `graph` was opened from holds is stored under the SHA-1 of its+ * bytes, the only name Figma reads. Archives OpenPencil wrote before image names were SHA-1 are+ * not, and records a save leaves untouched point at those names, so such a document is written+ * whole, which names every image as Figma needs, instead of reusing its archive. The archive+ * does not change, so it is checked once; a document with no archive has nothing to check.+ */+export function archiveImagesNamedForFigma(graph: SceneGraph): Promise<boolean> {+ const archive = figArchive(graph)+ if (!archive) return Promise.resolve(true)+ let checked = archiveImagesChecked.get(archive)+ if (!checked) {+ checked = archive.info().then(({ imageHashes }) =>+ imageHashes.every((name) => {+ const bytes = graph.images.get(name)+ return !bytes || computeImageHash(bytes) === name+ })+ )+ archiveImagesChecked.set(archive, checked)+ }+ return checked+}+/*** Write a document opened from a `.fig` as that archive with only its changed records* rewritten. The main thread serializes what changed; merging and compressing the rest happen@@ -372,8 +402,10 @@ export async function writePatchedFigFile(throw error}if (!built) return null+ const imageNames = nameImagesForFigma(built.patch.records, built.graph.images)const extras = await figFileExtras(built.graph,+ imageNames,options.pageId,options.ck,options.renderer,diff --git a/packages/core/tests/io/formats/fig/export/archive-patch.test.ts b/packages/core/tests/io/formats/fig/export/archive-patch.test.tsindex d23badc85..686e1683a 100644--- a/packages/core/tests/io/formats/fig/export/archive-patch.test.ts+++ b/packages/core/tests/io/formats/fig/export/archive-patch.test.ts@@ -2,13 +2,14 @@ import { describe, expect, setDefaultTimeout, test } from 'bun:test'import { expectDefined } from '#core-tests/helpers/assert'import { isEqual } from 'es-toolkit/predicate'+import { deflateSync } from 'fflate'import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'import { populateAllFigPages, populateFigPage } from '@open-pencil/core/io/formats/fig'-import { parseFigBuffer } from '@open-pencil/fig'-import type { NodeChange } from '@open-pencil/kiwi/fig/codec'+import { compressFigDataSync, parseFigBuffer } from '@open-pencil/fig'+import { getCompiledSchema, getSchemaBytes, type NodeChange } from '@open-pencil/kiwi/fig/codec'import { guidToString } from '@open-pencil/kiwi/fig/guid'-import { getSharedStyles, type SceneNode } from '@open-pencil/scene-graph'+import { computeImageHash, getSharedStyles, type SceneNode } from '@open-pencil/scene-graph'import { cloneNodeProps } from '@open-pencil/scene-graph/copy'import { releaseFigArchive } from '#core/kiwi/fig/session/archive'@@ -80,6 +81,74 @@ test('styles added to an opened file are written on the internal canvas, not as})/** A document over three pages: a frame of layers, a component, and a page of its instances. */+test('an archive whose images Figma cannot read is written whole, every image by its SHA-1', async () => {+ const graph = await open(await legacyImageArchive())+ graph.updateNode(layerNamed(graph, 'Photo 0').id, { name: 'Edited' })++ for (const saved of [+ await exportFigFile(graph),+ await exportFigFile(await open(await legacyImageArchive()))+ ]) {+ const photos = [...recordsOf(saved).values()].filter((record) => record.fillPaints?.length)+ const parsed = parseFigBuffer(saved.slice().buffer as ArrayBuffer)+ expect(photos.map((record) => paintImageName(record))).toEqual([PHOTO_NAME, PHOTO_NAME])+ expect(parsed.images.map(([name]) => name)).toEqual([PHOTO_NAME])+ }+})++const PHOTO = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, 7, 7, 7])+const PHOTO_NAME = computeImageHash(PHOTO)+/** A name an image had before images were named by their SHA-1. */+const LEGACY_NAME = '0123456789abcdef0123456789abcdef01234567'++function paintImageName(record: NodeChange): string | undefined {+ const hash = record.fillPaints?.[0]?.image?.hash+ return hash instanceof Uint8Array ? Buffer.from(hash).toString('hex') : undefined+}++/** Two layers painted with one image that the archive holds under a legacy name. */+async function legacyImageArchive(): Promise<Uint8Array> {+ await initCodec()+ const source = new SceneGraph()+ source.images.set(PHOTO_NAME, PHOTO)+ for (const index of [0, 1]) {+ source.createNode('RECTANGLE', source.getPages()[0].id, {+ name: `Photo ${index}`,+ x: index * 50,+ width: 40,+ height: 40,+ fills: [+ {+ type: 'IMAGE',+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true,+ imageHash: PHOTO_NAME,+ imageScaleMode: 'FILL'+ }+ ]+ })+ }+ const parsed = parseFigBuffer((await exportFigFile(source)).slice().buffer as ArrayBuffer)+ for (const record of parsed.nodeChanges) {+ const image = record.fillPaints?.[0]?.image+ if (image) image.hash = Uint8Array.from(Buffer.from(LEGACY_NAME, 'hex'))+ }+ const kiwi = getCompiledSchema().encodeMessage({+ type: 'NODE_CHANGES',+ sessionID: 0,+ ackID: 0,+ nodeChanges: parsed.nodeChanges+ })+ return compressFigDataSync(+ deflateSync(getSchemaBytes()),+ kiwi,+ expectDefined(parsed.thumbnailPNG, 'thumbnail'),+ parsed.metaJSON ?? '{}',+ [{ name: `images/${LEGACY_NAME}`, data: PHOTO }]+ )+}+async function fixtureBytes(): Promise<Uint8Array> {await initCodec()const source = new SceneGraph()diff --git a/packages/core/tests/io/formats/fig/roundtrip/shaders.test.ts b/packages/core/tests/io/formats/fig/roundtrip/shaders.test.tsindex c421d18df..6809cb111 100644--- a/packages/core/tests/io/formats/fig/roundtrip/shaders.test.ts+++ b/packages/core/tests/io/formats/fig/roundtrip/shaders.test.ts@@ -5,6 +5,7 @@ import { collectAllNodes } from '#core-tests/helpers/fig/traversal'import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'import {+ computeImageHash,createShaderPaint,shaderOfPaint,shaderPresetKey,@@ -18,7 +19,9 @@ const PRESET: ShaderPreset = { components: [{ type: 'Aurora', props: { colorA: '/*** A shader paint is an image paint of its frame with the preset in plugin data, so a `.fig`- * archive keeps both: Figma draws the frame, and OpenPencil reads the shader back.+ * archive keeps both: Figma draws the frame, and OpenPencil reads the shader back. Figma reads+ * the frame only under the SHA-1 of its bytes, so the archive names it that, in the paint and in+ * the plugin data alike.*/test('a shader fill keeps its frame and preset through a .fig archive', async () => {await initCodec()@@ -45,7 +48,45 @@ test('a shader fill keeps its frame and preset through a .fig archive', async ())const [fill] = copy.fills- expect(fill).toMatchObject({ type: 'IMAGE', imageHash: shader.image })- expect(read.images.get(shader.image)).toEqual(png)- expect(shaderOfPaint(copy, fill)).toEqual({ ...shader, frame })+ const figmaName = computeImageHash(png)+ expect(fill).toMatchObject({ type: 'IMAGE', imageHash: figmaName })+ expect(read.images.get(figmaName)).toEqual(png)+ expect(read.images.has(shader.image)).toBe(false)+ expect(shaderOfPaint(copy, fill)).toEqual({ ...shader, image: figmaName, frame })+})++test('images stored under other names are written once, under the SHA-1 of their bytes', async () => {+ await initCodec()+ const graph = new SceneGraph()+ const png = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, 1, 2, 3])+ // Two names for the same bytes, as documents saved before image names were SHA-1 can hold.+ const names = [+ '0123456789abcdef0123456789abcdef01234567',+ 'fedcba9876543210fedcba9876543210fedcba98'+ ]+ for (const [index, name] of names.entries()) {+ graph.images.set(name, png)+ graph.createNode('RECTANGLE', graph.getPages()[0].id, {+ name: `Photo ${index}`,+ width: 40,+ height: 40,+ fills: [+ {+ type: 'IMAGE',+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true,+ imageHash: name,+ imageScaleMode: 'FILL'+ }+ ]+ })+ }++ const read = await parseFigFile((await exportFigFile(graph)).buffer as ArrayBuffer)+ const figmaName = computeImageHash(png)+ const photos = collectAllNodes(read).filter((node) => node.name.startsWith('Photo'))++ expect(photos.map((photo) => photo.fills[0]?.imageHash)).toEqual([figmaName, figmaName])+ expect([...read.images.keys()]).toEqual([figmaName])})diff --git a/packages/fig/src/clipboard/images.ts b/packages/fig/src/clipboard/images.tsindex 2bff7b70a..ced2fe1c6 100644--- a/packages/fig/src/clipboard/images.ts+++ b/packages/fig/src/clipboard/images.ts@@ -1,41 +1,32 @@-import type { NodeChange, Paint } from '@open-pencil/kiwi/fig/codec'+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'import { bytesToHex } from '../node-change/bytes'+import { forEachImageReference, nameImagesForFigma } from '../node-change/images'-/** Clipboard recipients cannot fetch image hashes from an OpenPencil source file. */-export async function embedClipboardImages(+/**+ * Clipboard recipients cannot fetch images from an OpenPencil source file, so the images the+ * pasted records use travel with them as blobs, each once, under the name Figma reads them by.+ */+export function embedClipboardImages(changes: NodeChange[],blobs: Uint8Array[],images: ReadonlyMap<string, Uint8Array>-): Promise<void> {- const embedded = new Map<string, { index: number; hash: Uint8Array }>()- async function embed(paints: Paint[] = []) {- for (const paint of paints) {- for (const image of [paint.image, paint.imageThumbnail, paint.animatedImage]) {- if (!image?.hash) continue- const hash = typeof image.hash === 'string' ? image.hash : bytesToHex(image.hash)- const bytes = images.get(hash)- if (!bytes) continue- let entry = embedded.get(hash)- if (!entry) {- // Figma rejects bytes whose SHA-1 differs from the image reference.- // Internal SceneGraph image identifiers are not necessarily SHA-1.- const digest = await crypto.subtle.digest('SHA-1', new Uint8Array(bytes).buffer)- entry = { index: blobs.length, hash: new Uint8Array(digest) }- blobs.push(bytes)- embedded.set(hash, entry)- }- image.hash = entry.hash- image.dataBlob = entry.index- }+): void {+ const names = nameImagesForFigma(changes, images)+ const bytesByName = new Map<string, Uint8Array>()+ for (const [name, bytes] of images) bytesByName.set(names.get(name) ?? name, bytes)+ const indexes = new Map<string, number>()+ forEachImageReference(changes, (image) => {+ if (image.hash === undefined) return+ const name = typeof image.hash === 'string' ? image.hash : bytesToHex(image.hash)+ const bytes = bytesByName.get(name)+ if (!bytes) return+ let index = indexes.get(name)+ if (index === undefined) {+ index = blobs.length+ blobs.push(bytes)+ indexes.set(name, index)}- }- async function visit(change: NodeChange): Promise<void> {- await embed(change.fillPaints)- await embed(change.strokePaints)- await embed(change.backgroundPaints)- await embed(change.textDecorationFillPaints)- for (const override of change.textData?.styleOverrideTable ?? []) await visit(override)- }- for (const change of changes) await visit(change)+ image.dataBlob = index+ })}diff --git a/packages/fig/src/node-change/images.ts b/packages/fig/src/node-change/images.tsnew file mode 100644index 000000000..c58f75b0f--- /dev/null+++ b/packages/fig/src/node-change/images.ts@@ -0,0 +1,123 @@+import type { NodeChange, PluginData } from '@open-pencil/kiwi/fig/codec'+import {+ computeImageHash,+ OPEN_PENCIL_PLUGIN_DATA,+ OPEN_PENCIL_PLUGIN_ID+} from '@open-pencil/scene-graph'++import { bytesToHex, hexToBytes } from './bytes'++/** The fields of a paint that reference an image. */+const IMAGE_FIELDS = ['image', 'imageThumbnail', 'animatedImage'] as const++const { shader } = OPEN_PENCIL_PLUGIN_DATA++/** An image reference as a written paint holds it. */+export interface ImageReference {+ hash?: Uint8Array | string+ dataBlob?: number+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !ArrayBuffer.isView(value)+}++function isImageReference(value: unknown): value is ImageReference {+ return isRecord(value) && 'hash' in value+}++function isPluginData(value: unknown): value is PluginData {+ return isRecord(value) && 'pluginID' in value && 'key' in value+}++/**+ * Calls `visit` with every image reference and every plugin-data entry in `value`, however deep:+ * paints sit in fills, strokes, backgrounds, text and vector style overrides, and instance+ * overrides, and plugin data on records and overrides alike.+ */+function walk(+ value: unknown,+ visit: { image: (image: ImageReference) => void; pluginData: (entry: PluginData) => void }+): void {+ if (Array.isArray(value)) {+ for (const item of value) walk(item, visit)+ return+ }+ if (!isRecord(value)) return+ if (isPluginData(value)) {+ visit.pluginData(value)+ return+ }+ for (const field of IMAGE_FIELDS) {+ const image = value[field]+ if (isImageReference(image)) visit.image(image)+ }+ for (const child of Object.values(value)) walk(child, visit)+}++/** Every image reference the records' paints hold. */+export function forEachImageReference(+ changes: readonly NodeChange[],+ visit: (image: ImageReference) => void+): void {+ walk(changes, { image: visit, pluginData: () => undefined })+}++function referenceName(image: ImageReference): string | null {+ if (image.hash === undefined) return null+ return typeof image.hash === 'string' ? image.hash : bytesToHex(image.hash)+}++/**+ * Figma reads an image only under the SHA-1 of its bytes. A document may hold images under other+ * names: a shader's still frame under a name of its own, which stays while the frame is redrawn,+ * and images saved before images were named by their SHA-1. Points every image reference in+ * `changes` at its SHA-1, along with the shader plugin data that names a paint's image, so the+ * shader still finds its paint when the file is read back. Returns the new name of every image+ * renamed; references to images `images` lacks are left as they are.+ */+export function nameImagesForFigma(+ changes: readonly NodeChange[],+ images: ReadonlyMap<string, Uint8Array>+): Map<string, string> {+ const names = new Map<string, string>()+ const figmaName = (name: string): string | null => {+ const known = names.get(name)+ if (known) return known+ const bytes = images.get(name)+ if (!bytes) return null+ const hash = computeImageHash(bytes)+ names.set(name, hash)+ return hash+ }+ walk(changes, {+ image(image) {+ const name = referenceName(image)+ const renamed = name ? figmaName(name) : null+ if (!renamed || renamed === name) return+ image.hash = typeof image.hash === 'string' ? renamed : hexToBytes(renamed)+ },+ pluginData(entry) {+ if (entry.pluginID !== OPEN_PENCIL_PLUGIN_ID || entry.key !== shader.key) return+ const paint = shader.decode(entry.value)+ const renamed = paint ? figmaName(paint.image) : null+ if (!paint || !renamed || renamed === paint.image) return+ entry.value = shader.encode({ ...paint, image: renamed })+ }+ })+ return names+}++/**+ * `images` as a `.fig` archive stores them: each under the name `names` gave it, or the SHA-1 of+ * its bytes when no record references it, and each name once, so images that were stored twice+ * under different names are written once.+ */+export function figImageEntries(+ images: ReadonlyMap<string, Uint8Array>,+ names: ReadonlyMap<string, string>+): Array<{ name: string; data: Uint8Array }> {+ const entries = new Map<string, Uint8Array>()+ for (const [name, data] of images) entries.set(names.get(name) ?? computeImageHash(data), data)+ return [...entries].map(([name, data]) => ({ name: `images/${name}`, data }))+}diff --git a/packages/fig/src/node-change/index.ts b/packages/fig/src/node-change/index.tsindex 51c8fd73c..d8e8ef8e4 100644--- a/packages/fig/src/node-change/index.ts+++ b/packages/fig/src/node-change/index.ts@@ -11,6 +11,7 @@ export { placeSlotContent } from './export/slots'export * from './font/features'export * from './font/style'export * from './font/variations'+export * from './images'export * from './instance/linkage'export * from './paint'export * from './path/commands'diff --git a/packages/fig/tests/node-change/images.test.ts b/packages/fig/tests/node-change/images.test.tsnew file mode 100644index 000000000..4683f7f8d--- /dev/null+++ b/packages/fig/tests/node-change/images.test.ts@@ -0,0 +1,95 @@+import { describe, expect, test } from 'bun:test'++import { bytesToHex, hexToBytes } from '#fig/node-change/bytes'+import { figImageEntries, nameImagesForFigma } from '#fig/node-change/images'++import type { NodeChange } from '@open-pencil/kiwi/fig/codec'+import {+ computeImageHash,+ OPEN_PENCIL_PLUGIN_DATA,+ OPEN_PENCIL_PLUGIN_ID+} from '@open-pencil/scene-graph'++const STILL = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 1, 2, 3])+/** A shader still's own name, which is not the SHA-1 of its bytes. */+const STILL_NAME = 'aa'.repeat(20)+const FIGMA_NAME = computeImageHash(STILL)+const PRESET = { components: [{ type: 'Aurora' }] }++function imagePaint(name: string) {+ return { type: 'IMAGE' as const, image: { hash: hexToBytes(name) } }+}++/** A layer whose fill is a shader still, and a text style override that paints the same still. */+function records(): NodeChange[] {+ return [+ {+ fillPaints: [imagePaint(STILL_NAME)],+ pluginData: [+ {+ pluginID: OPEN_PENCIL_PLUGIN_ID,+ key: OPEN_PENCIL_PLUGIN_DATA.shader.key,+ value: OPEN_PENCIL_PLUGIN_DATA.shader.encode({ image: STILL_NAME, preset: PRESET })+ }+ ],+ textData: { characters: '', styleOverrideTable: [{ fillPaints: [imagePaint(STILL_NAME)] }] }+ }+ ]+}++function paintName(paint: { image?: { hash?: Uint8Array | string } } | undefined): string {+ const hash = paint?.image?.hash+ return hash instanceof Uint8Array ? bytesToHex(hash) : String(hash)+}++describe('nameImagesForFigma', () => {+ test('points every paint at the SHA-1 of its image, however deep', () => {+ const changes = records()+ const names = nameImagesForFigma(changes, new Map([[STILL_NAME, STILL]]))+ const [layer] = changes++ expect(names).toEqual(new Map([[STILL_NAME, FIGMA_NAME]]))+ expect(paintName(layer.fillPaints?.[0])).toBe(FIGMA_NAME)+ expect(paintName(layer.textData?.styleOverrideTable?.[0]?.fillPaints?.[0])).toBe(FIGMA_NAME)+ })++ test('renames the image in shader plugin data, so the shader still finds its paint', () => {+ const changes = records()+ nameImagesForFigma(changes, new Map([[STILL_NAME, STILL]]))+ const entry = changes[0].pluginData?.[0]++ expect(OPEN_PENCIL_PLUGIN_DATA.shader.decode(entry?.value)).toEqual({+ image: FIGMA_NAME,+ preset: PRESET+ })+ })++ test('leaves references to images it does not have as they are', () => {+ const changes = records()+ expect(nameImagesForFigma(changes, new Map())).toEqual(new Map())+ expect(paintName(changes[0].fillPaints?.[0])).toBe(STILL_NAME)+ })+})++describe('figImageEntries', () => {+ test('names an image no record references by its SHA-1 too', () => {+ const images = new Map([[STILL_NAME, STILL]])+ expect(figImageEntries(images, new Map())).toEqual([+ { name: `images/${FIGMA_NAME}`, data: STILL }+ ])+ })++ test('writes each image once under its new name', () => {+ const other = 'bb'.repeat(20)+ const images = new Map([+ [STILL_NAME, STILL],+ [other, STILL]+ ])+ const names = new Map([+ [STILL_NAME, FIGMA_NAME],+ [other, FIGMA_NAME]+ ])++ expect(figImageEntries(images, names)).toEqual([{ name: `images/${FIGMA_NAME}`, data: STILL }])+ })+})diff --git a/packages/scene-graph/package.json b/packages/scene-graph/package.jsonindex caa894e9d..d98cfa401 100644--- a/packages/scene-graph/package.json+++ b/packages/scene-graph/package.json@@ -235,6 +235,7 @@"typecheck": "bunx tsc --noEmit -p tsconfig.test.json"},"dependencies": {+ "@noble/hashes": "^2.4.0","culori": "^4.0.2","es-toolkit": "^1.52.0","nanoevents": "^9.1.0",diff --git a/packages/scene-graph/src/images.ts b/packages/scene-graph/src/images.tsindex 3b40225f4..beb9ec353 100644--- a/packages/scene-graph/src/images.ts+++ b/packages/scene-graph/src/images.ts@@ -1,36 +1,13 @@+import { sha1 } from '@noble/hashes/legacy.js'+import { bytesToHex } from '@noble/hashes/utils.js'++/**+ * The name an image's bytes are stored under: the hex SHA-1 of the bytes, as Figma names images,+ * so `.fig` files and the Figma clipboard can carry the name as it is. Documents saved before may+ * hold images under other names; anything that hands images to Figma still checks.+ */export function computeImageHash(data: Uint8Array): string {- let h1 = 0x811c9dc5 >>> 0- let h2 = 0x811c9dc5 >>> 0- let h3 = 0x811c9dc5 >>> 0- let h4 = 0x811c9dc5 >>> 0- let h5 = 0x811c9dc5 >>> 0- for (let i = 0; i < data.length; i++) {- const b = data[i]- switch (i % 5) {- case 0:- h1 ^= b- h1 = Math.imul(h1, 0x01000193) >>> 0- break- case 1:- h2 ^= b- h2 = Math.imul(h2, 0x01000193) >>> 0- break- case 2:- h3 ^= b- h3 = Math.imul(h3, 0x01000193) >>> 0- break- case 3:- h4 ^= b- h4 = Math.imul(h4, 0x01000193) >>> 0- break- default:- h5 ^= b- h5 = Math.imul(h5, 0x01000193) >>> 0- break- }- }- h5 = Math.imul(h5 ^ data.length, 0x01000193) >>> 0- return [h1, h2, h3, h4, h5].map((hash) => hash.toString(16).padStart(8, '0')).join('')+ return bytesToHex(sha1(data))}export type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp'diff --git a/packages/scene-graph/src/shaders/model.ts b/packages/scene-graph/src/shaders/model.tsindex e28fbc201..6af7dc8da 100644--- a/packages/scene-graph/src/shaders/model.ts+++ b/packages/scene-graph/src/shaders/model.ts@@ -1,5 +1,7 @@+import { sha1 } from '@noble/hashes/legacy.js'+import { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js'+import { TRANSPARENT } from '../constants'-import { computeImageHash } from '../images'import { readAllPluginData, withAllPluginData } from '../plugin-data/field'import { OPEN_PENCIL_PLUGIN_DATA } from '../plugin-data/fields'import { randomHex } from '../random'@@ -77,7 +79,7 @@ export function createShaderPaint(preset: ShaderPreset): {/** A short key that tells one preset from another, which a rendered frame records. */export function shaderPresetKey(preset: ShaderPreset): string {- return computeImageHash(new TextEncoder().encode(JSON.stringify(preset)))+ return bytesToHex(sha1(utf8ToBytes(JSON.stringify(preset))))}/**diff --git a/packages/scene-graph/tests/images.test.ts b/packages/scene-graph/tests/images.test.tsindex 7bcbdc54b..d2bd441b8 100644--- a/packages/scene-graph/tests/images.test.ts+++ b/packages/scene-graph/tests/images.test.ts@@ -1,6 +1,15 @@import { describe, expect, test } from 'bun:test'-import { imageMimeType } from '@open-pencil/scene-graph'+import { computeImageHash, imageMimeType } from '@open-pencil/scene-graph'++describe('computeImageHash', () => {+ test('names bytes by their SHA-1, as Figma names images', () => {+ expect(computeImageHash(new TextEncoder().encode('abc'))).toBe(+ 'a9993e364706816aba3e25717850c26c9cd0d89d'+ )+ expect(computeImageHash(new Uint8Array())).toBe('da39a3ee5e6b4b0d3255bfef95601890afd80709')+ })+})describe('imageMimeType', () => {test('reads the type from the bytes', () => {diff --git a/src/app/editor/clipboard/figma-images.ts b/src/app/editor/clipboard/figma-images.tsindex a12cc0c6a..17337a7b7 100644--- a/src/app/editor/clipboard/figma-images.ts+++ b/src/app/editor/clipboard/figma-images.ts@@ -1,5 +1,7 @@import * as v from 'valibot'+import { computeImageHash } from '@open-pencil/scene-graph/images'+import { tauriFetch } from '@/app/tauri/http'type ClipboardImageFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>@@ -29,11 +31,6 @@ function imageURLsFromBatchResponse(value: unknown): FigmaImageURLs {)}-async function sha1Hex(bytes: Uint8Array): Promise<string> {- const digest = await crypto.subtle.digest('SHA-1', Uint8Array.from(bytes))- return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('')-}-export async function resolveFigmaClipboardImages(fileKey: string,hashes: string[],@@ -70,7 +67,7 @@ export async function resolveFigmaClipboardImages(const response = await fetcher(url, { signal: AbortSignal.timeout(timeoutMs) })if (!response.ok) throw new Error(`status ${response.status}`)const bytes = new Uint8Array(await response.arrayBuffer())- if ((await sha1Hex(bytes)) !== hash.toLowerCase()) {+ if (computeImageHash(bytes) !== hash.toLowerCase()) {throw new Error('SHA-1 mismatch')}images.set(hash, bytes)diff --git a/tools/AGENTS.md b/tools/AGENTS.mdindex f8ccb6af8..7569c00c9 100644--- a/tools/AGENTS.md+++ b/tools/AGENTS.md@@ -37,7 +37,7 @@ Private tooling lives under `tools/<role>/<domain>/{src,tests}`; Steiger enforce## Demo document-The `/demo` document is a tour of eight chapters on one page, each a section stacked top to bottom, built from `tools/generate/demo/src/document/`: `theme.ts` (the Theme and App chrome collections, each with a Dark and a Light mode that `src/app/demo/theme.ts` switches by name to follow the app's theme; every color in the tour, icons included, is bound to them), `callout.tsx` (the Tip component every chapter instances, whose Where slot each fills with a piece of the app from `chrome.tsx`, drawn to the dark theme's tokens with the target ringed), `player/` (the player card, its artwork slot, and its controls with behaviours), and one file per chapter under `chapters/`, laid out by `chapters/chapter.ts` as numeral, heading, subject, and tip, with each section's and subject's name from `chapters/names.ts`, which hosts outside the app such as the docs landing import from `@open-pencil/demo-tools/chapters`; `src/app/demo/viewport.ts` opens the tour on the first chapter. It renders design JSX through `document/icons.ts`, which serves Lucide from the bundled icon JSON so the build needs no Iconify API, and writes the ignored `public/demo.fig`, which the app opens like any `.fig` file; it is never generated in the browser. `ensureDemoDocument` runs from `vite.config.ts`, rebuilds only when its inputs' fingerprint changes, and runs the build in Bun; `bun run generate:demo` forces it. A chapter that needs something new from the engine adds that package's `src` to the fingerprint in `tools/generate/demo/src/ensure.ts`. Shader fills get their still frames from `src/shaders/stills.ts`, which draws each preset as WebP in the Playwright Chromium with WebGPU (`bunx playwright install chromium` locally; the deploy and preview workflows install it); without the browser the build warns and the editor draws the frames when the demo opens.+The `/demo` document is a tour of eight chapters on one page, each a section stacked top to bottom, built from `tools/generate/demo/src/document/`: `theme.ts` (the Theme and App chrome collections, each with a Dark and a Light mode that `src/app/demo/theme.ts` switches by name to follow the app's theme; every color in the tour, icons included, is bound to them), `callout.tsx` (the Tip component every chapter instances, whose Where slot each fills with a piece of the app from `chrome.tsx`, drawn to the dark theme's tokens with the target ringed), `player/` (the player card, its artwork slot, and its controls with behaviours), and one file per chapter under `chapters/`, laid out by `chapters/chapter.ts` as numeral, heading, subject, and tip, with each section's and subject's name from `chapters/names.ts`, which hosts outside the app such as the docs landing import from `@open-pencil/demo-tools/chapters`; `src/app/demo/viewport.ts` opens the tour on the first chapter. It renders design JSX through `document/icons.ts`, which serves Lucide from the bundled icon JSON so the build needs no Iconify API, and writes the ignored `public/demo.fig`, which the app opens like any `.fig` file; it is never generated in the browser. `ensureDemoDocument` runs from `vite.config.ts`, rebuilds only when its inputs' fingerprint changes, and runs the build in Bun; `bun run generate:demo` forces it. A chapter that needs something new from the engine adds that package's `src` to the fingerprint in `tools/generate/demo/src/ensure.ts`. Shader fills get their still frames from `src/shaders/stills.ts`, which draws each preset in the Playwright Chromium with WebGPU, at the size and in the encoding the editor uses (`shaderFramePixels` and `shaderFrameEncoding` from scene-graph) (`bunx playwright install chromium` locally; the deploy and preview workflows install it); without the browser the build warns and the editor draws the frames when the demo opens.## Brand assets