Skip to content

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

feat(figma-api): add exportAsync and Figma's exportSettings (#1694)

Danila Poyarkov83459901c4d0
diff --git a/changes/1694/added.md b/changes/1694/added.md
new file mode 100644
index 000000000..c5e2b844f
--- /dev/null
+++ b/changes/1694/added.md
@@ -0,0 +1 @@
+- Scripts can export layers and pages with Figma's `node.exportAsync()` as PNG, JPG, SVG, or PDF, and read and set `node.exportSettings` with Figma's options, which `.fig` files keep.
diff --git a/packages/cli/src/commands/eval.ts b/packages/cli/src/commands/eval.ts
index 4be512541..27da4a1a7 100644
--- a/packages/cli/src/commands/eval.ts
+++ b/packages/cli/src/commands/eval.ts
@@ -74,6 +74,11 @@ export default defineCommand({
populateWholeDocument(graph)
await measureDocumentText(graph)
const figma = new FigmaAPI(graph)
+ // CanvasKit starts only when a script exports an image.
+ figma.exportImage = async (nodeIds, options) => {
+ const { headlessRenderNodes } = await import('@open-pencil/core/io/formats/raster')
+ return headlessRenderNodes(graph, options.pageId ?? figma.currentPageId, nodeIds, options)
+ }
let result: unknown
try {
diff --git a/packages/core/src/figma-api/compatibility.ts b/packages/core/src/figma-api/compatibility.ts
index 5c95c6f8d..8f6897c8b 100644
--- a/packages/core/src/figma-api/compatibility.ts
+++ b/packages/core/src/figma-api/compatibility.ts
@@ -6,6 +6,7 @@ import type {
DocumentNode,
Effect,
EffectStyle,
+ ExportMixin,
FrameNode,
GradientPaint,
GridStyle,
@@ -393,6 +394,12 @@ type ShapeMembersMatch = Expect<
>
const _shapeMembersMatch: ShapeMembersMatch = true
+type ExportKeys = 'exportSettings' | 'exportAsync'
+type ExportMembersMatch = Expect<
+ Extends<Pick<FigmaNodeProxy, ExportKeys>, Pick<ExportMixin, ExportKeys>>
+>
+const _exportMembersMatch: ExportMembersMatch = true
+
// --- Styles: each style's members are Figma's, apart from consumers, which read node proxies ---
type BaseStyleKeys =
diff --git a/packages/core/src/figma-api/export/accessors.ts b/packages/core/src/figma-api/export/accessors.ts
new file mode 100644
index 000000000..a202a79f7
--- /dev/null
+++ b/packages/core/src/figma-api/export/accessors.ts
@@ -0,0 +1,52 @@
+import type { ExportSettings } from '@figma/plugin-typings/plugin-api-standalone'
+
+import { OPEN_PENCIL_PLUGIN_DATA, withPluginData } from '@open-pencil/scene-graph/plugin-data'
+
+import {
+ graph,
+ nodeId,
+ raw,
+ updateNode,
+ type NodeProxyInternals,
+ type ProxyThis
+} from '#core/figma-api/accessor-utils'
+import type { NodeProxyHost } from '#core/figma-api/proxy'
+
+import { exportLayer } from './render'
+import { figmaExportSettings, parseExportRequest, parseExportSettings } from './settings'
+
+/**
+ * `exportSettings` and `exportAsync` on every layer and page, as Figma's `ExportMixin` has them;
+ * the document has neither.
+ */
+export function installExportAccessors(target: object, internals: NodeProxyInternals): void {
+ Object.defineProperty(target, 'exportSettings', {
+ get(this: ProxyThis): readonly ExportSettings[] {
+ return figmaExportSettings(raw(this, internals).exportSettings)
+ },
+ set(this: ProxyThis, value: unknown) {
+ const node = raw(this, internals)
+ const exportSettings = parseExportSettings(value, node.type === 'TEXT')
+ // Saved as the Export panel saves them, so a file keeps these rather than those it opened with.
+ const pluginData = withPluginData(
+ node.pluginData,
+ OPEN_PENCIL_PLUGIN_DATA.exportSettings,
+ exportSettings.length > 0 ? exportSettings : undefined
+ )
+ updateNode(this, internals, { exportSettings, pluginData })
+ }
+ })
+ Object.defineProperty(target, 'exportAsync', {
+ async value(this: ProxyThis, settings?: unknown): Promise<Uint8Array | string> {
+ const request = parseExportRequest(settings)
+ const node = graph(this, internals).getNode(nodeId(this, internals))
+ if (!node) {
+ throw new Error(
+ `in exportAsync: The node with id "${nodeId(this, internals)}" does not exist`
+ )
+ }
+ const host = this[internals.api] as NodeProxyHost
+ return exportLayer(host, graph(this, internals), node, request)
+ }
+ })
+}
diff --git a/packages/core/src/figma-api/export/render.ts b/packages/core/src/figma-api/export/render.ts
new file mode 100644
index 000000000..3f7fd63ef
--- /dev/null
+++ b/packages/core/src/figma-api/export/render.ts
@@ -0,0 +1,102 @@
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import {
+ isValidExportScale,
+ MAX_EXPORT_SCALE,
+ MIN_EXPORT_SCALE
+} from '@open-pencil/scene-graph/export-scale'
+
+import { flushPendingLayout } from '#core/figma-api/pending-layout'
+import type { ExportImageOptions } from '#core/figma-api/types'
+import { findPageId } from '#core/io/subgraph'
+
+import type { ExportRequest } from './settings'
+
+/** What a host lends an export: its renderer, for raster formats. */
+export interface ExportHost {
+ exportImage?: (nodeIds: string[], options: ExportImageOptions) => Promise<Uint8Array | null>
+}
+
+/** A layer or page as `exportAsync` writes it: bytes, an SVG string for `SVG_STRING`. */
+export async function exportLayer(
+ host: ExportHost,
+ graph: SceneGraph,
+ node: SceneNode,
+ request: ExportRequest
+): Promise<Uint8Array | string> {
+ // A script's edits that nothing read yet are laid out first, as Figma lays them out.
+ flushPendingLayout(graph)
+ // A page exports what is on it.
+ const ids =
+ node.type === 'CANVAS' ? graph.getChildren(node.id).map((child) => child.id) : [node.id]
+ const pageId = node.type === 'CANVAS' ? node.id : findPageId(graph, node.id)
+ if (!pageId) throw new Error(`in exportAsync: The node with id "${node.id}" is not on a page`)
+ switch (request.format) {
+ case 'PNG':
+ case 'JPG':
+ return exportImage(host, graph, pageId, ids, request)
+ case 'SVG':
+ case 'SVG_STRING': {
+ const { renderNodesToLaidOutSVG } = await import('#core/io/formats/svg/text/layout')
+ const svg = await renderNodesToLaidOutSVG(graph, pageId, ids, {
+ xmlDeclaration: false,
+ layerIds: request.svgIdAttribute,
+ useAbsoluteBounds: request.useAbsoluteBounds
+ })
+ if (svg === null) throw nothingToExport()
+ return request.format === 'SVG' ? new TextEncoder().encode(svg) : svg
+ }
+ case 'PDF': {
+ const { exportPDFDocument } = await import('#core/io/formats/pdf/document')
+ const pdf = await exportPDFDocument(graph, [{ pageId, nodeIds: ids }], { embedFonts: false })
+ if (!pdf || pdf.data.length === 0) throw nothingToExport()
+ return pdf.data
+ }
+ case 'JSON_REST_V1':
+ throw new Error('in exportAsync: OpenPencil does not export JSON_REST_V1')
+ default:
+ // Figma's words for a layer with nothing animated, which no OpenPencil layer has.
+ throw new Error('Cannot export node as video')
+ }
+}
+
+async function exportImage(
+ host: ExportHost,
+ graph: SceneGraph,
+ pageId: string,
+ ids: string[],
+ request: Extract<ExportRequest, { format: 'PNG' | 'JPG' }>
+): Promise<Uint8Array> {
+ if (!host.exportImage) {
+ throw new Error('in exportAsync: This host has no renderer to export PNG or JPG images with')
+ }
+ const { exportBounds, oversizedRaster, rasterSize } = await import('#core/io/formats/raster')
+ const bounds = exportBounds(graph, ids, request.useAbsoluteBounds)
+ if (!bounds) throw nothingToExport()
+ const constraint = request.constraint
+ let scale = 1
+ // Figma reads a scale of 0 as none.
+ if (constraint?.type === 'SCALE' && constraint.value !== 0) scale = constraint.value
+ if (constraint?.type === 'WIDTH') scale = constraint.value / (bounds.maxX - bounds.minX)
+ if (constraint?.type === 'HEIGHT') scale = constraint.value / (bounds.maxY - bounds.minY)
+ if (!isValidExportScale(scale)) {
+ throw new Error(
+ `in exportAsync: An image must be exported at ${MIN_EXPORT_SCALE} to ${MAX_EXPORT_SCALE} times the layer's size`
+ )
+ }
+ const { width, height } = rasterSize(bounds, scale)
+ const oversized = oversizedRaster(width, height)
+ if (oversized) throw new Error(`in exportAsync: ${oversized}`)
+ const data = await host.exportImage(ids, {
+ scale,
+ format: request.format,
+ pageId,
+ useAbsoluteBounds: request.useAbsoluteBounds
+ })
+ if (!data || data.length === 0) throw nothingToExport()
+ return data
+}
+
+/** Figma exports a hidden or empty layer as a blank pixel; OpenPencil has nothing to write. */
+function nothingToExport(): Error {
+ return new Error('in exportAsync: The layer draws nothing to export')
+}
diff --git a/packages/core/src/figma-api/export/settings.ts b/packages/core/src/figma-api/export/settings.ts
new file mode 100644
index 000000000..34b127c60
--- /dev/null
+++ b/packages/core/src/figma-api/export/settings.ts
@@ -0,0 +1,175 @@
+import type {
+ ExportSettings,
+ ExportSettingsConstraints
+} from '@figma/plugin-typings/plugin-api-standalone'
+import * as v from 'valibot'
+
+import type { ExportSetting } from '@open-pencil/scene-graph'
+import {
+ compactExportSetting,
+ EXPORT_OPTION_DEFAULTS,
+ type ExportFormatId
+} from '@open-pencil/scene-graph/export-format'
+import { clampExportScale } from '@open-pencil/scene-graph/export-scale'
+
+import { finiteNumberSchema } from '#core/figma-api/schema'
+import { parseFigma } from '#core/figma-api/validation'
+
+// Figma's export settings, as its plugin API checks and reads them (Figma desktop 126). An
+// export's options are checked loosely, so a key Figma does not know is dropped; its size is
+// checked strictly.
+
+const COLOR_PROFILES = ['DOCUMENT', 'SRGB', 'DISPLAY_P3_V4'] as const
+
+/** How big an export is: a multiplier, or a width or height in pixels. */
+const constraintSchema = v.union([
+ v.strictObject({ type: v.literal('SCALE'), value: finiteNumberSchema }),
+ v.strictObject({ type: v.picklist(['WIDTH', 'HEIGHT']), value: finiteNumberSchema })
+])
+
+const optionEntries = {
+ contentsOnly: v.optional(v.boolean()),
+ useAbsoluteBounds: v.optional(v.boolean()),
+ suffix: v.optional(v.string()),
+ colorProfile: v.optional(v.picklist(COLOR_PROFILES))
+}
+
+const imageSchema = v.looseObject({
+ format: v.picklist(['PNG', 'JPG']),
+ ...optionEntries,
+ constraint: v.optional(constraintSchema)
+})
+
+const pdfSchema = v.looseObject({ format: v.literal('PDF'), ...optionEntries })
+
+const svgSchema = v.looseObject({
+ format: v.picklist(['SVG', 'SVG_STRING']),
+ ...optionEntries,
+ svgOutlineText: v.optional(v.boolean()),
+ svgIdAttribute: v.optional(v.boolean()),
+ svgSimplifyStroke: v.optional(v.boolean())
+})
+
+/** An export a layer keeps: the formats Figma keeps, which includes the SVG string it refuses. */
+const exportSettingSchema = v.variant('format', [imageSchema, pdfSchema, svgSchema])
+
+/** What `exportAsync` takes: an export a layer keeps, Figma's REST JSON, or a video. */
+const exportRequestSchema = v.variant('format', [
+ imageSchema,
+ pdfSchema,
+ svgSchema,
+ v.strictObject({ format: v.literal('JSON_REST_V1') }),
+ v.looseObject({ format: v.picklist(['MP4', 'GIF', 'WEBM']) })
+])
+
+export type ExportRequest = v.InferOutput<typeof exportRequestSchema>
+
+/** What `exportAsync` was asked for, a PNG at its size when nothing was, or Figma's refusal. */
+export function parseExportRequest(value: unknown): ExportRequest {
+ if (value === undefined) return { format: 'PNG' }
+ return parseFigma(exportRequestSchema, value, 'exportAsync', 'settings')
+}
+
+type KeptExport = v.InferOutput<typeof exportSettingSchema>
+
+const FIGMA_FORMATS = {
+ png: 'PNG',
+ jpg: 'JPG',
+ svg: 'SVG',
+ pdf: 'PDF'
+} as const satisfies Partial<Record<ExportFormatId, ExportSettings['format']>>
+
+type FigmaFormat = (typeof FIGMA_FORMATS)[keyof typeof FIGMA_FORMATS]
+
+const MODEL_FORMATS: Record<FigmaFormat, ExportFormatId> = {
+ PNG: 'png',
+ JPG: 'jpg',
+ SVG: 'svg',
+ PDF: 'pdf'
+}
+
+function isFigmaFormat(format: ExportFormatId): format is keyof typeof FIGMA_FORMATS {
+ return format in FIGMA_FORMATS
+}
+
+/**
+ * A layer's exports as Figma reads them, each option filled in with its default. Exports in
+ * formats Figma has no setting for, such as WebP or PowerPoint, are left out.
+ */
+export function figmaExportSettings(settings: readonly ExportSetting[]): readonly ExportSettings[] {
+ return Object.freeze(
+ settings.flatMap((setting) =>
+ isFigmaFormat(setting.format)
+ ? [Object.freeze(figmaExportSetting(setting, FIGMA_FORMATS[setting.format]))]
+ : []
+ )
+ )
+}
+
+function figmaExportSetting(setting: ExportSetting, format: FigmaFormat): ExportSettings {
+ const defaults = EXPORT_OPTION_DEFAULTS
+ const options = {
+ suffix: setting.suffix ?? defaults.suffix,
+ contentsOnly: setting.contentsOnly ?? defaults.contentsOnly,
+ colorProfile: setting.colorProfile ?? defaults.colorProfile
+ }
+ // Figma reads `useAbsoluteBounds` only on text that has it.
+ const common = setting.useAbsoluteBounds ? { ...options, useAbsoluteBounds: true } : options
+ if (format === 'PDF') return { format, ...common }
+ if (format === 'SVG') {
+ return {
+ format,
+ ...common,
+ svgOutlineText: setting.svgOutlineText ?? defaults.svgOutlineText,
+ svgIdAttribute: setting.svgIdAttribute ?? defaults.svgIdAttribute,
+ svgSimplifyStroke: setting.svgSimplifyStroke ?? defaults.svgSimplifyStroke
+ }
+ }
+ const constraint: ExportSettingsConstraints = Object.freeze(
+ setting.size ? { ...setting.size } : { type: 'SCALE', value: setting.scale }
+ )
+ return { format, ...common, constraint }
+}
+
+/** `value` as the exports a layer keeps, or Figma's refusal of it. */
+export function parseExportSettings(value: unknown, isText: boolean): ExportSetting[] {
+ const parsed = parseFigma(
+ v.array(exportSettingSchema),
+ value,
+ 'set_exportSettings',
+ 'exportSettings'
+ )
+ return parsed.map((setting) => {
+ if (setting.format === 'SVG_STRING') {
+ throw new Error('in set_exportSettings: Invalid value "SVG_STRING" for enum "ImageType"')
+ }
+ if (setting.useAbsoluteBounds && !isText) {
+ throw new Error(
+ 'in set_exportSettings: Cannot set useAbsoluteBounds for ExportSetting on node that is not type text.'
+ )
+ }
+ return exportSetting(setting, MODEL_FORMATS[setting.format])
+ })
+}
+
+/** A kept export as the model keeps it. */
+function exportSetting(setting: KeptExport, format: ExportFormatId): ExportSetting {
+ const constraint =
+ setting.format === 'PNG' || setting.format === 'JPG' ? setting.constraint : undefined
+ const svg = setting.format === 'SVG' || setting.format === 'SVG_STRING' ? setting : undefined
+ return compactExportSetting({
+ scale: constraint?.type === 'SCALE' ? clampExportScale(constraint.value) : 1,
+ format,
+ size:
+ constraint && constraint.type !== 'SCALE'
+ ? { type: constraint.type, value: constraint.value }
+ : undefined,
+ suffix: setting.suffix,
+ contentsOnly: setting.contentsOnly,
+ useAbsoluteBounds: setting.useAbsoluteBounds,
+ colorProfile: setting.colorProfile,
+ svgOutlineText: svg?.svgOutlineText,
+ svgIdAttribute: svg?.svgIdAttribute,
+ svgSimplifyStroke: svg?.svgSimplifyStroke
+ })
+}
diff --git a/packages/core/src/figma-api/members.ts b/packages/core/src/figma-api/members.ts
index 5b9a5ecd7..12c42bc87 100644
--- a/packages/core/src/figma-api/members.ts
+++ b/packages/core/src/figma-api/members.ts
@@ -2,6 +2,7 @@ import type {
BooleanOperationNode,
ComponentSetNode,
DocumentNode,
+ ExportMixin,
Guide,
LeadingTrim,
MinimalFillsMixin,
@@ -91,6 +92,8 @@ export abstract class FigmaNodeMembers {
declare horizontalPadding: number
declare verticalPadding: number
declare guides: readonly Guide[]
+ declare exportSettings: ExportMixin['exportSettings']
+ declare exportAsync: ExportMixin['exportAsync']
declare layoutWrap: string
declare primaryAxisSizingMode: string
declare counterAxisSizingMode: string
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index a14bf1d72..0ad7ce8b8 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -23,6 +23,8 @@ import { installVectorNodeProxyAccessors } from './accessors/vector'
import { installVisualNodeProxyAccessors } from './accessors/visual'
import { installComponentPropertyAccessors } from './components'
import { installDevStatusAccessors } from './dev-status'
+import { installExportAccessors } from './export/accessors'
+import type { ExportHost } from './export/render'
import { FigmaNodeMembers } from './members'
import type { FigmaFrameNode, FigmaInstanceNode } from './node-types'
import { installInstanceOverrideAccessors } from './overrides'
@@ -44,7 +46,7 @@ export const INTERNAL_ID = Symbol('id')
export const INTERNAL_GRAPH = Symbol('graph')
export const INTERNAL_API = Symbol('api')
-export interface NodeProxyHost {
+export interface NodeProxyHost extends ExportHost {
wrapNode(id: string): FigmaNodeProxy
readonly currentPageId: string
/** How groups and booleans refit; booleans size to their result when a renderer is attached. */
@@ -82,6 +84,7 @@ export class FigmaNodeProxy extends FigmaNodeMembers {
if (type) installGuideAccessors(this, internals, type)
if (type) installInstanceOverrideAccessors(this, internals, type)
if (type) installStyleReferenceAccessors(this, internals, type, id === graph.rootId, MIXED)
+ if (type && id !== graph.rootId) installExportAccessors(this, internals)
// Figma loads a page's layers on demand in dynamic-page mode and has `loadAsync` on pages
// alone; every page here is already loaded.
if (type === 'CANVAS')
diff --git a/packages/core/src/figma-api/types.ts b/packages/core/src/figma-api/types.ts
index 571bc9304..1bfc1fb65 100644
--- a/packages/core/src/figma-api/types.ts
+++ b/packages/core/src/figma-api/types.ts
@@ -11,4 +11,6 @@ export interface ExportImageOptions {
format?: RasterExportFormat
quality?: number
pageId?: string
+ /** Crop to the layers' boxes rather than to everything they draw. */
+ useAbsoluteBounds?: boolean
}
diff --git a/packages/core/src/io/formats/raster/headless.ts b/packages/core/src/io/formats/raster/headless.ts
index 18d9dacf2..3146e4a77 100644
--- a/packages/core/src/io/formats/raster/headless.ts
+++ b/packages/core/src/io/formats/raster/headless.ts
@@ -42,6 +42,7 @@ export async function headlessRenderNodes(
format?: ExportFormat
quality?: number
trimTransparent?: boolean
+ useAbsoluteBounds?: boolean
} = {}
): Promise<Uint8Array | null> {
const { ck, renderer } = await getRenderer()
@@ -53,7 +54,8 @@ export async function headlessRenderNodes(
scale: options.scale ?? 1,
format: options.format ?? 'PNG',
quality: options.quality,
- trimTransparent: options.trimTransparent
+ trimTransparent: options.trimTransparent,
+ useAbsoluteBounds: options.useAbsoluteBounds
})
}
diff --git a/packages/core/src/io/formats/raster/index.ts b/packages/core/src/io/formats/raster/index.ts
index ef887e36e..6b3db3003 100644
--- a/packages/core/src/io/formats/raster/index.ts
+++ b/packages/core/src/io/formats/raster/index.ts
@@ -1,5 +1,9 @@
export {
computeContentBounds,
+ exportBounds,
+ MAX_RASTER_PIXELS,
+ oversizedRaster,
+ rasterSize,
renderNodesToImage,
renderThumbnail,
thumbnailFrame,
diff --git a/packages/core/src/io/formats/raster/render.ts b/packages/core/src/io/formats/raster/render.ts
index 21f375389..ea960f176 100644
--- a/packages/core/src/io/formats/raster/render.ts
+++ b/packages/core/src/io/formats/raster/render.ts
@@ -2,8 +2,12 @@ import type { CanvasKit, Canvas } from 'canvaskit-wasm'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import type { RenderColorSpace } from '@open-pencil/scene-graph/color'
-import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
-import { computeDescendantVisualBounds, type VisualBounds } from '@open-pencil/scene-graph/geometry'
+import { getAxisAlignedWorldBounds, getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
+import {
+ computeDescendantVisualBounds,
+ unionVisualBounds,
+ type VisualBounds
+} from '@open-pencil/scene-graph/geometry'
import type { Mat3 } from '@open-pencil/scene-graph/matrix'
import type { SkiaRenderer } from '#core/canvas'
@@ -21,6 +25,31 @@ interface RenderOptions {
quality?: number
colorSpace?: RenderColorSpace
trimTransparent?: boolean
+ /** Crop to the layers' boxes rather than to everything they draw, as Figma can for text. */
+ useAbsoluteBounds?: boolean
+}
+
+/**
+ * The most pixels a raster export holds: 8192 by 8192, 256 MB of RGBA. Larger images would
+ * exhaust the renderer's memory, so they are refused rather than attempted.
+ */
+export const MAX_RASTER_PIXELS = 8192 * 8192
+
+/** Exports up to this size are drawn at twice their size and scaled down, for smoother edges. */
+const SUPERSAMPLE = 2
+
+/** The pixel size of `bounds` exported at `scale`. */
+export function rasterSize(bounds: VisualBounds, scale: number): { width: number; height: number } {
+ return {
+ width: Math.ceil((bounds.maxX - bounds.minX) * scale),
+ height: Math.ceil((bounds.maxY - bounds.minY) * scale)
+ }
+}
+
+/** Why an image of `width` by `height` pixels is too big to export, or null when it is not. */
+export function oversizedRaster(width: number, height: number): string | null {
+ if (width * height <= MAX_RASTER_PIXELS) return null
+ return `An image can hold at most ${MAX_RASTER_PIXELS} pixels; this one would be ${width} by ${height}`
}
function ensureSinglePageSelection(graph: SceneGraph, pageId: string, nodeIds: string[]): boolean {
@@ -35,6 +64,26 @@ export function computeContentBounds(graph: SceneGraph, nodeIds: string[]) {
)
}
+/**
+ * What an export of `nodeIds` covers: everything they draw, or with `useAbsoluteBounds` their
+ * boxes alone; null when nothing is visible.
+ */
+export function exportBounds(
+ graph: SceneGraph,
+ nodeIds: string[],
+ useAbsoluteBounds = false
+): VisualBounds | null {
+ if (!useAbsoluteBounds) return computeContentBounds(graph, nodeIds)
+ let bounds: VisualBounds | null = null
+ for (const id of nodeIds) {
+ const node = graph.getNode(id)
+ if (!node?.visible) continue
+ const { x, y, width, height } = getAxisAlignedWorldBounds(node, graph)
+ bounds = unionVisualBounds(bounds, { minX: x, minY: y, maxX: x + width, maxY: y + height })
+ }
+ return bounds
+}
+
function findAlphaBounds(ck: CanvasKit, canvas: Canvas, width: number, height: number) {
const pixels = canvas.readPixels(0, 0, {
alphaType: ck.AlphaType.Unpremul,
@@ -94,7 +143,10 @@ function renderToSurface(
setup: (canvas: Canvas) => void,
trimTransparent = false
): Uint8Array<ArrayBuffer> | null {
- const renderScale = 2
+ const oversized = oversizedRaster(width, height)
+ if (oversized) throw new RangeError(oversized)
+ const renderScale =
+ width * height * SUPERSAMPLE * SUPERSAMPLE <= MAX_RASTER_PIXELS ? SUPERSAMPLE : 1
const renderWidth = width * renderScale
const renderHeight = height * renderScale
const pixels = ck.Malloc(Uint8Array, renderWidth * renderHeight * 4)
@@ -254,15 +306,14 @@ export function renderNodesToImage(
throw new Error('Raster export selection must stay on a single page')
}
- const bounds = computeContentBounds(graph, nodeIds)
+ const bounds = exportBounds(graph, nodeIds, options.useAbsoluteBounds)
if (!bounds) return null
const contentW = bounds.maxX - bounds.minX
const contentH = bounds.maxY - bounds.minY
if (contentW <= 0 || contentH <= 0) return null
- const pixelW = Math.ceil(contentW * options.scale)
- const pixelH = Math.ceil(contentH * options.scale)
+ const { width: pixelW, height: pixelH } = rasterSize(bounds, options.scale)
if (pixelW <= 0 || pixelH <= 0) return null
// Figma exports a layer by itself, without the page behind it, even when it blends.
diff --git a/packages/core/src/io/formats/svg/defs.ts b/packages/core/src/io/formats/svg/defs.ts
index 2563d4549..cf0bd1ca8 100644
--- a/packages/core/src/io/formats/svg/defs.ts
+++ b/packages/core/src/io/formats/svg/defs.ts
@@ -48,10 +48,18 @@ export interface SVGExportContext {
/** Measured line breaks. Without them, only explicit newlines start a new baseline. */
textLayout?: SVGTextLayout
fontAlias?: SVGFontAlias
+ /**
+ * When layers are written with their names as ids: how many have taken each name, and every id
+ * given out so far, defs included, so no two elements share one.
+ */
+ layerIds?: { names: Map<string, number>; taken: Set<string> }
}
export function nextDefId(ctx: SVGExportContext, prefix: string): string {
- return `${ctx.idPrefix ?? ''}${prefix}${ctx.defIdCounter++}`
+ let id = `${ctx.idPrefix ?? ''}${prefix}${ctx.defIdCounter++}`
+ while (ctx.layerIds?.taken.has(id)) id = `${ctx.idPrefix ?? ''}${prefix}${ctx.defIdCounter++}`
+ ctx.layerIds?.taken.add(id)
+ return id
}
export function formatColor(
diff --git a/packages/core/src/io/formats/svg/export.ts b/packages/core/src/io/formats/svg/export.ts
index 49461e13c..3bb43d5ce 100644
--- a/packages/core/src/io/formats/svg/export.ts
+++ b/packages/core/src/io/formats/svg/export.ts
@@ -3,7 +3,7 @@ import type { RenderColorSpace } from '@open-pencil/scene-graph/color'
import { normalizeDashPattern } from '#core/canvas/strokes'
import { lineStrokePath } from '#core/canvas/strokes/line'
import { fittedDashPattern } from '#core/canvas/strokes/sides'
-import { computeContentBounds } from '#core/io/formats/raster'
+import { exportBounds } from '#core/io/formats/raster'
import {
nextDefId,
@@ -382,7 +382,34 @@ function exportedFill(
function renderNode(node: SceneNode, ctx: SVGExportContext): SVGNode | null {
if (!node.visible) return null
+ // A layer without a name has nothing to be found by.
+ if (!ctx.layerIds || !node.name) return drawNode(node, ctx)
+ // Parents take their names before their children, so a repeated name counts in layer order.
+ const id = layerId(node.name, ctx.layerIds)
+ const drawn = drawNode(node, ctx)
+ if (!drawn) return null
+ // A layer drawn as its only child's element keeps that child's id and gets its own group.
+ if ('id' in drawn.attrs) return svg('g', { id }, drawn)
+ return { ...drawn, attrs: { id, ...drawn.attrs } }
+}
+
+/**
+ * A layer's name as an element id, numbered from `_2` when an earlier layer has it, as Figma does,
+ * and past any id already given out.
+ */
+function layerId(name: string, ids: NonNullable<SVGExportContext['layerIds']>): string {
+ let count = ids.names.get(name) ?? 0
+ let id: string
+ do {
+ count += 1
+ id = count === 1 ? name : `${name}_${count}`
+ } while (ids.taken.has(id))
+ ids.names.set(name, count)
+ ids.taken.add(id)
+ return id
+}
+function drawNode(node: SceneNode, ctx: SVGExportContext): SVGNode | null {
const { attrs: groupAttrs, clipId } = buildGroupAttrs(node, ctx)
if (node.type === 'TEXT') {
@@ -467,6 +494,10 @@ export interface SVGExportOptions {
* file under. Text in an aliased face is written in that family at normal weight and style.
*/
fontAlias?: SVGFontAlias
+ /** Each layer's name as its element's `id`, as Figma's "Include id attribute" writes it. */
+ layerIds?: boolean
+ /** Size the drawing to the layers' boxes rather than to everything they draw. */
+ useAbsoluteBounds?: boolean
}
export function renderNodesToSVG(
@@ -475,7 +506,7 @@ export function renderNodesToSVG(
nodeIds: string[],
options: SVGExportOptions = {}
): string | null {
- const bounds = computeContentBounds(graph, nodeIds)
+ const bounds = exportBounds(graph, nodeIds, options.useAbsoluteBounds)
if (!bounds) return null
const { minX, minY, maxX, maxY } = bounds
@@ -488,7 +519,8 @@ export function renderNodesToSVG(
graph,
colorSpace: options.colorSpace ?? 'srgb',
textLayout: options.textLayout,
- fontAlias: options.fontAlias
+ fontAlias: options.fontAlias,
+ layerIds: options.layerIds ? { names: new Map(), taken: new Set() } : undefined
}
const contentNodes: SVGNode[] = []
diff --git a/packages/core/tests/figma-api/export.test.ts b/packages/core/tests/figma-api/export.test.ts
new file mode 100644
index 000000000..935e5dc12
--- /dev/null
+++ b/packages/core/tests/figma-api/export.test.ts
@@ -0,0 +1,319 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createAPI } from '#core-tests/helpers/figma-api'
+
+import { headlessRenderNodes, MAX_RASTER_PIXELS } from '#core/io/formats/raster'
+
+// Figma's answers measured in Figma desktop 126.
+
+function refusal(run: () => unknown): string | null {
+ try {
+ run()
+ } catch (error) {
+ return error instanceof Error ? error.message : String(error)
+ }
+ return null
+}
+
+/** A PNG's size, from its header. */
+function pngSize(data: Uint8Array | string): [number, number] {
+ if (typeof data === 'string') throw new Error('expected PNG bytes')
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength)
+ return [view.getUint32(16), view.getUint32(20)]
+}
+
+describe('exportSettings', () => {
+ test('reads each export with Figma’s defaults filled in', () => {
+ const figma = createAPI()
+ const rect = figma.createRectangle()
+ expect(rect.exportSettings).toEqual([])
+ rect.exportSettings = [
+ { format: 'PNG', constraint: { type: 'SCALE', value: 2 }, suffix: '@2x' },
+ { format: 'SVG', svgIdAttribute: true },
+ { format: 'JPG', constraint: { type: 'HEIGHT', value: 30 }, colorProfile: 'SRGB' },
+ { format: 'PDF' }
+ ]
+ expect(rect.exportSettings).toEqual([
+ {
+ format: 'PNG',
+ suffix: '@2x',
+ contentsOnly: true,
+ colorProfile: 'DOCUMENT',
+ constraint: { type: 'SCALE', value: 2 }
+ },
+ {
+ format: 'SVG',
+ suffix: '',
+ contentsOnly: true,
+ colorProfile: 'DOCUMENT',
+ svgOutlineText: true,
+ svgIdAttribute: true,
+ svgSimplifyStroke: true
+ },
+ {
+ format: 'JPG',
+ suffix: '',
+ contentsOnly: true,
+ colorProfile: 'SRGB',
+ constraint: { type: 'HEIGHT', value: 30 }
+ },
+ { format: 'PDF', suffix: '', contentsOnly: true, colorProfile: 'DOCUMENT' }
+ ])
+ expect(figma.graph.getNode(rect.id)?.exportSettings[2]).toEqual({
+ scale: 1,
+ format: 'jpg',
+ size: { type: 'HEIGHT', value: 30 },
+ colorProfile: 'SRGB'
+ })
+ })
+
+ test('drops keys Figma does not know, and options its format has no use for', () => {
+ const figma = createAPI()
+ const rect = figma.createRectangle()
+ rect.exportSettings = [
+ { format: 'PNG', foo: 1 },
+ { format: 'PDF', constraint: { type: 'SCALE', value: 2 } }
+ ] as never
+ expect(rect.exportSettings).toEqual([
+ {
+ format: 'PNG',
+ suffix: '',
+ contentsOnly: true,
+ colorProfile: 'DOCUMENT',
+ constraint: { type: 'SCALE', value: 1 }
+ },
+ { format: 'PDF', suffix: '', contentsOnly: true, colorProfile: 'DOCUMENT' }
+ ])
+ })
+
+ test('leaves out exports in formats Figma has no setting for', () => {
+ const figma = createAPI()
+ const rect = figma.createRectangle()
+ figma.graph.updateNode(rect.id, {
+ exportSettings: [
+ { scale: 1, format: 'webp' },
+ { scale: 1, format: 'png' }
+ ]
+ })
+ expect(rect.exportSettings.map((setting) => setting.format)).toEqual(['PNG'])
+ })
+
+ test('refuses what Figma refuses, in its words', () => {
+ const figma = createAPI()
+ const rect = figma.createRectangle()
+ const text = figma.createText()
+ const set = (value: unknown) =>
+ refusal(() => {
+ rect.exportSettings = value as never
+ })
+ const invalid = 'in set_exportSettings: Property "exportSettings" failed validation: '
+ expect(set([{ format: 'WEBP' }])).toBe(
+ `${invalid}Expected [0].format to be one of the following: PNG, JPG, PDF, SVG, SVG_STRING`
+ )
+ expect(set({ format: 'PNG' })).toBe(`${invalid}Expected array, received object`)
+ expect(set([null])).toBe(`${invalid}Expected object, received null at index 0`)
+ expect(set([{ format: 'PNG', suffix: 1 }])).toBe(
+ `${invalid}Expected string, received number at [0].suffix`
+ )
+ expect(set([{ format: 'PNG', colorProfile: 'P3' }])).toBe(
+ `${invalid}Invalid option: expected one of "DOCUMENT"|"SRGB"|"DISPLAY_P3_V4" at [0].colorProfile`
+ )
+ expect(set([{ format: 'PNG', constraint: { type: 'SCALE' } }])).toBe(
+ `${invalid}Expected [0].constraint to be one of the following, but none matched:\n` +
+ ' Required value missing at [0].constraint.value\n' +
+ ' Multiple issues at [0].constraint:\n' +
+ ' Invalid option: expected one of "WIDTH"|"HEIGHT" at [0].constraint.type\n' +
+ ' Required value missing at [0].constraint.value'
+ )
+ expect(set([{ format: 'PNG', constraint: { type: 'WIDTH', value: 2, foo: 1 } }])).toBe(
+ `${invalid}Unrecognized key: "foo" at [0].constraint`
+ )
+ expect(set([{ format: 'SVG_STRING' }])).toBe(
+ 'in set_exportSettings: Invalid value "SVG_STRING" for enum "ImageType"'
+ )
+ expect(set([{ format: 'PNG', useAbsoluteBounds: true }])).toBe(
+ 'in set_exportSettings: Cannot set useAbsoluteBounds for ExportSetting on node that is not type text.'
+ )
+ text.exportSettings = [{ format: 'PNG', useAbsoluteBounds: true }]
+ expect(text.exportSettings[0]).toMatchObject({ useAbsoluteBounds: true })
+ })
+
+ test('pages keep exports, and the document has none', () => {
+ const figma = createAPI()
+ figma.currentPage.exportSettings = [{ format: 'PDF' }]
+ expect(figma.currentPage.exportSettings).toHaveLength(1)
+ expect('exportSettings' in figma.root).toBe(false)
+ expect('exportAsync' in figma.root).toBe(false)
+ })
+})
+
+describe('exportAsync', () => {
+ test('refuses settings Figma refuses, in its words', async () => {
+ const figma = createAPI()
+ const rect = figma.createRectangle()
+ const invalid = 'in exportAsync: Property "settings" failed validation: '
+ await expect(rect.exportAsync({ format: 'WEBP' } as never)).rejects.toThrow(
+ `${invalid}Expected .format to be one of the following: PNG, JPG, PDF, SVG, SVG_STRING, JSON_REST_V1, MP4, GIF, WEBM`
+ )
+ await expect(rect.exportAsync(null as never)).rejects.toThrow(
+ `${invalid}Expected object, received null`
+ )
+ await expect(rect.exportAsync({ format: 'JSON_REST_V1', foo: 1 } as never)).rejects.toThrow(
+ `${invalid}Unrecognized key: "foo"`
+ )
+ await expect(rect.exportAsync({ format: 'GIF' })).rejects.toThrow('Cannot export node as video')
+ const gone = figma.createRectangle()
+ gone.remove()
+ await expect(gone.exportAsync({ format: 'SVG' })).rejects.toThrow(
+ `in exportAsync: The node with id "${gone.id}" does not exist`
+ )
+ })
+
+ test('writes SVG as bytes or a string, with layer names as ids on request', async () => {
+ const figma = createAPI()
+ const frame = figma.createFrame()
+ frame.name = 'Card'
+ frame.resize(60, 40)
+ for (const x of [0, 20]) {
+ const box = figma.createRectangle()
+ box.name = 'Box'
+ box.resize(10, 10)
+ box.x = x
+ frame.appendChild(box)
+ }
+ const bytes = await frame.exportAsync({ format: 'SVG' })
+ expect(bytes).toBeInstanceOf(Uint8Array)
+ const svg = await frame.exportAsync({ format: 'SVG_STRING', svgIdAttribute: true })
+ expect(svg.startsWith('<svg')).toBe(true)
+ // Layers' ids, not those of the clip paths and gradients they use.
+ const layerIds = [...svg.matchAll(/<(?:g|rect|path) id="([^"]+)"/g)].map((match) => match[1])
+ expect(layerIds).toEqual(['Card', 'Box', 'Box_2'])
+ expect(await frame.exportAsync({ format: 'SVG_STRING' })).not.toContain(' id="Box"')
+ })
+
+ test('writes a PDF', async () => {
+ const figma = createAPI()
+ const pdf = await figma.createRectangle().exportAsync({ format: 'PDF' })
+ expect(new TextDecoder().decode(pdf.slice(0, 5))).toBe('%PDF-')
+ })
+
+ test('sizes images by scale, width, or height, around what the layer draws', async () => {
+ const figma = createAPI()
+ figma.exportImage = (ids, options) =>
+ headlessRenderNodes(figma.graph, options.pageId ?? figma.currentPageId, ids, options)
+ const rect = figma.createRectangle()
+ rect.resize(20, 10)
+ rect.strokes = [{ type: 'SOLID', color: { r: 0, g: 0, b: 0 } }]
+ rect.strokeWeight = 2
+ rect.strokeAlign = 'OUTSIDE'
+ expect(pngSize(await rect.exportAsync())).toEqual([24, 14])
+ expect(pngSize(await rect.exportAsync({ format: 'PNG', useAbsoluteBounds: true }))).toEqual([
+ 20, 10
+ ])
+ const scaled = { format: 'PNG', constraint: { type: 'SCALE', value: 0.5 } } as const
+ expect(pngSize(await rect.exportAsync(scaled))).toEqual([12, 7])
+ const wide = { format: 'PNG', constraint: { type: 'WIDTH', value: 48 } } as const
+ expect(pngSize(await rect.exportAsync(wide))).toEqual([48, 28])
+ const tall = { format: 'PNG', constraint: { type: 'HEIGHT', value: 7 } } as const
+ expect(pngSize(await rect.exportAsync(tall))).toEqual([12, 7])
+ // Figma reads a scale of 0 as none.
+ const unscaled = { format: 'PNG', constraint: { type: 'SCALE', value: 0 } } as const
+ expect(pngSize(await rect.exportAsync(unscaled))).toEqual([24, 14])
+ const jpg = await rect.exportAsync({ format: 'JPG' })
+ expect([jpg[0], jpg[1]]).toEqual([0xff, 0xd8])
+ })
+
+ test('lays out a script’s pending edits before exporting', async () => {
+ const figma = createAPI()
+ const frame = figma.createFrame()
+ frame.layoutMode = 'HORIZONTAL'
+ frame.primaryAxisSizingMode = 'AUTO'
+ frame.counterAxisSizingMode = 'AUTO'
+ for (let index = 0; index < 3; index += 1) {
+ const box = figma.createRectangle()
+ box.resize(10, 10)
+ frame.appendChild(box)
+ }
+ const svg = await frame.exportAsync({ format: 'SVG_STRING' })
+ expect(svg).toContain('width="30"')
+ })
+
+ test('keeps every SVG id unique', async () => {
+ const figma = createAPI()
+ const frame = figma.createFrame()
+ frame.name = 'clip0'
+ frame.resize(60, 40)
+ frame.clipsContent = true
+ for (const name of ['Box', 'Box_2', 'Box']) {
+ const box = figma.createRectangle()
+ box.name = name
+ box.resize(10, 10)
+ frame.appendChild(box)
+ }
+ const unnamed = figma.createRectangle()
+ unnamed.name = ''
+ frame.appendChild(unnamed)
+ const svg = await frame.exportAsync({ format: 'SVG_STRING', svgIdAttribute: true })
+ expect(svg).not.toContain('id=""')
+ const ids = [...svg.matchAll(/ id="([^"]+)"/g)].map((match) => match[1])
+ expect(new Set(ids).size).toBe(ids.length)
+ expect(ids).toEqual(expect.arrayContaining(['clip0', 'Box', 'Box_2', 'Box_3']))
+ })
+
+ test('sizes an SVG to the layer’s box with useAbsoluteBounds', async () => {
+ const figma = createAPI()
+ const rect = figma.createRectangle()
+ rect.resize(20, 10)
+ rect.strokes = [{ type: 'SOLID', color: { r: 0, g: 0, b: 0 } }]
+ rect.strokeWeight = 2
+ rect.strokeAlign = 'OUTSIDE'
+ expect(await rect.exportAsync({ format: 'SVG_STRING' })).toContain('width="24"')
+ const boxed = await rect.exportAsync({ format: 'SVG_STRING', useAbsoluteBounds: true })
+ expect(boxed).toContain('width="20"')
+ })
+
+ test('refuses an image size past the export scale limits rather than shrinking it', async () => {
+ const figma = createAPI()
+ figma.exportImage = () => Promise.resolve(new Uint8Array([1]))
+ const rect = figma.createRectangle()
+ rect.resize(1, 1)
+ const limit = "in exportAsync: An image must be exported at 0.01 to 1024 times the layer's size"
+ await expect(
+ rect.exportAsync({ format: 'PNG', constraint: { type: 'WIDTH', value: 2000 } })
+ ).rejects.toThrow(limit)
+ await expect(
+ rect.exportAsync({ format: 'PNG', constraint: { type: 'SCALE', value: -1 } })
+ ).rejects.toThrow(limit)
+ })
+
+ test('refuses an image too big for the renderer before drawing it', async () => {
+ const figma = createAPI()
+ let drawn = 0
+ figma.exportImage = () => {
+ drawn++
+ return Promise.resolve(new Uint8Array([1]))
+ }
+ const rect = figma.createRectangle()
+ rect.resize(10, 10)
+ await expect(
+ rect.exportAsync({ format: 'PNG', constraint: { type: 'SCALE', value: 1024 } })
+ ).rejects.toThrow(
+ `in exportAsync: An image can hold at most ${MAX_RASTER_PIXELS} pixels; this one would be 10240 by 10240`
+ )
+ expect(drawn).toBe(0)
+ // The renderer refuses it as well, for callers that skip exportAsync.
+ await expect(
+ headlessRenderNodes(figma.graph, figma.currentPageId, [rect.id], {
+ scale: 1024,
+ format: 'PNG'
+ })
+ ).rejects.toThrow(`at most ${MAX_RASTER_PIXELS} pixels`)
+ })
+
+ test('says so when the host has no renderer for images', async () => {
+ const figma = createAPI()
+ await expect(figma.createRectangle().exportAsync()).rejects.toThrow(
+ 'in exportAsync: This host has no renderer to export PNG or JPG images with'
+ )
+ })
+})
diff --git a/packages/docs/de/programmable/cli/scripting.md b/packages/docs/de/programmable/cli/scripting.md
index e3770af57..fe36bcb58 100644
--- a/packages/docs/de/programmable/cli/scripting.md
+++ b/packages/docs/de/programmable/cli/scripting.md
@@ -37,6 +37,6 @@ Exakte Namen wie `figma.createFrame()`, `node.appendChild()`, `fontSize` und `la
## Noch nicht kompatibel
-Noch nicht angeboten werden unter anderem `node.exportAsync()`, `node.setBoundVariable()`, `figma.combineAsVariants()` und die Stil-APIs von Figma.
+Noch nicht angeboten werden unter anderem `node.setBoundVariable()` und `figma.combineAsVariants()`.
Dafür stehen je nach Aufgabe CLI-Export, Werkzeuge des Kernpakets oder direkte SceneGraph-Hilfsfunktionen zur Verfügung.
diff --git a/packages/docs/es/programmable/cli/scripting.md b/packages/docs/es/programmable/cli/scripting.md
index 9e9b03fe9..c8ae06232 100644
--- a/packages/docs/es/programmable/cli/scripting.md
+++ b/packages/docs/es/programmable/cli/scripting.md
@@ -111,6 +111,6 @@ Las propiedades habituales se leen y modifican mediante el objeto correspondient
## Limitaciones
-Aún no hay equivalentes completos para `node.exportAsync()`, las variables de bibliotecas, estilos de pintura/texto y todas las operaciones booleanas vectoriales.
+Aún no hay equivalentes completos para las variables de bibliotecas y todas las operaciones booleanas vectoriales.
Según la tarea, pueden usarse el comando de exportación, las herramientas del núcleo o las operaciones directas de SceneGraph.
diff --git a/packages/docs/fr/programmable/cli/scripting.md b/packages/docs/fr/programmable/cli/scripting.md
index cb446fe05..8ecfe9ba8 100644
--- a/packages/docs/fr/programmable/cli/scripting.md
+++ b/packages/docs/fr/programmable/cli/scripting.md
@@ -55,6 +55,6 @@ Les identifiants exacts comme `figma.currentPage`, `createFrame`, `appendChild`,
## Limites
-Il n’existe pas encore d’équivalent complet pour `node.exportAsync()`, `node.setBoundVariable()`, `figma.combineAsVariants()`, les styles de peinture/texte et toutes les opérations booléennes vectorielles.
+Il n’existe pas encore d’équivalent complet pour `node.setBoundVariable()`, `figma.combineAsVariants()` et toutes les opérations booléennes vectorielles.
Selon le besoin, utilisez aussi la commande d’exportation, les outils du noyau ou les opérations directes de SceneGraph.
diff --git a/packages/docs/it/programmable/cli/scripting.md b/packages/docs/it/programmable/cli/scripting.md
index d0e5e5f6e..8599acf07 100644
--- a/packages/docs/it/programmable/cli/scripting.md
+++ b/packages/docs/it/programmable/cli/scripting.md
@@ -47,4 +47,4 @@ Gli identificatori esatti come `figma.currentPage`, `createFrame`, `appendChild`
## Limiti
-Non esistono ancora equivalenti completi per `node.exportAsync()`, `node.setBoundVariable()`, `figma.combineAsVariants()`, gli stili e tutte le operazioni booleane vettoriali.
+Non esistono ancora equivalenti completi per `node.setBoundVariable()`, `figma.combineAsVariants()` e tutte le operazioni booleane vettoriali.
diff --git a/packages/docs/pl/programmable/cli/scripting.md b/packages/docs/pl/programmable/cli/scripting.md
index 512bf1a5e..8abc60f28 100644
--- a/packages/docs/pl/programmable/cli/scripting.md
+++ b/packages/docs/pl/programmable/cli/scripting.md
@@ -108,6 +108,6 @@ Najczęściej używane właściwości można odczytywać i zapisywać przez poś
## Brak pełnej zgodności z Figmą
-Nie są jeszcze dostępne między innymi `node.exportAsync()`, zmienne z bibliotek i API stylów Figmy.
+Nie są jeszcze dostępne między innymi zmienne z bibliotek.
Zamiast nich używaj poleceń eksportu CLI, narzędzi głównego pakietu albo bezpośrednich funkcji pomocniczych SceneGraph.
diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.md
index 8b68e21c0..3bbb380a0 100644
--- a/packages/docs/programmable/cli/scripting.md
+++ b/packages/docs/programmable/cli/scripting.md
@@ -247,6 +247,11 @@ The API is intentionally close to Figma's Plugin API, but it maps to OpenPencil'
- `style.name`, `description`, `key`, `paints`, `effects`, `layoutGrids`, a text style's font, size, spacing, case, and decoration, `getStyleConsumersAsync()`, and `remove()`; a change to a style reaches every layer and text range that uses it, and removing it leaves them its values
- `fillStyleId`, `strokeStyleId`, `effectStyleId`, `gridStyleId`, and `textStyleId` with their `set…StyleIdAsync` setters, on the layers Figma has them on; setting one gives the layer the style's values, an empty ID takes the style off, and a style the document does not hold is refused
+### Export
+
+- `node.exportAsync(settings?)` on layers and pages writes `PNG` and `JPG` (sized by a `SCALE`, `WIDTH`, or `HEIGHT` constraint, cropped to the layer's box with `useAbsoluteBounds`), `SVG` as bytes, `SVG_STRING` as a string (with layer names as element ids when `svgIdAttribute` is set), and `PDF`. PNG and JPG need a renderer: the desktop app, the browser app, and `open-pencil eval` have one. SVG text stays `<text>` whatever `svgOutlineText` says, colour profiles are not applied, and `contentsOnly: false` exports the layer alone. A hidden or empty layer is refused with `The layer draws nothing to export`, where Figma exports a 1×1 image. OpenPencil also refuses an image at less than 0.01 or more than 1024 times the layer's size, or larger than 8192 by 8192 pixels. `JSON_REST_V1` and video formats are refused
+- `node.exportSettings` reads and sets the exports a layer keeps, with Figma's options and defaults; exports in formats Figma has no setting for, such as WebP or PowerPoint, are left out
+
### Properties
Common node properties are readable/writable through the proxy, including:
@@ -288,10 +293,8 @@ Common node properties are readable/writable through the proxy, including:
These Figma APIs are not exposed as compatible helpers yet:
-- `node.exportAsync()`
- `figma.util.normalizeMarkdown()`, which fails because OpenPencil has no rich-text descriptions or annotations to normalize for
- Library variables, extended collections, and variable bindings on effects and layout grids
-- Figma style APIs such as `figma.createPaintStyle()` / `figma.createTextStyle()`
- Full vector boolean operation parity
Use OpenPencil CLI export commands, core tools, or direct scene-graph helpers where available.
diff --git a/packages/docs/ru/programmable/cli/scripting.md b/packages/docs/ru/programmable/cli/scripting.md
index 2a2869392..3cd55d4c7 100644
--- a/packages/docs/ru/programmable/cli/scripting.md
+++ b/packages/docs/ru/programmable/cli/scripting.md
@@ -149,9 +149,7 @@ API намеренно близок к Figma Plugin API, но работает
Следующие API пока не предоставляются в совместимом виде:
-- `node.exportAsync()`
- переменные из библиотек, расширенные коллекции и привязки переменных к эффектам и сеткам
-- API стилей Figma, например `figma.createPaintStyle()` и `figma.createTextStyle()`
- полная совместимость логических операций над векторами
Вместо них используйте команды экспорта OpenPencil CLI, инструменты основного пакета или прямые вспомогательные функции SceneGraph, когда они доступны.
diff --git a/packages/fig/src/node-change/plugin-data.ts b/packages/fig/src/node-change/plugin-data.ts
index e77b6ea5e..2f776115a 100644
--- a/packages/fig/src/node-change/plugin-data.ts
+++ b/packages/fig/src/node-change/plugin-data.ts
@@ -1,4 +1,5 @@
import { omit } from 'es-toolkit/object'
+import * as v from 'valibot'
import type { NodeChange, PluginData, PluginRelaunchData } from '@open-pencil/kiwi/fig/codec'
import { guidToString } from '@open-pencil/kiwi/fig/guid'
@@ -8,7 +9,7 @@ import type {
PluginRelaunchDataEntry,
SceneNode
} from '@open-pencil/scene-graph'
-import type { ExportFormatId } from '@open-pencil/scene-graph/export-format'
+import { compactExportSetting, type ExportFormatId } from '@open-pencil/scene-graph/export-format'
import { clampExportScale } from '@open-pencil/scene-graph/export-scale'
import {
hasPluginData,
@@ -131,29 +132,63 @@ function mapNativeImageType(imageType: unknown): ExportFormatId | null {
return null
}
-function extractNativeConstraintScale(constraint: unknown): number {
- if (!constraint || typeof constraint !== 'object' || Array.isArray(constraint)) return 1
- const type = (constraint as { type?: unknown }).type
- if (type !== 'CONTENT_SCALE' && type !== 0) return 1
- const value = (constraint as { value?: unknown }).value
- // Clamp native CONTENT_SCALE too: malformed .fig data can carry huge multipliers.
- return typeof value === 'number' && Number.isFinite(value) ? clampExportScale(value) : 1
-}
-
export function extractExportSettings(nc: NodeChange): ExportSetting[] {
const pluginSettings = readNodeChangePluginData(nc, exportSettings)
if (pluginSettings) return pluginSettings
-
return (nc.exportSettings ?? []).flatMap((entry): ExportSetting[] => {
- if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return []
- const format = mapNativeImageType((entry as { imageType?: unknown }).imageType)
- if (!format) return []
- return [
- {
- scale: extractNativeConstraintScale((entry as { constraint?: unknown }).constraint),
- format
- }
- ]
+ const native = v.safeParse(nativeExportSettingSchema, entry)
+ if (!native.success) return []
+ const format = mapNativeImageType(native.output.imageType)
+ return format ? [exportSettingFromNative(native.output, format)] : []
+ })
+}
+
+/** An enum Kiwi decodes by name, or by its index in `names` when it is a number. */
+function nativeEnum<const T extends string>(names: readonly T[], value: unknown): T | undefined {
+ const name = typeof value === 'number' ? names[value] : value
+ return names.find((candidate) => candidate === name)
+}
+
+const CONSTRAINT_TYPES = ['CONTENT_SCALE', 'CONTENT_WIDTH', 'CONTENT_HEIGHT'] as const
+const COLOR_PROFILES = ['DOCUMENT', 'SRGB', 'DISPLAY_P3_V4'] as const
+const SVG_ID_MODES = ['IF_NEEDED', 'ALWAYS'] as const
+
+const nativeExportSettingSchema = v.looseObject({
+ imageType: v.unknown(),
+ suffix: v.optional(v.string()),
+ constraint: v.optional(
+ v.looseObject({ type: v.unknown(), value: v.optional(v.pipe(v.number(), v.finite())) })
+ ),
+ contentsOnly: v.optional(v.boolean()),
+ useAbsoluteBounds: v.optional(v.boolean()),
+ colorProfile: v.optional(v.unknown()),
+ svgOutlineText: v.optional(v.boolean()),
+ svgIDMode: v.optional(v.unknown()),
+ svgForceStrokeMasks: v.optional(v.boolean())
+})
+
+/** Figma's export options as the model keeps them; an option Figma left out reads as its default. */
+function exportSettingFromNative(
+ native: v.InferOutput<typeof nativeExportSettingSchema>,
+ format: ExportFormatId
+): ExportSetting {
+ const constraint = nativeEnum(CONSTRAINT_TYPES, native.constraint?.type) ?? 'CONTENT_SCALE'
+ const value = native.constraint?.value
+ const svgIDMode = nativeEnum(SVG_ID_MODES, native.svgIDMode)
+ const sized = constraint !== 'CONTENT_SCALE' && value !== undefined
+ return compactExportSetting({
+ // Clamp native CONTENT_SCALE too: malformed .fig data can carry huge multipliers.
+ scale: constraint === 'CONTENT_SCALE' && value !== undefined ? clampExportScale(value) : 1,
+ format,
+ size: sized ? { type: constraint === 'CONTENT_WIDTH' ? 'WIDTH' : 'HEIGHT', value } : undefined,
+ suffix: native.suffix,
+ contentsOnly: native.contentsOnly,
+ useAbsoluteBounds: native.useAbsoluteBounds,
+ colorProfile: nativeEnum(COLOR_PROFILES, native.colorProfile),
+ svgOutlineText: native.svgOutlineText,
+ svgIdAttribute: svgIDMode === undefined ? undefined : svgIDMode === 'ALWAYS',
+ svgSimplifyStroke:
+ native.svgForceStrokeMasks === undefined ? undefined : !native.svgForceStrokeMasks
})
}
diff --git a/packages/fig/tests/node-change/plugin-data.test.ts b/packages/fig/tests/node-change/plugin-data.test.ts
index a7994dae9..85b04a491 100644
--- a/packages/fig/tests/node-change/plugin-data.test.ts
+++ b/packages/fig/tests/node-change/plugin-data.test.ts
@@ -8,6 +8,7 @@ import {
} from '#fig/node-change/plugin-data'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import type { ExportSetting } from '@open-pencil/scene-graph'
import { clampExportScale } from '@open-pencil/scene-graph/export-scale'
import {
OPEN_PENCIL_PLUGIN_DATA,
@@ -82,6 +83,66 @@ describe('OpenPencil plugin data readers', () => {
}
})
+ test('native export settings keep Figma’s options, by name or by index', () => {
+ expect(
+ extractExportSettings({
+ exportSettings: [
+ {
+ imageType: 'PNG',
+ suffix: '@2x',
+ constraint: { type: 'CONTENT_WIDTH', value: 120 },
+ contentsOnly: false,
+ useAbsoluteBounds: true,
+ colorProfile: 'SRGB'
+ },
+ {
+ imageType: 2,
+ constraint: { type: 0, value: 3 },
+ svgOutlineText: false,
+ svgIDMode: 1,
+ svgForceStrokeMasks: true,
+ colorProfile: 0
+ },
+ { imageType: 'MP4' }
+ ]
+ })
+ ).toEqual([
+ {
+ scale: 1,
+ format: 'png',
+ suffix: '@2x',
+ size: { type: 'WIDTH', value: 120 },
+ contentsOnly: false,
+ useAbsoluteBounds: true,
+ colorProfile: 'SRGB'
+ },
+ {
+ scale: 3,
+ format: 'svg',
+ svgOutlineText: false,
+ svgIdAttribute: true,
+ svgSimplifyStroke: false
+ }
+ ])
+ })
+
+ test('export settings in plugin data keep Figma’s options', () => {
+ const settings: ExportSetting[] = [
+ {
+ scale: 1,
+ format: 'jpg',
+ suffix: '-small',
+ size: { type: 'HEIGHT', value: 40 },
+ colorProfile: 'DISPLAY_P3_V4'
+ }
+ ]
+ expect(
+ extractExportSettings(
+ withPluginValue(OPEN_PENCIL_PLUGIN_DATA.exportSettings.key, JSON.stringify(settings))
+ )
+ ).toEqual(settings)
+ })
+
test('library source defaults its optional fields and rejects a malformed identity', () => {
const identity = { libraryId: 'lib', assetKey: 'button', revisionId: 'r1' }
expect(
diff --git a/packages/scene-graph/src/export-format.ts b/packages/scene-graph/src/export-format.ts
index e2248d376..29aa22949 100644
--- a/packages/scene-graph/src/export-format.ts
+++ b/packages/scene-graph/src/export-format.ts
@@ -1,3 +1,7 @@
+import { omitBy } from 'es-toolkit/object'
+
+import type { ExportSetting } from './types'
+
/**
* Formats a node's export settings may persist. Each id must name a Core IO
* export adapter that supports node export; labels and options come from that
@@ -10,3 +14,28 @@ export type ExportFormatId = (typeof EXPORT_FORMAT_IDS)[number]
export function isExportFormatId(value: unknown): value is ExportFormatId {
return EXPORT_FORMAT_IDS.some((id) => id === value)
}
+
+/** What each of Figma's export options reads as when an export leaves it out. */
+export const EXPORT_OPTION_DEFAULTS = {
+ suffix: '',
+ contentsOnly: true,
+ useAbsoluteBounds: false,
+ colorProfile: 'DOCUMENT',
+ svgOutlineText: true,
+ svgIdAttribute: false,
+ svgSimplifyStroke: true
+} as const satisfies Required<Omit<ExportSetting, 'scale' | 'format' | 'size'>>
+
+/** An export as the model keeps it: options that are unset or at Figma's default left out. */
+export function compactExportSetting({
+ scale,
+ format,
+ size,
+ ...options
+}: ExportSetting): ExportSetting {
+ const changed = omitBy(
+ options,
+ (value, key) => value === undefined || value === EXPORT_OPTION_DEFAULTS[key]
+ )
+ return size ? { scale, format, size, ...changed } : { scale, format, ...changed }
+}
diff --git a/packages/scene-graph/src/plugin-data/fields.ts b/packages/scene-graph/src/plugin-data/fields.ts
index 16e462db4..ab07d410e 100644
--- a/packages/scene-graph/src/plugin-data/fields.ts
+++ b/packages/scene-graph/src/plugin-data/fields.ts
@@ -60,10 +60,23 @@ const exportSettingsSchema: v.GenericSchema<unknown, ExportSetting[]> = v.array(
v.pipe(
v.object({
scale: v.pipe(v.number(), v.finite()),
- format: v.custom<ExportFormatId>(isExportFormatId)
+ format: v.custom<ExportFormatId>(isExportFormatId),
+ suffix: v.optional(v.string()),
+ size: v.optional(
+ v.object({
+ type: v.picklist(['WIDTH', 'HEIGHT']),
+ value: v.pipe(v.number(), v.finite())
+ })
+ ),
+ contentsOnly: v.optional(v.boolean()),
+ useAbsoluteBounds: v.optional(v.boolean()),
+ colorProfile: v.optional(v.picklist(['DOCUMENT', 'SRGB', 'DISPLAY_P3_V4'])),
+ svgOutlineText: v.optional(v.boolean()),
+ svgIdAttribute: v.optional(v.boolean()),
+ svgSimplifyStroke: v.optional(v.boolean())
}),
// Clamp at the file boundary: imported plugin data may carry a scale the UI never produces.
- v.transform(({ scale, format }) => ({ scale: clampExportScale(scale), format }))
+ v.transform((setting) => ({ ...setting, scale: clampExportScale(setting.scale) }))
)
)
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index 05fdb4d28..6bd190ae0 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -443,9 +443,37 @@ export interface PluginDataEntry {
value: string
}
+/** A fixed width or height in pixels an export is scaled to, instead of a multiplier. */
+export interface ExportSize {
+ type: 'WIDTH' | 'HEIGHT'
+ value: number
+}
+
+/** The colour profile an export is written in; the document's own unless set. */
+export type ExportColorProfile = 'DOCUMENT' | 'SRGB' | 'DISPLAY_P3_V4'
+
+/**
+ * One export a layer keeps. The options past `scale` and `format` are Figma's and read as Figma's
+ * defaults when left out.
+ */
export interface ExportSetting {
scale: number
format: ExportFormatId
+ /** Appended to the file name. */
+ suffix?: string
+ /** A size that replaces `scale`. */
+ size?: ExportSize
+ /** Only the layer, without what overlaps it (default true). */
+ contentsOnly?: boolean
+ /** The layer's box rather than everything it draws, for text (default false). */
+ useAbsoluteBounds?: boolean
+ colorProfile?: ExportColorProfile
+ /** SVG: text as outlines rather than `<text>` (default true). */
+ svgOutlineText?: boolean
+ /** SVG: every layer's name as its element's `id` (default false). */
+ svgIdAttribute?: boolean
+ /** SVG: strokes as strokes where possible rather than masked outlines (default true). */
+ svgSimplifyStroke?: boolean
}
export interface PluginRelaunchDataEntry {
diff --git a/packages/vue/src/document/export/helpers.ts b/packages/vue/src/document/export/helpers.ts
index 39c62d8fc..057d94576 100644
--- a/packages/vue/src/document/export/helpers.ts
+++ b/packages/vue/src/document/export/helpers.ts
@@ -1,10 +1,16 @@
+import { omit } from 'es-toolkit/object'
+import { isEqual } from 'es-toolkit/predicate'
import { computed } from 'vue'
import type { ComputedRef } from 'vue'
import type { Editor } from '@open-pencil/core'
import { BUILTIN_IO_FORMATS, IORegistry, type BuiltinIOFormatId } from '@open-pencil/core/io'
import type { ExportSetting, PluginDataEntry } from '@open-pencil/scene-graph'
-import { EXPORT_FORMAT_IDS, type ExportFormatId } from '@open-pencil/scene-graph/export-format'
+import {
+ compactExportSetting,
+ EXPORT_FORMAT_IDS,
+ type ExportFormatId
+} from '@open-pencil/scene-graph/export-format'
import {
MAX_EXPORT_SCALE,
MIN_EXPORT_SCALE,
@@ -87,7 +93,7 @@ export function createExportTargetState(editor: Editor, selectedIds: ComputedRef
const first = editor.graph.getNode(firstId)?.exportSettings ?? []
return otherIds.some((id) => {
const settings = editor.graph.getNode(id)?.exportSettings ?? []
- return !exportSettingsEqual(first, settings)
+ return !isEqual(first.map(compactExportSetting), settings.map(compactExportSetting))
})
})
@@ -103,14 +109,6 @@ export function createExportTargetState(editor: Editor, selectedIds: ComputedRef
}
}
-function exportSettingsEqual(a: ExportSetting[], b: ExportSetting[]) {
- if (a.length !== b.length) return false
- return a.every((setting, index) => {
- const other = b[index]
- return setting.scale === other.scale && setting.format === other.format
- })
-}
-
function nextExportSetting(settings: ExportSetting[]): ExportSetting {
const last = settings.at(-1)
if (!last) return createDefaultExportSetting()
@@ -172,7 +170,8 @@ export function createExportSettingActions(editor: Editor, targetIds: ComputedRe
function updateScale(index: number, scale: number) {
updateEveryTarget(editor, targetIds, 'Update export scale', (settings) =>
settings.map((setting, i) =>
- i === index ? { ...setting, scale: clampExportScale(scale) } : setting
+ // A scale replaces a fixed width or height, which the panel has no field for.
+ i === index ? { ...omit(setting, ['size']), scale: clampExportScale(scale) } : setting
)
)
}
diff --git a/packages/vue/tests/document/export/actions.test.ts b/packages/vue/tests/document/export/actions.test.ts
new file mode 100644
index 000000000..efa6a0869
--- /dev/null
+++ b/packages/vue/tests/document/export/actions.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, test } from 'bun:test'
+
+import { computed } from 'vue'
+
+import { createEditor } from '@open-pencil/core'
+
+import { createExportSettingActions } from '#vue/document/export/helpers'
+
+describe('createExportSettingActions', () => {
+ test('a chosen scale replaces a fixed width or height and keeps the other options', () => {
+ const editor = createEditor()
+ const rect = editor.graph.createNode('RECTANGLE', editor.state.currentPageId, {
+ width: 40,
+ height: 20,
+ exportSettings: [
+ { scale: 1, format: 'png', size: { type: 'WIDTH', value: 300 }, contentsOnly: false }
+ ]
+ })
+ const { updateScale } = createExportSettingActions(
+ editor,
+ computed(() => [rect.id])
+ )
+
+ updateScale(0, 2)
+
+ expect(editor.graph.getNode(rect.id)?.exportSettings).toEqual([
+ { scale: 2, format: 'png', contentsOnly: false }
+ ])
+ })
+})
diff --git a/src/app/automation/bridge/export-handlers.ts b/src/app/automation/bridge/export-handlers.ts
index cc6673210..51583005f 100644
--- a/src/app/automation/bridge/export-handlers.ts
+++ b/src/app/automation/bridge/export-handlers.ts
@@ -1,5 +1,6 @@
import { fromUint8Array } from 'js-base64'
+import type { ExportImageOptions } from '@open-pencil/core/figma-api'
import type { RasterExportFormat } from '@open-pencil/core/io/formats/raster'
import { selectionToJSX } from '@open-pencil/design-jsx'
import { sceneNodesToTailwindJSX } from '@open-pencil/dom-css/export'
@@ -14,16 +15,14 @@ import type { EditorStore } from '@/app/editor/active-store'
export function renderAutomationImage(
store: EditorStore,
nodeIds: string[],
- scale: number,
- format: RasterExportFormat,
- pageId?: string
+ { scale = 1, format = 'PNG', pageId, useAbsoluteBounds }: ExportImageOptions
): Promise<Uint8Array | null> {
if (!store.renderer) {
throw new Error(
'This document has no canvas renderer, so it cannot be exported as an image: its canvas has not started or could not create a WebGL surface'
)
}
- return store.renderExportImage(nodeIds, scale, format, pageId)
+ return store.renderExportImage(nodeIds, scale, format, pageId, { useAbsoluteBounds })
}
type ExportArgs = { nodeIds?: string[]; scope?: 'page'; scale?: number; format?: string }
@@ -41,12 +40,10 @@ export async function handleExport(target: AutomationTarget, args: unknown): Pro
const exportArgs = args as ExportArgs | undefined
const nodeIds = exportNodeIds(target, exportArgs)
if (nodeIds.length === 0) throw new Error('No nodes to export')
- const data = await renderAutomationImage(
- store,
- nodeIds,
- exportArgs?.scale ?? 1,
- (exportArgs?.format ?? 'PNG') as RasterExportFormat
- )
+ const data = await renderAutomationImage(store, nodeIds, {
+ scale: exportArgs?.scale,
+ format: exportArgs?.format as RasterExportFormat | undefined
+ })
if (!data) throw new Error('The renderer returned no image for these layers')
const base64 = fromUint8Array(data)
return {
diff --git a/src/app/automation/bridge/figma-factory.ts b/src/app/automation/bridge/figma-factory.ts
index 9cdc27728..417c62313 100644
--- a/src/app/automation/bridge/figma-factory.ts
+++ b/src/app/automation/bridge/figma-factory.ts
@@ -37,13 +37,7 @@ export function makeFigmaFromStore(
zoom: store.state.zoom
}
api.exportImage = async (nodeIds, opts) =>
- renderAutomationImage(
- store,
- nodeIds,
- opts.scale ?? 1,
- opts.format ?? 'PNG',
- opts.pageId ?? pageId
- )
+ renderAutomationImage(store, nodeIds, { ...opts, pageId: opts.pageId ?? pageId })
if (store.renderer) api.rasterCodec = createCanvasKitRasterCodec(store.renderer.ck)
api.listAvailableFontsAsync = async () => {
const [systemFonts, familyOptions] = await Promise.all([listFonts(), listFamilies()])
diff --git a/src/app/document/export/files.ts b/src/app/document/export/files.ts
index 9dba21893..413def6af 100644
--- a/src/app/document/export/files.ts
+++ b/src/app/document/export/files.ts
@@ -107,7 +107,8 @@ export function createExportTargetActions(editor: Editor, state: EditorState, io
nodeIds: string[],
scale: number,
format: RasterExportFormat,
- pageId = state.currentPageId
+ pageId = state.currentPageId,
+ { useAbsoluteBounds = false }: { useAbsoluteBounds?: boolean } = {}
): Promise<Uint8Array<ArrayBuffer> | null> {
const renderer = editor.renderer
if (!renderer) return null
@@ -116,7 +117,8 @@ export function createExportTargetActions(editor: Editor, state: EditorState, io
const ownerPageId = findPageId(editor.graph, ids[0]) ?? pageId
return renderNodesToImage(renderer.ck, renderer, editor.graph, ownerPageId, ids, {
scale,
- format
+ format,
+ useAbsoluteBounds
})
}