Skip to content

AI-native design editor. Open-source Figma alternative.

feat: choose how tightly a document's .fig is compressed (#1335)

Danila Poyarkov3fe07843054e
diff --git a/bun.lock b/bun.lock
index 38d87713e..992160f95 100644
--- a/bun.lock
+++ b/bun.lock
@@ -477,6 +477,7 @@
"name": "@open-pencil/kiwi",
"version": "0.16.0",
"dependencies": {
+ "@hpcc-js/wasm-zstd": "^1.16.2",
"fflate": "^0.8.3",
"fzstd": "^0.1.1",
},
@@ -1320,6 +1321,8 @@
"@hono/node-server": ["@hono/[email protected]", "", { "peerDependencies": { "hono": "^4" } }, "sha512-dSneS5qhiauZWGDCeK4o695Xd9nUNjviSZCMQrj10eetr8Uln1ucn6bbphOM6UynAMMtNIzZNSpL9vnASJwrPQ=="],
+ "@hpcc-js/wasm-zstd": ["@hpcc-js/[email protected]", "", {}, "sha512-owm3y0AfdgVfft82RaF4aEPHdk1odK8V1RqryjAhYx3s1oaaHG0gBDC+PJ5P7sFEoayBHSWS5zuXLt9hmOgEvQ=="],
+
"@humanfs/core": ["@humanfs/[email protected]", "", { "dependencies": { "@humanfs/types": "^0.15.0" } }, "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA=="],
"@humanfs/node": ["@humanfs/[email protected]", "", { "dependencies": { "@humanfs/core": "^0.19.2", "@humanfs/types": "^0.15.0", "@humanwhocodes/retry": "^0.4.0" } }, "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ=="],
diff --git a/changes/1335/added.md b/changes/1335/added.md
new file mode 100644
index 000000000..9d69df999
--- /dev/null
+++ b/changes/1335/added.md
@@ -0,0 +1 @@
+- With nothing selected, the Design panel's Document section sets how tightly a document's `.fig` is compressed: Fast, as Figma saves, Smaller, or Smallest. The choice is stored in the file, every save uses it, and Figma opens all three. Saves in the browser and of opened files on desktop now write Zstd instead of deflate, so they come out smaller at every setting.
diff --git a/desktop/AGENTS.md b/desktop/AGENTS.md
index 51c0ee40f..072176764 100644
--- a/desktop/AGENTS.md
+++ b/desktop/AGENTS.md
@@ -13,7 +13,7 @@ Check `desktop/Cargo.toml`, `desktop/capabilities/**`, and `desktop/tauri.conf.j
- `desktop/generated/menu.json` is produced by `bun run generate:tauri-menu` from `src/app/shell/menu/schema.ts`; do not edit or import it directly.
- A menu entry with a `feature` in the schema is built only while the frontend names that feature through `set_native_menu_features` (`src/app/shell/menu/features.ts`); every rebuild keeps the check states the menu had (`desktop/src/menu.rs`).
- Run `bun run generate:icons --target desktop` before direct Cargo checks; native icons are generated, not committed.
-- `build_fig_file` performs `.fig` export on desktop; the browser path uses fflate (`packages/fig/AGENTS.md`).
+- `build_fig_file` performs full `.fig` export on desktop at the level it is given, on a blocking thread, since high levels take seconds; saves that patch an opened archive compress in the web worker (`packages/fig/AGENTS.md`).
- The embedded WebDriver plugin compiles only with the `native-test` Cargo feature and must never be enabled in development or production binaries. Native tests use `bun run test:native` (`tests/AGENTS.md`).
- The editor opens external links through the `open_external_url` command, which allows only `http`, `https`, and `mailto`; native-test builds record them for `take_native_test_opened_urls` instead of launching a browser (`opener` unit tests, `tests/e2e/native/cloud-links.spec.ts`).
- `openpencil://` links are parsed in `desktop/src/deep_link.rs`: `open` queues files through `take_pending_open`, `join` queues validated room IDs through `take_pending_rooms`, `cloud` queues Cloud invitations and shared links (UUID, hex secret, `http(s)` server) through `take_pending_cloud_links`; second launches forward their link arguments through the single-instance handler (`deep_link` unit tests).
diff --git a/desktop/src/fig_container.rs b/desktop/src/fig_container.rs
index b30e7f1f3..ecb23d940 100644
--- a/desktop/src/fig_container.rs
+++ b/desktop/src/fig_container.rs
@@ -7,16 +7,51 @@ pub struct ImageEntry {
data: Vec<u8>,
}
+/// The zstd level Figma itself saves with.
+const DEFAULT_COMPRESSION_LEVEL: i32 = 3;
+
+/// Writes the `.fig` archive on a blocking thread: high zstd levels take seconds on large
+/// documents, which would otherwise stall the window.
#[tauri::command]
-pub fn build_fig_file(
+pub async fn build_fig_file(
+ schema_deflated: Vec<u8>,
+ kiwi_data: Vec<u8>,
+ thumbnail_png: Vec<u8>,
+ meta_json: String,
+ images: Option<Vec<ImageEntry>>,
+ fig_kiwi_version: Option<u32>,
+ compression_level: Option<i32>,
+) -> Result<tauri::ipc::Response, String> {
+ tauri::async_runtime::spawn_blocking(move || {
+ write_fig_file(
+ schema_deflated,
+ kiwi_data,
+ thumbnail_png,
+ meta_json,
+ images,
+ fig_kiwi_version,
+ compression_level,
+ )
+ })
+ .await
+ .map_err(|e| e.to_string())?
+}
+
+fn write_fig_file(
schema_deflated: Vec<u8>,
kiwi_data: Vec<u8>,
thumbnail_png: Vec<u8>,
meta_json: String,
images: Option<Vec<ImageEntry>>,
fig_kiwi_version: Option<u32>,
+ compression_level: Option<i32>,
) -> Result<tauri::ipc::Response, String> {
- let mut encoder = zstd::Encoder::new(Vec::new(), 3).map_err(|e| e.to_string())?;
+ let levels = zstd::compression_level_range();
+ let level = compression_level
+ .unwrap_or(DEFAULT_COMPRESSION_LEVEL)
+ .clamp(*levels.start(), *levels.end());
+ // Figma rejects zstd frames that do not declare their decompressed size.
+ let mut encoder = zstd::Encoder::new(Vec::new(), level).map_err(|e| e.to_string())?;
encoder
.include_contentsize(true)
.map_err(|e| e.to_string())?;
diff --git a/oxlint.json b/oxlint.json
index 4cee0bcfa..1a3bb1fd8 100644
--- a/oxlint.json
+++ b/oxlint.json
@@ -609,6 +609,7 @@
{
"files": [
"packages/core/src/io/formats/fig/export/index.ts",
+ "packages/core/src/io/formats/fig/export/worker.ts",
"packages/core/src/kiwi/fig/parse/worker.ts"
],
"rules": {
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index d9ece2426..66e45948c 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -39,6 +39,7 @@ import { createConnectorDrawActions, createConnectorEndpointActions } from './co
import { createConnectorRouting } from './connectors/routing'
import { createConnectorStyleActions } from './connectors/style'
import { createDesignTokenActions } from './design-tokens'
+import { createFigCompressionActions } from './fig-compression'
import { createGraphEventSubscription } from './graph-events'
import { createGraphReadActions } from './graph-reads'
import { createGuideActions } from './guides'
@@ -303,6 +304,7 @@ export function createEditor(options?: EditorOptions) {
const shapesWithText = createShapeWithTextActions(ctx)
const generatedText = createGeneratedTextActions(ctx)
const statuses = createStatusActions(ctx)
+ const figCompression = createFigCompressionActions(ctx)
createConnectorRouting(ctx)
const connectorDrawing = createConnectorDrawActions(ctx)
const connectorEndpoints = createConnectorEndpointActions(
@@ -517,6 +519,8 @@ export function createEditor(options?: EditorOptions) {
redoAction: () => text.runTextEditStep(undoBridge.redoAction),
setDocumentColorSpace: colorSpace.setDocumentColorSpace,
+ figCompression: figCompression.figCompression,
+ setFigCompression: figCompression.setFigCompression,
// Clipboard — bridge functions that need selectedNodes
...clipboardBridge,
diff --git a/packages/core/src/editor/fig-compression.ts b/packages/core/src/editor/fig-compression.ts
new file mode 100644
index 000000000..b135f5f13
--- /dev/null
+++ b/packages/core/src/editor/fig-compression.ts
@@ -0,0 +1,43 @@
+import {
+ DEFAULT_FIG_COMPRESSION,
+ OPEN_PENCIL_PLUGIN_DATA,
+ withPluginData,
+ type FigCompression
+} from '@open-pencil/scene-graph'
+
+import { figCompressionOf } from '#core/io/formats/fig/compression'
+
+import type { EditorContext } from './types'
+
+/** How tightly the document's `.fig` is compressed, and the command that changes it. */
+export function createFigCompressionActions(ctx: EditorContext) {
+ function figCompression(): FigCompression {
+ return figCompressionOf(ctx.graph)
+ }
+
+ /** Sets the document's compression as one undo step; the default leaves no entry behind. */
+ function setFigCompression(next: FigCompression): void {
+ const previous = figCompression()
+ if (previous === next) return
+ const write = (value: FigCompression) => {
+ const rootId = ctx.graph.rootId
+ const root = ctx.graph.getNode(rootId)
+ if (!root) return
+ ctx.graph.updateNode(rootId, {
+ pluginData: withPluginData(
+ root.pluginData,
+ OPEN_PENCIL_PLUGIN_DATA.figCompression,
+ value === DEFAULT_FIG_COMPRESSION ? undefined : value
+ )
+ })
+ }
+ write(next)
+ ctx.undo.push({
+ label: 'Change compression',
+ forward: () => write(next),
+ inverse: () => write(previous)
+ })
+ }
+
+ return { figCompression, setFigCompression }
+}
diff --git a/packages/core/src/io/formats/fig/compression.ts b/packages/core/src/io/formats/fig/compression.ts
new file mode 100644
index 000000000..974d41105
--- /dev/null
+++ b/packages/core/src/io/formats/fig/compression.ts
@@ -0,0 +1,31 @@
+import {
+ DEFAULT_FIG_COMPRESSION,
+ OPEN_PENCIL_PLUGIN_DATA,
+ readPluginData,
+ type FigCompression,
+ type SceneGraph
+} from '@open-pencil/scene-graph'
+
+/**
+ * The zstd level each preset writes at. Reading costs the same at every level; writing does
+ * not: on a 45 MB document, level 9 takes about 5× and level 19 about 150× level 3's time.
+ */
+export const FIG_COMPRESSION_LEVELS = {
+ fast: 3,
+ smaller: 9,
+ smallest: 19
+} as const satisfies Record<FigCompression, number>
+
+/** The compression the document asks its `.fig` to be written with. */
+export function figCompressionOf(graph: SceneGraph): FigCompression {
+ return (
+ readPluginData(
+ graph.getNode(graph.rootId)?.pluginData,
+ OPEN_PENCIL_PLUGIN_DATA.figCompression
+ ) ?? DEFAULT_FIG_COMPRESSION
+ )
+}
+
+export function figCompressionLevel(graph: SceneGraph): number {
+ return FIG_COMPRESSION_LEVELS[figCompressionOf(graph)]
+}
diff --git a/packages/core/src/io/formats/fig/export/index.ts b/packages/core/src/io/formats/fig/export/index.ts
index d6c350c9e..d14cf03cf 100644
--- a/packages/core/src/io/formats/fig/export/index.ts
+++ b/packages/core/src/io/formats/fig/export/index.ts
@@ -6,12 +6,14 @@ import {
} from '@open-pencil/fig/node-change'
import { initCodec } from '@open-pencil/kiwi/fig/codec'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { loadFigDataCompressor } from '@open-pencil/kiwi/fig/container'
import type { SceneGraph } from '@open-pencil/scene-graph'
import { fractionalPosition } from '@open-pencil/scene-graph/order-keys'
import type { GUID } from '@open-pencil/scene-graph/primitives'
import { withFigExportRuntime } from '#core/canvas/text/shape'
import { IS_BROWSER, IS_TAURI } from '#core/constants'
+import { figCompressionLevel } from '#core/io/formats/fig/compression'
import { sceneNodeToKiwi } from '#core/kiwi/fig/node-change/serialize'
import { cloneSceneGraphForFigExport } from '#core/kiwi/fig/parse/transfer'
import {
@@ -32,6 +34,7 @@ import {
type KiwiNodeChange
} from './setup'
import { appendVariableNodeChanges, sequentialPositions, assignSharedStyleGuids } from './variables'
+import type { CompressResult } from './worker'
type InternalResourceContext = FigExportSetup & { nodeChanges: KiwiNodeChange[] }
@@ -191,6 +194,7 @@ async function writeFigFile(
const extras = await figFileExtras(graph, imageNames, options)
const version = graph.figKiwiVersion ?? undefined
+ const compressionLevel = figCompressionLevel(sourceGraph)
if (IS_TAURI) {
const { invoke } = await import('@tauri-apps/api/core')
@@ -201,7 +205,8 @@ async function writeFigFile(
thumbnailPng: Array.from(extras.thumbnailPNG),
metaJson: extras.metaJSON,
images: extras.images.map((e) => ({ name: e.name, data: Array.from(e.data) })),
- figKiwiVersion: version
+ figKiwiVersion: version,
+ compressionLevel
})
)
}
@@ -212,7 +217,8 @@ async function writeFigFile(
extras.thumbnailPNG,
extras.metaJSON,
extras.images,
- version
+ version,
+ compressionLevel
)
}
@@ -229,15 +235,17 @@ function compressViaWorker(
thumbnailPNG: Uint8Array,
metaJSON: string,
imageEntries: Array<{ name: string; data: Uint8Array }>,
- figKiwiVersion?: number
+ figKiwiVersion?: number,
+ compressionLevel?: number
): Promise<Uint8Array> {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL('./worker.ts', import.meta.url), {
type: 'module'
})
- worker.onmessage = (e: MessageEvent<Uint8Array>) => {
- resolve(e.data)
+ worker.onmessage = (e: MessageEvent<CompressResult>) => {
+ if (e.data instanceof Uint8Array) resolve(e.data)
+ else reject(new Error(e.data.error))
worker.terminate()
}
worker.onerror = (err) => {
@@ -255,18 +263,21 @@ function compressViaWorker(
thumbnailPNG,
metaJSON,
images: imageEntries,
- figKiwiVersion
+ figKiwiVersion,
+ compressionLevel
})
})
}
-export function compressFigData(
+/** Assemble a `.fig` archive with its document data compressed at `compressionLevel` (zstd). */
+export async function compressFigData(
schemaDeflated: Uint8Array,
kiwiData: Uint8Array,
thumbnailPNG: Uint8Array,
metaJSON: string,
imageEntries: Array<{ name: string; data: Uint8Array }>,
- figKiwiVersion?: number
+ figKiwiVersion?: number,
+ compressionLevel?: number
): Promise<Uint8Array> {
if (canUseWorker()) {
return compressViaWorker(
@@ -275,17 +286,17 @@ export function compressFigData(
thumbnailPNG,
metaJSON,
imageEntries,
- figKiwiVersion
+ figKiwiVersion,
+ compressionLevel
)
}
- return Promise.resolve(
- compressFigDataSync(
- schemaDeflated,
- kiwiData,
- thumbnailPNG,
- metaJSON,
- imageEntries,
- figKiwiVersion
- )
+ return compressFigDataSync(
+ schemaDeflated,
+ kiwiData,
+ thumbnailPNG,
+ metaJSON,
+ imageEntries,
+ figKiwiVersion,
+ await loadFigDataCompressor(compressionLevel)
)
}
diff --git a/packages/core/src/io/formats/fig/export/patch/index.ts b/packages/core/src/io/formats/fig/export/patch/index.ts
index df61d061f..fab467cf6 100644
--- a/packages/core/src/io/formats/fig/export/patch/index.ts
+++ b/packages/core/src/io/formats/fig/export/patch/index.ts
@@ -16,6 +16,7 @@ import {
import { siblingOrderKeys } from '@open-pencil/scene-graph/order-keys'
import type { GUID } from '@open-pencil/scene-graph/primitives'
+import { figCompressionLevel } from '#core/io/formats/fig/compression'
import {
figExportRecordOptions,
figFileExtras,
@@ -434,6 +435,7 @@ export async function writePatchedFigFile(
return archive.patch(built.patch, {
thumbnailPNG: extras.thumbnailPNG,
metaJSON: extras.metaJSON,
- images: extras.images.filter((image) => !archivedImages.has(image.name))
+ images: extras.images.filter((image) => !archivedImages.has(image.name)),
+ compressionLevel: figCompressionLevel(source)
})
}
diff --git a/packages/core/src/io/formats/fig/export/worker.ts b/packages/core/src/io/formats/fig/export/worker.ts
index 75812ff54..0cde6f221 100644
--- a/packages/core/src/io/formats/fig/export/worker.ts
+++ b/packages/core/src/io/formats/fig/export/worker.ts
@@ -1,4 +1,5 @@
import { compressFigDataSync } from '@open-pencil/fig'
+import { loadFigDataCompressor } from '@open-pencil/kiwi/fig/container'
interface CompressMessage {
schemaDeflated: Uint8Array
@@ -7,17 +8,26 @@ interface CompressMessage {
metaJSON: string
images: Array<{ name: string; data: Uint8Array }>
figKiwiVersion?: number
+ compressionLevel?: number
}
-self.onmessage = (e: MessageEvent<CompressMessage>) => {
+/** The archive, or why it could not be written: a rejected handler would never reach `onerror`. */
+export type CompressResult = Uint8Array | { error: string }
+
+self.onmessage = async (e: MessageEvent<CompressMessage>) => {
const { schemaDeflated, kiwiData, thumbnailPNG, metaJSON, images, figKiwiVersion } = e.data
- const result = compressFigDataSync(
- schemaDeflated,
- kiwiData,
- thumbnailPNG,
- metaJSON,
- images,
- figKiwiVersion
- )
- self.postMessage(result, { transfer: [result.buffer] })
+ try {
+ const result = compressFigDataSync(
+ schemaDeflated,
+ kiwiData,
+ thumbnailPNG,
+ metaJSON,
+ images,
+ figKiwiVersion,
+ await loadFigDataCompressor(e.data.compressionLevel)
+ )
+ self.postMessage(result, { transfer: [result.buffer] })
+ } catch (error) {
+ self.postMessage({ error: error instanceof Error ? error.message : String(error) })
+ }
}
diff --git a/packages/core/src/kiwi/fig/session/archive/access.ts b/packages/core/src/kiwi/fig/session/archive/access.ts
index 50497a408..a3474c528 100644
--- a/packages/core/src/kiwi/fig/session/archive/access.ts
+++ b/packages/core/src/kiwi/fig/session/archive/access.ts
@@ -5,6 +5,7 @@ import {
type FigPatchedArchiveInput,
type FigRecordPatch
} from '@open-pencil/fig'
+import { loadFigDataCompressor } from '@open-pencil/kiwi/fig/container'
import type { SceneGraph } from '@open-pencil/scene-graph'
import { randomHex } from '@open-pencil/scene-graph/random'
@@ -50,8 +51,8 @@ export function createFigArchiveOperations(bytes: ArrayBuffer, info: () => FigAr
original: () => new Uint8Array(bytes.slice(0)),
info,
componentPages: (componentIds: string[]) => figArchiveComponentUsePages(bytes, componentIds),
- patch: (patch: FigRecordPatch, input: FigPatchedArchiveInput) =>
- patchFigArchive(bytes, patch, input)
+ patch: async (patch: FigRecordPatch, input: FigPatchedArchiveInput) =>
+ patchFigArchive(bytes, patch, input, await loadFigDataCompressor(input.compressionLevel))
}
}
@@ -64,7 +65,7 @@ export function localFigArchive(
original: async () => operations.original(),
info: async () => operations.info(),
componentPages: async (componentIds) => operations.componentPages(componentIds),
- patch: async (patch, input) => operations.patch(patch, input),
+ patch: (patch, input) => operations.patch(patch, input),
close: () => undefined
}
}
diff --git a/packages/core/src/kiwi/fig/session/worker.ts b/packages/core/src/kiwi/fig/session/worker.ts
index 62563ce3d..c1809bbc8 100644
--- a/packages/core/src/kiwi/fig/session/worker.ts
+++ b/packages/core/src/kiwi/fig/session/worker.ts
@@ -41,7 +41,7 @@ type ArchiveRequest = Extract<
{ type: 'original-archive' | 'archive-info' | 'component-pages' | 'patch-archive' }
>
-function answerArchiveRequest(request: ArchiveRequest): void {
+async function answerArchiveRequest(request: ArchiveRequest): Promise<void> {
const { requestId } = request
try {
if (!archive) throw new Error('FIG session has no original archive')
@@ -54,7 +54,7 @@ function answerArchiveRequest(request: ArchiveRequest): void {
const pageIds = archive.componentPages(request.componentIds)
respond({ type: 'component-pages-result', requestId, pageIds })
} else {
- const bytes = archive.patch(request.patch, request.input)
+ const bytes = await archive.patch(request.patch, request.input)
port?.postMessage({ type: 'patch-archive-result', requestId, bytes }, [bytes.buffer])
}
} catch (error) {
@@ -74,7 +74,7 @@ function handleRequest(request: FigSessionRequest): void {
request.type === 'component-pages' ||
request.type === 'patch-archive'
) {
- answerArchiveRequest(request)
+ void answerArchiveRequest(request)
return
}
if (request.type === 'dispose') {
diff --git a/packages/core/tests/editor/fig-compression.test.ts b/packages/core/tests/editor/fig-compression.test.ts
new file mode 100644
index 000000000..53739f851
--- /dev/null
+++ b/packages/core/tests/editor/fig-compression.test.ts
@@ -0,0 +1,31 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import { createEditor, type Editor } from '@open-pencil/core/editor'
+import { hasPluginData, OPEN_PENCIL_PLUGIN_DATA } from '@open-pencil/scene-graph'
+
+let editor: Editor
+
+afterEach(() => editor.dispose())
+
+const rootPluginData = () => editor.graph.getNode(editor.graph.rootId)?.pluginData
+
+describe('file compression in the editor', () => {
+ test('changes the document compression as one undo step', () => {
+ editor = createEditor()
+ expect(editor.figCompression()).toBe('fast')
+ editor.setFigCompression('smallest')
+ expect(editor.figCompression()).toBe('smallest')
+ editor.undo.undo()
+ expect(editor.figCompression()).toBe('fast')
+ editor.undo.redo()
+ expect(editor.figCompression()).toBe('smallest')
+ })
+
+ test('the default leaves no entry on the document', () => {
+ editor = createEditor()
+ editor.setFigCompression('smaller')
+ expect(hasPluginData(rootPluginData(), OPEN_PENCIL_PLUGIN_DATA.figCompression)).toBe(true)
+ editor.setFigCompression('fast')
+ expect(hasPluginData(rootPluginData(), OPEN_PENCIL_PLUGIN_DATA.figCompression)).toBe(false)
+ })
+})
diff --git a/packages/core/tests/io/formats/fig/compression.test.ts b/packages/core/tests/io/formats/fig/compression.test.ts
new file mode 100644
index 000000000..10396acdd
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/compression.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, setDefaultTimeout, test } from 'bun:test'
+
+import { unzipSync } from 'fflate'
+
+import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
+import { parseFigKiwiChunks } from '@open-pencil/kiwi/fig/container'
+import {
+ OPEN_PENCIL_PLUGIN_DATA,
+ withPluginData,
+ type FigCompression
+} from '@open-pencil/scene-graph'
+
+import { figCompressionOf } from '#core/io/formats/fig/compression'
+import { hasPendingReaderPages } from '#core/kiwi/fig/session/document-state'
+
+setDefaultTimeout(60_000)
+
+/** A document with enough layers for compression levels to differ. */
+function sampleDocument(): SceneGraph {
+ const graph = new SceneGraph()
+ const [page] = graph.getPages()
+ for (let index = 0; index < 400; index++) {
+ graph.createNode('RECTANGLE', page.id, {
+ name: `Layer ${index % 37}`,
+ x: (index * 13) % 900,
+ y: (index * 29) % 700,
+ width: 10 + (index % 11),
+ height: 10 + (index % 7)
+ })
+ }
+ graph.addPage('Second')
+ return graph
+}
+
+function setCompression(graph: SceneGraph, compression: FigCompression) {
+ const root = graph.getNode(graph.rootId)
+ if (!root) throw new Error('Missing document node')
+ graph.updateNode(graph.rootId, {
+ pluginData: withPluginData(root.pluginData, OPEN_PENCIL_PLUGIN_DATA.figCompression, compression)
+ })
+}
+
+/** The compressed document data inside a `.fig` archive. */
+function dataChunk(bytes: Uint8Array): Uint8Array {
+ const chunk = parseFigKiwiChunks(unzipSync(bytes)['canvas.fig'])?.[1]
+ if (!chunk) throw new Error('Missing document data')
+ return chunk
+}
+
+const open = (bytes: Uint8Array, populate: 'all' | 'first-page' = 'all') =>
+ parseFigFile(bytes.slice().buffer as ArrayBuffer, { populate })
+
+describe('.fig compression', () => {
+ test('a new document is written at its compression and keeps it', async () => {
+ await initCodec()
+ const fast = sampleDocument()
+ const smallest = sampleDocument()
+ setCompression(smallest, 'smallest')
+ const fastBytes = await exportFigFile(fast)
+ const smallestBytes = await exportFigFile(smallest)
+ expect(dataChunk(smallestBytes).length).toBeLessThan(dataChunk(fastBytes).length)
+ expect(figCompressionOf(await open(smallestBytes))).toBe('smallest')
+ })
+
+ test('an opened document is patched at the compression it was changed to', async () => {
+ await initCodec()
+ const original = await exportFigFile(sampleDocument())
+ const fast = await open(original, 'first-page')
+ const smallest = await open(original, 'first-page')
+ setCompression(smallest, 'smallest')
+ fast.createNode('RECTANGLE', fast.getPages()[0].id, { name: 'Edit' })
+ const fastBytes = await exportFigFile(fast)
+ const smallestBytes = await exportFigFile(smallest)
+ // Saved over the archive they were opened from: the pages never opened are still pending.
+ expect(hasPendingReaderPages(fast)).toBe(true)
+ expect(hasPendingReaderPages(smallest)).toBe(true)
+ expect(dataChunk(smallestBytes).length).toBeLessThan(dataChunk(fastBytes).length)
+ expect(figCompressionOf(await open(smallestBytes))).toBe('smallest')
+ })
+})
diff --git a/packages/docs/reference/file-format.md b/packages/docs/reference/file-format.md
index f61734d58..bbe33fc0e 100644
--- a/packages/docs/reference/file-format.md
+++ b/packages/docs/reference/file-format.md
@@ -36,14 +36,14 @@ A `.fig` file is a ZIP archive containing a Kiwi-encoded binary message:
## Export Pipeline
```
-SceneGraph → NodeChange[] → Kiwi encode → compress (Zstd/deflate)
+SceneGraph → NodeChange[] → Kiwi encode → compress (Zstd)
→ build ZIP (header + schema + message + thumbnail.png)
→ write .fig file
```
Export uses <kbd>⌘</kbd><kbd>S</kbd> (Save) and <kbd>⇧</kbd><kbd>⌘</kbd><kbd>S</kbd> (Save As) with native OS dialogs on the desktop app. The exported file includes a `thumbnail.png` required by Figma for file preview. OpenPencil uses the first page named exactly `Cover` (case-insensitive), then the first page whose name contains `Cover`. The desktop app also caches this Cover after opening a file so Recent Files can prefer the generated preview without modifying the source `.fig`.
-Compression uses Zstd via Tauri Rust command on desktop, with deflate fallback in the browser.
+Compression uses Zstd at the level the document asks for (see [Compression](#compression)): through a Tauri Rust command on desktop, Bun's own Zstd in the CLI, and a WebAssembly build in the browser.
## Kiwi Binary Codec
@@ -62,7 +62,9 @@ Figma's schema uses non-contiguous field IDs (e.g. 1, 2, 5, 10 with gaps). The k
### Compression
-`.fig` files use Zstd compression for both the schema and message payloads. Decompression uses the `fzstd` library. For export, Zstd compression is offloaded to a Tauri Rust command on the desktop app (better performance, correct frame headers). In the browser, deflate via `fflate` is used as a fallback.
+The schema chunk is deflated and the message chunk is Zstd-compressed; Figma also reads a deflated message chunk, as older files have. Decompression uses the `fzstd` library.
+
+Export writes the message chunk with Zstd at a level set per document, stored as `figCompression` in the document node's `open-pencil` plugin data: `fast` (level 3, as Figma saves), `smaller` (9), or `smallest` (19). Figma opens every Zstd level, but only frames that declare their decompressed size, which all three encoders write. Reading costs the same at every level; on a 45 MB message, level 9 takes about five times and level 19 about 150 times as long to write as level 3.
## Supported Formats
diff --git a/packages/docs/user-guide/exporting.md b/packages/docs/user-guide/exporting.md
index b504c6592..adf2c2d3c 100644
--- a/packages/docs/user-guide/exporting.md
+++ b/packages/docs/user-guide/exporting.md
@@ -70,6 +70,8 @@ You can also drag a `.fig`, `.pen`, or other supported document onto the window;
Saved files are compressed and include a thumbnail image for preview in file browsers.
+With nothing selected, the **Document** section of the Design panel sets how tightly the document is compressed. **Fast** matches Figma's own saves. **Smaller** and **Smallest** make the file smaller and take longer to save, which is most noticeable on large documents and least on files made mostly of images. The choice is stored in the file, and Figma opens all three.
+
### Round-trip Compatibility
Files exported from OpenPencil can be opened in Figma, and vice versa. The .fig format preserves all node types, properties, fills, strokes, effects, vector data, and layout settings.
diff --git a/packages/fig/AGENTS.md b/packages/fig/AGENTS.md
index 1068bf3bc..d42059e40 100644
--- a/packages/fig/AGENTS.md
+++ b/packages/fig/AGENTS.md
@@ -6,7 +6,7 @@
- Figma clipboard envelope encoding, decoding, and bounds belong to `@open-pencil/fig/clipboard`; converting those records to a SceneGraph is `materializeFigFragment` in `packages/fig/src/document/fragment.ts`, which Core drives from `packages/core/src/clipboard/fig-import.ts`. Core prepares runtime fonts and text and owns editor placement and history; browser and Tauri adapters own system clipboard I/O. Do not add platform clipboard APIs here.
- One reader serves every `.fig` path — parse, worker, page population, session recovery, export, and paste — through the document sessions in `packages/fig/src/document/`. Read what it could not resolve with `readerDiagnostics(graph)` from `packages/core/src/kiwi/fig/session/document-state.ts`; do not add a second import path.
- A generated frame's `.fig` record carries its sublayers as `nodeGenerationData` and their derived geometry. Each generated type registers a `GeneratedFrameCodec` that reads and writes them in `packages/fig/src/node-change/generated/codecs.ts`; the import and export dispatch through it and never test node types (`packages/fig/tests/node-change/generated/codecs.test.ts`).
-- Browser `.fig` export uses fflate and `@open-pencil/fig`; Tauri uses `build_fig_file` in `desktop/`.
+- `.fig` document data is written with Zstd at the document's `figCompression` level: `build_fig_file` in `desktop/` on Tauri, `loadFigDataCompressor` from `@open-pencil/kiwi/fig/container` elsewhere, which is Bun's Zstd or a WebAssembly build. Figma rejects a Zstd frame that does not declare its decompressed size, so every encoder must write it (`packages/kiwi/tests/container.test.ts`).
- Saving a document opened from a `.fig` writes only the fields its edits changed, merged into the archive's records, and copies the rest as bytes (`packages/core/src/io/formats/fig/export/patch/`, `patchFigMessage` in `packages/fig/src/record-patch/`); the full export remains for documents with no archive. A change is what the archive tracker sees outside page loads and outside `applyDerivedLayoutDuring`, which wraps layout derived from the file or its fonts; layout an edit causes counts, and the tracker keeps each edited layer as it was so the fields are found by comparing records (`packages/core/tests/io/formats/fig/export/patch/`).
- Changes to `.fig` behavior require round-trip validation in Figma. `packages/docs/development/roadmap.md` tracks raw metadata coverage and the code map for import/export mapping and schema files.
- Measure a reader change over a whole archive, not one frame: capture before and after with `visual-oracles compare digest --file F --out baseline.json` then `--baseline baseline.json`, and account for every node it reports. `compare interpreted-document` checks one frame against live Figma and will report no change while a rule breaks pages it does not cover.
diff --git a/packages/fig/src/archive.ts b/packages/fig/src/archive.ts
index dfcdf790b..6751ad3f3 100644
--- a/packages/fig/src/archive.ts
+++ b/packages/fig/src/archive.ts
@@ -3,7 +3,11 @@ import * as v from 'valibot'
import type { FigPageManifestEntry } from '@open-pencil/kiwi/fig'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
-import { buildFigKiwi, parseFigKiwiChunks } from '@open-pencil/kiwi/fig/container'
+import {
+ buildFigKiwi,
+ parseFigKiwiChunks,
+ type FigDataCompressor
+} from '@open-pencil/kiwi/fig/container'
import { decodeFigKiwiCanvas, parseFigKiwiContainer } from '@open-pencil/kiwi/fig/parse'
import type { HeaderFields } from '@open-pencil/kiwi/schema-runtime'
import type { Color, Rect, Size } from '@open-pencil/scene-graph/primitives'
@@ -22,6 +26,8 @@ export interface WriteFigArchiveInput {
metaJSON: string
images?: FigImageEntry[]
figKiwiVersion?: number
+ /** Compresses the document data; Bun's zstd or deflate when omitted. */
+ compress?: FigDataCompressor
}
export interface FigParseResult {
@@ -258,7 +264,12 @@ export function renameFigArchive(bytes: Uint8Array, fileName: string): Uint8Arra
/** Assemble a complete zipped `.fig` archive from an encoded Kiwi message and resources. */
export function writeFigArchive(input: WriteFigArchiveInput): Uint8Array {
- const canvasData = buildFigKiwi(input.schemaDeflated, input.kiwiData, input.figKiwiVersion)
+ const canvasData = buildFigKiwi(
+ input.schemaDeflated,
+ input.kiwiData,
+ input.figKiwiVersion,
+ input.compress
+ )
const entries: Zippable = {
'canvas.fig': [canvasData, { level: 0 }],
'thumbnail.png': [input.thumbnailPNG, { level: 0 }],
@@ -275,7 +286,8 @@ export function compressFigDataSync(
thumbnailPNG: Uint8Array,
metaJSON: string,
imageEntries: FigImageEntry[],
- figKiwiVersion?: number
+ figKiwiVersion?: number,
+ compress?: FigDataCompressor
): Uint8Array {
return writeFigArchive({
schemaDeflated,
@@ -283,6 +295,7 @@ export function compressFigDataSync(
thumbnailPNG,
metaJSON,
images: imageEntries,
- figKiwiVersion
+ figKiwiVersion,
+ compress
})
}
diff --git a/packages/fig/src/record-patch/index.ts b/packages/fig/src/record-patch/index.ts
index dbad3d6b9..de6f99f33 100644
--- a/packages/fig/src/record-patch/index.ts
+++ b/packages/fig/src/record-patch/index.ts
@@ -1,6 +1,7 @@
import { inflateSync } from 'fflate'
import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
+import type { FigDataCompressor } from '@open-pencil/kiwi/fig/container'
import { guidToString } from '@open-pencil/kiwi/fig/guid'
import {
ByteBuffer,
@@ -56,6 +57,8 @@ export interface FigPatchedArchiveInput {
metaJSON: string
/** Images the archive does not hold yet. */
images: FigImageEntry[]
+ /** The zstd level the document data is written at; the archive is read whatever it used. */
+ compressionLevel?: number
}
const VARIABLE_TYPES = new Set(['VARIABLE', 'VARIABLE_SET'])
@@ -478,7 +481,8 @@ export function patchFigMessage(
export function patchFigArchive(
bytes: ArrayBuffer,
patch: FigRecordPatch,
- input: FigPatchedArchiveInput
+ input: FigPatchedArchiveInput,
+ compress?: FigDataCompressor
): Uint8Array {
const parts = readFigArchiveParts(bytes)
const kiwiData = patchFigMessage(parts.schemaDeflated, parts.dataRaw, patch)
@@ -492,7 +496,8 @@ export function patchFigArchive(
...parts.images.map(([name, data]) => ({ name: `images/${name}`, data })),
...input.images.filter((image) => !archiveImages.has(image.name.replace(/^images\//, '')))
],
- figKiwiVersion: parts.figKiwiVersion
+ figKiwiVersion: parts.figKiwiVersion,
+ compress
})
}
diff --git a/packages/kiwi/package.json b/packages/kiwi/package.json
index c23af4c77..44c9f5f54 100644
--- a/packages/kiwi/package.json
+++ b/packages/kiwi/package.json
@@ -74,6 +74,7 @@
"typecheck": "bunx tsc --noEmit -p tsconfig.test.json"
},
"dependencies": {
+ "@hpcc-js/wasm-zstd": "^1.16.2",
"fflate": "^0.8.3",
"fzstd": "^0.1.1"
},
diff --git a/packages/kiwi/src/fig/container.ts b/packages/kiwi/src/fig/container.ts
index a299f4656..4d6dec4f3 100644
--- a/packages/kiwi/src/fig/container.ts
+++ b/packages/kiwi/src/fig/container.ts
@@ -5,6 +5,58 @@ import { isZstdCompressed } from './protocol'
export const FIG_KIWI_DEFAULT_VERSION = 101
+/** Compresses a fig-kiwi data chunk. */
+export type FigDataCompressor = (data: Uint8Array) => Uint8Array
+
+/** The zstd level Figma itself saves with. */
+export const FIG_ZSTD_DEFAULT_LEVEL = 3
+
+type BunZstdCompress = (data: Uint8Array, options?: { level?: number }) => Uint8Array
+
+function bunZstdCompress(): BunZstdCompress | undefined {
+ const g = globalThis as { Bun?: { zstdCompressSync?: BunZstdCompress } }
+ return g.Bun?.zstdCompressSync
+}
+
+/**
+ * Bun's zstd at its default level, or deflate where zstd needs loading first. Figma reads both,
+ * so writers that cannot wait, such as the clipboard, use this one.
+ */
+export const defaultFigDataCompressor: FigDataCompressor = (data) =>
+ bunZstdCompress()?.(data) ?? deflateSync(data)
+
+let wasmZstd: Promise<(data: Uint8Array, level: number) => Uint8Array> | undefined
+
+/** The WebAssembly zstd encoder, loaded once; a failed load is retried on the next call. */
+export async function loadWasmFigDataCompressor(
+ level = FIG_ZSTD_DEFAULT_LEVEL
+): Promise<FigDataCompressor> {
+ wasmZstd ??= import('@hpcc-js/wasm-zstd')
+ .then(({ Zstd }) => Zstd.load())
+ .then(
+ (zstd) => (data: Uint8Array, compressionLevel: number) =>
+ zstd.compress(data, compressionLevel)
+ )
+ .catch((error: unknown) => {
+ wasmZstd = undefined
+ throw error
+ })
+ const compress = await wasmZstd
+ return (data) => compress(data, level)
+}
+
+/**
+ * A zstd compressor at `level`: Bun's own where it runs, the WebAssembly build elsewhere. Figma
+ * opens every level, but only frames that declare their decompressed size, which both write.
+ */
+export async function loadFigDataCompressor(
+ level = FIG_ZSTD_DEFAULT_LEVEL
+): Promise<FigDataCompressor> {
+ const native = bunZstdCompress()
+ if (native) return (data) => native(data, { level })
+ return loadWasmFigDataCompressor(level)
+}
+
function bunZstdDecompressSync(data: Uint8Array): Uint8Array | undefined {
const g = globalThis as { Bun?: { zstdDecompressSync?: (data: Uint8Array) => Uint8Array } }
return g.Bun?.zstdDecompressSync?.(data)
@@ -57,18 +109,10 @@ export async function decompressFigKiwiDataAsync(compressed: Uint8Array): Promis
export function buildFigKiwi(
schemaDeflated: Uint8Array,
dataRaw: Uint8Array,
- version = FIG_KIWI_DEFAULT_VERSION
+ version = FIG_KIWI_DEFAULT_VERSION,
+ compress: FigDataCompressor = defaultFigDataCompressor
): Uint8Array {
- let dataCompressed: Uint8Array
- const zstdCompress: ((data: Uint8Array) => Uint8Array) | undefined = (() => {
- const g = globalThis as { Bun?: { zstdCompressSync?: (data: Uint8Array) => Uint8Array } }
- return g.Bun?.zstdCompressSync
- })()
- if (zstdCompress) {
- dataCompressed = zstdCompress(dataRaw)
- } else {
- dataCompressed = deflateSync(dataRaw)
- }
+ const dataCompressed = compress(dataRaw)
const total = 8 + 4 + 4 + schemaDeflated.length + 4 + dataCompressed.length
const out = new Uint8Array(total)
diff --git a/packages/kiwi/tests/container.test.ts b/packages/kiwi/tests/container.test.ts
index bfd21c2f9..c6933559b 100644
--- a/packages/kiwi/tests/container.test.ts
+++ b/packages/kiwi/tests/container.test.ts
@@ -7,8 +7,30 @@ import {
decompressFigKiwiData,
decompressFigKiwiDataAsync,
FIG_KIWI_DEFAULT_VERSION,
- parseFigKiwiChunks
+ loadFigDataCompressor,
+ loadWasmFigDataCompressor,
+ parseFigKiwiChunks,
+ type FigDataCompressor
} from '../src/fig/container'
+import { isZstdCompressed } from '../src/fig/protocol'
+
+/** Text that compresses better the harder zstd works, generated the same way every run. */
+function sampleDocument(): Uint8Array {
+ let seed = 1
+ const next = () => (seed = (seed * 1103515245 + 12345) % 2 ** 31)
+ const records = Array.from(
+ { length: 4000 },
+ () => `{"name":"Layer ${next() % 500}","x":${next() % 2000},"fills":[${next() % 7}]}`
+ )
+ return new TextEncoder().encode(records.join('\n'))
+}
+
+/** Whether a zstd frame header records the decompressed size, which Figma requires. */
+function declaresContentSize(frame: Uint8Array): boolean {
+ const descriptor = frame[4]
+ const singleSegment = (descriptor >> 5) & 1
+ return singleSegment === 1 || descriptor >> 6 !== 0
+}
describe('Figma FIG Kiwi container helpers', () => {
test('builds and parses fig-kiwi chunks', async () => {
@@ -45,6 +67,35 @@ describe('Figma FIG Kiwi container helpers', () => {
await expect(decompressFigKiwiDataAsync(deflated)).resolves.toEqual(dataRaw)
})
+ // Bun's own zstd where it runs, and the WebAssembly build browsers and webviews save with.
+ for (const [encoder, load] of [
+ ['native', loadFigDataCompressor],
+ ['WebAssembly', loadWasmFigDataCompressor]
+ ] as const satisfies ReadonlyArray<
+ readonly [string, (level: number) => Promise<FigDataCompressor>]
+ >) {
+ test(`${encoder} zstd compresses at the requested level into frames Figma opens`, async () => {
+ const dataRaw = sampleDocument()
+ const sizes: number[] = []
+ for (const level of [3, 9, 19]) {
+ const compress = await load(level)
+ const binary = buildFigKiwi(
+ new Uint8Array([1]),
+ dataRaw,
+ FIG_KIWI_DEFAULT_VERSION,
+ compress
+ )
+ const dataChunk = parseFigKiwiChunks(binary)?.[1] ?? new Uint8Array()
+ expect(isZstdCompressed(dataChunk)).toBe(true)
+ expect(declaresContentSize(dataChunk)).toBe(true)
+ expect(decompressFigKiwiData(dataChunk)).toEqual(dataRaw)
+ sizes.push(dataChunk.length)
+ }
+ expect(sizes[1]).toBeLessThan(sizes[0])
+ expect(sizes[2]).toBeLessThan(sizes[1])
+ })
+ }
+
test('rejects non fig-kiwi data', () => {
expect(parseFigKiwiChunks(new TextEncoder().encode('not-fig-kiwi'))).toBeNull()
})
diff --git a/packages/scene-graph/src/fig-compression.ts b/packages/scene-graph/src/fig-compression.ts
new file mode 100644
index 000000000..8346732d3
--- /dev/null
+++ b/packages/scene-graph/src/fig-compression.ts
@@ -0,0 +1,9 @@
+/**
+ * How tightly a document's `.fig` data is compressed when it is written: `fast` matches Figma's
+ * own saves, `smaller` and `smallest` trade save time for size. Figma opens all three.
+ */
+export const FIG_COMPRESSIONS = ['fast', 'smaller', 'smallest'] as const
+
+export type FigCompression = (typeof FIG_COMPRESSIONS)[number]
+
+export const DEFAULT_FIG_COMPRESSION: FigCompression = 'fast'
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index 98b609880..4fefd31c7 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -93,6 +93,7 @@ export {
export * from './snap'
export * from './export-format'
export * from './export-scale'
+export * from './fig-compression'
export * from './coordinate'
export * from './layout'
export * from './text'
diff --git a/packages/scene-graph/src/plugin-data/fields.ts b/packages/scene-graph/src/plugin-data/fields.ts
index f32801f56..b7f4c6c50 100644
--- a/packages/scene-graph/src/plugin-data/fields.ts
+++ b/packages/scene-graph/src/plugin-data/fields.ts
@@ -4,6 +4,7 @@ import { behaviourSchema } from '../behaviours/schema'
import type { OkHCLPayload } from '../color/okhcl'
import { isExportFormatId, type ExportFormatId } from '../export-format'
import { clampExportScale } from '../export-scale'
+import { FIG_COMPRESSIONS } from '../fig-compression'
import { iconSchema, iconTintSchema } from '../icons/schema'
import type { Rect } from '../primitives'
import { shaderPaintSchema } from '../shaders/schema'
@@ -214,6 +215,8 @@ export const OPEN_PENCIL_PLUGIN_DATA = {
comments: jsonPluginDataField('comments', 'bookkeeping', comments),
/** The statuses layers can be in, on the DOCUMENT node. */
statuses: jsonPluginDataField('statuses', 'bookkeeping', statusWorkflowSchema),
+ /** How tightly the document's `.fig` data is compressed, on the DOCUMENT node. */
+ figCompression: textPluginDataField('figCompression', 'bookkeeping', FIG_COMPRESSIONS),
/** A layer's status, any state of the workflow; Figma's `sectionStatusInfo` knows only two. */
status: jsonPluginDataField('status', 'format', nodeStatusSchema),
/** Unit and CSS expressions, on each VARIABLE. */
diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.json
index d627ce5d7..021bcb692 100644
--- a/packages/vue/src/i18n/locales/de/panels.json
+++ b/packages/vue/src/i18n/locales/de/panels.json
@@ -460,6 +460,11 @@
"maskTypeAlpha": "Alpha",
"maskTypeVector": "Vektor",
"maskTypeLuminance": "Luminanz",
+ "document": "Dokument",
+ "compression": "Komprimierung",
+ "compressionFast": "Schnell",
+ "compressionSmaller": "Kleiner",
+ "compressionSmallest": "Am kleinsten",
"sticky": "Haftnotiz",
"stickyColor": "Farbe",
"stickyColorWhite": "Weiß",
diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.json
index 490ab0557..a028a7216 100644
--- a/packages/vue/src/i18n/locales/es/panels.json
+++ b/packages/vue/src/i18n/locales/es/panels.json
@@ -460,6 +460,11 @@
"maskTypeAlpha": "Alfa",
"maskTypeVector": "Vectorial",
"maskTypeLuminance": "Luminancia",
+ "document": "Documento",
+ "compression": "Compresión",
+ "compressionFast": "Rápida",
+ "compressionSmaller": "Menor",
+ "compressionSmallest": "Mínima",
"sticky": "Nota adhesiva",
"stickyColor": "Color",
"stickyColorWhite": "Blanco",
diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.json
index eff6310c5..f9f205463 100644
--- a/packages/vue/src/i18n/locales/fr/panels.json
+++ b/packages/vue/src/i18n/locales/fr/panels.json
@@ -460,6 +460,11 @@
"maskTypeAlpha": "Alpha",
"maskTypeVector": "Vectoriel",
"maskTypeLuminance": "Luminance",
+ "document": "Document",
+ "compression": "Compression",
+ "compressionFast": "Rapide",
+ "compressionSmaller": "Réduite",
+ "compressionSmallest": "Minimale",
"sticky": "Note autocollante",
"stickyColor": "Couleur",
"stickyColorWhite": "Blanc",
diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.json
index cb5e85b35..cbf693101 100644
--- a/packages/vue/src/i18n/locales/it/panels.json
+++ b/packages/vue/src/i18n/locales/it/panels.json
@@ -460,6 +460,11 @@
"maskTypeAlpha": "Alfa",
"maskTypeVector": "Vettore",
"maskTypeLuminance": "Luminanza",
+ "document": "Documento",
+ "compression": "Compressione",
+ "compressionFast": "Veloce",
+ "compressionSmaller": "Ridotta",
+ "compressionSmallest": "Minima",
"sticky": "Nota adesiva",
"stickyColor": "Colore",
"stickyColorWhite": "Bianco",
diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.json
index 099810aff..e21cf8b93 100644
--- a/packages/vue/src/i18n/locales/ja/panels.json
+++ b/packages/vue/src/i18n/locales/ja/panels.json
@@ -454,6 +454,11 @@
"maskTypeAlpha": "アルファ",
"maskTypeVector": "ベクター",
"maskTypeLuminance": "輝度",
+ "document": "ドキュメント",
+ "compression": "圧縮",
+ "compressionFast": "高速",
+ "compressionSmaller": "小さめ",
+ "compressionSmallest": "最小",
"sticky": "付箋",
"stickyColor": "色",
"stickyColorWhite": "白",
diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.json
index ebda5ba1b..8d2dfb0f5 100644
--- a/packages/vue/src/i18n/locales/pl/panels.json
+++ b/packages/vue/src/i18n/locales/pl/panels.json
@@ -466,6 +466,11 @@
"maskTypeAlpha": "Alfa",
"maskTypeVector": "Wektorowa",
"maskTypeLuminance": "Luminancja",
+ "document": "Dokument",
+ "compression": "Kompresja",
+ "compressionFast": "Szybka",
+ "compressionSmaller": "Mniejszy plik",
+ "compressionSmallest": "Najmniejszy plik",
"sticky": "Karteczka",
"stickyColor": "Kolor",
"stickyColorWhite": "Biały",
diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.json
index 0eafdb71c..59761637f 100644
--- a/packages/vue/src/i18n/locales/ru/panels.json
+++ b/packages/vue/src/i18n/locales/ru/panels.json
@@ -466,6 +466,11 @@
"maskTypeAlpha": "Альфа-канал",
"maskTypeVector": "Вектор",
"maskTypeLuminance": "Яркость",
+ "document": "Документ",
+ "compression": "Сжатие",
+ "compressionFast": "Быстрое",
+ "compressionSmaller": "Компактнее",
+ "compressionSmallest": "Максимальное",
"sticky": "Стикер",
"stickyColor": "Цвет",
"stickyColorWhite": "Белый",
diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.json
index b6cb5b4d7..8e75646f6 100644
--- a/packages/vue/src/i18n/locales/zh-cn/panels.json
+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json
@@ -454,6 +454,11 @@
"maskTypeAlpha": "Alpha",
"maskTypeVector": "矢量",
"maskTypeLuminance": "亮度",
+ "document": "文档",
+ "compression": "压缩",
+ "compressionFast": "快速",
+ "compressionSmaller": "较小",
+ "compressionSmallest": "最小",
"sticky": "便利贴",
"stickyColor": "颜色",
"stickyColorWhite": "白色",
diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.ts
index 37ee0d0ab..0cd4d0b5e 100644
--- a/packages/vue/src/i18n/messages/panels.ts
+++ b/packages/vue/src/i18n/messages/panels.ts
@@ -369,6 +369,11 @@ export const panelMessageDefaults = {
maskTypeAlpha: 'Alpha',
maskTypeVector: 'Vector',
maskTypeLuminance: 'Luminance',
+ document: 'Document',
+ compression: 'Compression',
+ compressionFast: 'Fast',
+ compressionSmaller: 'Smaller',
+ compressionSmallest: 'Smallest',
sticky: 'Sticky note',
stickyColor: 'Color',
diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vue
index cb27c13a6..4b258f1be 100644
--- a/src/components/DesignPanel.vue
+++ b/src/components/DesignPanel.vue
@@ -25,6 +25,7 @@ import { usePropertyBinding } from './properties/component-properties/usePropert
import VariantAuthoringSection from './properties/component-properties/variant/VariantAuthoringSection.vue'
import ConnectorSection from './properties/connector/ConnectorSection.vue'
import ConstraintsSection from './properties/constraints/ConstraintsSection.vue'
+import DocumentSection from './properties/DocumentSection.vue'
import EffectsSection from './properties/EffectsSection.vue'
import ExportSection from './properties/ExportSection.vue'
import FillSection from './properties/FillSection.vue'
@@ -254,6 +255,7 @@ const { panels } = useI18n()
<PageSection />
<VariablesSection @open-dialog="openVariablesDialog(store)" />
<StatusesSection />
+ <DocumentSection />
<ExportSection />
</div>
</template>
diff --git a/src/components/properties/DocumentSection.vue b/src/components/properties/DocumentSection.vue
new file mode 100644
index 000000000..7f0aec271
--- /dev/null
+++ b/src/components/properties/DocumentSection.vue
@@ -0,0 +1,40 @@
+<script setup lang="ts">
+import { computed } from 'vue'
+
+import type { FigCompression } from '@open-pencil/scene-graph'
+import { useI18n, useSceneComputed } from '@open-pencil/vue'
+
+import { useEditorStore } from '@/app/editor/active-store'
+import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'
+import PanelSection from '@/components/ui/panel/PanelSection.vue'
+import AppSelect from '@/components/ui/select/AppSelect.vue'
+
+/** Settings for the whole document, shown with nothing selected. */
+const store = useEditorStore()
+const { panels } = useI18n()
+const current = useSceneComputed(() => store.figCompression())
+
+const compressionOptions = computed<Array<{ value: FigCompression; label: string }>>(() => [
+ { value: 'fast', label: panels.value.compressionFast },
+ { value: 'smaller', label: panels.value.compressionSmaller },
+ { value: 'smallest', label: panels.value.compressionSmallest }
+])
+
+const compression = computed<FigCompression>({
+ get: () => current.value,
+ set: (value) => store.setFigCompression(value)
+})
+</script>
+
+<template>
+ <PanelSection :label="panels.document" data-test-id="document-section">
+ <PanelFieldGroup :label="panels.compression">
+ <AppSelect
+ v-model="compression"
+ :label="panels.compression"
+ :options="compressionOptions"
+ data-property="fig-compression"
+ />
+ </PanelFieldGroup>
+ </PanelSection>
+</template>
diff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txt
index 98ef2dd5e..2187b4570 100644
--- a/tools/checks/i18n/translation-baseline.txt
+++ b/tools/checks/i18n/translation-baseline.txt
@@ -150,10 +150,12 @@ fr:panels.colorFormatHsb
fr:panels.colorFormatHsl
fr:panels.colorFormatOkhcl
fr:panels.colorFormatRgb
+fr:panels.compression
fr:panels.description
fr:panels.design
fr:panels.dimensions
fr:panels.direction
+fr:panels.document
fr:panels.documentation
fr:panels.export
fr:panels.framePresetCategoryFigmaCommunity