Skip to content

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

9.4 KB
Raw Blame
import * as v from 'valibot'

import { behaviourSchema } from '../behaviours/schema'
import type { OkHCLPayload } from '../color/okhcl'
import { commentThreadsSchema } from '../comments/schema'
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'
import { nodeStatusSchema, statusWorkflowSchema } from '../statuses/schema'
import {
  MODE_ATTRIBUTE_PATTERN,
  TOKEN_UNITS,
  type EnabledLibraryBinding,
  type ExportSetting,
  type LayoutDirection,
  type LibraryAssetSource,
  type PluginDataEntry,
  type SourceLibraryPublication,
  type TextDirection,
  type TokenUnit
} from '../types'
import {
  jsonPluginDataField,
  textPluginDataField,
  withoutPluginData,
  type PluginDataKey
} from './field'

const DIRECTIONS = ['AUTO', 'LTR', 'RTL'] as const satisfies readonly (
  | TextDirection
  | LayoutDirection
)[]

const textPathBoxSchema: v.GenericSchema<unknown, Rect> = v.pipe(
  v.object({ x: v.number(), y: v.number(), width: v.number(), height: v.number() }),
  v.check(
    ({ x, y, width, height }) => Number.isFinite(x + y + width + height) && width > 0 && height > 0
  )
)

/** String-valued entries of a JSON object; other entries are dropped, not rejected. */
const boundVariablesSchema = v.pipe(
  v.custom<Record<string, unknown>>(
    (value) => typeof value === 'object' && value !== null && !Array.isArray(value)
  ),
  v.transform((value) =>
    Object.fromEntries(
      Object.entries(value).filter(
        (entry): entry is [string, string] => typeof entry[1] === 'string'
      )
    )
  )
)

/** Every entry must be valid, or the whole value is ignored in favour of native settings. */
const exportSettingsSchema: v.GenericSchema<unknown, ExportSetting[]> = v.array(
  v.pipe(
    v.object({
      scale: v.pipe(v.number(), v.finite()),
      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((setting) => ({ ...setting, scale: clampExportScale(setting.scale) }))
  )
)

const librarySourceSchema: v.GenericSchema<unknown, LibraryAssetSource> = v.pipe(
  v.object({
    identity: v.object({ libraryId: v.string(), assetKey: v.string(), revisionId: v.string() }),
    sourceNodeId: v.optional(v.unknown()),
    readOnly: v.optional(v.unknown())
  }),
  v.transform(({ identity, sourceNodeId, readOnly }) => ({
    identity,
    sourceNodeId: typeof sourceNodeId === 'string' ? sourceNodeId : null,
    readOnly: readOnly === true
  }))
)

const enabledLibrarySchema = v.object({
  libraryId: v.string(),
  revisionId: v.string(),
  enabled: v.optional(v.unknown())
})

/** Invalid entries are skipped one by one, so one bad binding keeps the others. */
const enabledLibrariesSchema: v.GenericSchema<unknown, EnabledLibraryBinding[]> = v.pipe(
  v.array(v.unknown()),
  v.transform((items) =>
    items.flatMap((item) => {
      const parsed = v.safeParse(enabledLibrarySchema, item)
      if (!parsed.success) return []
      const { libraryId, revisionId, enabled } = parsed.output
      return [{ libraryId, revisionId, enabled: enabled === true }]
    })
  )
)

// Shape only. Whether a string is valid CSS is checked where it is written into a stylesheet.
const cssTextSchema = v.pipe(v.string(), v.trim(), v.nonEmpty(), v.maxLength(1000))

/** Token fields Figma has no slot for, with mode ids as the file spells them. */
export interface StoredToken {
  unit?: TokenUnit
  expressions?: Record<string, { css: string; resolved?: number }>
}

const tokenSchema: v.GenericSchema<unknown, StoredToken> = v.object({
  unit: v.optional(v.picklist(TOKEN_UNITS)),
  expressions: v.optional(
    v.record(
      v.string(),
      v.object({ css: cssTextSchema, resolved: v.optional(v.pipe(v.number(), v.finite())) })
    )
  )
})

const okhclSchema: v.GenericSchema<unknown, OkHCLPayload> = v.object({
  version: v.literal(1),
  kind: v.picklist(['fill', 'stroke']),
  index: v.number(),
  color: v.object({
    h: v.number(),
    c: v.number(),
    l: v.number(),
    a: v.fallback(v.optional(v.number()), undefined)
  })
})

const sourceLibraryPublicationSchema: v.GenericSchema<unknown, SourceLibraryPublication> = v.object(
  {
    libraryId: v.string(),
    revisionId: v.string(),
    name: v.string(),
    catalogSource: v.optional(v.string())
  }
)

/**
 * Every plugin-data entry OpenPencil writes under {@link OPEN_PENCIL_PLUGIN_ID}: state Figma's
 * format has no field for. Add a key here, never as a string elsewhere, so reading and writing
 * it share one schema.
 */
export const OPEN_PENCIL_PLUGIN_DATA = {
  /** A text node's direction, on TEXT nodes. */
  textDirection: textPluginDataField('textDirection', 'format', DIRECTIONS),
  /** An auto-layout frame's direction. */
  layoutDirection: textPluginDataField('layoutDirection', 'format', DIRECTIONS),
  /** Marks a component set Figma would read as a plain frame. */
  nodeType: textPluginDataField('nodeType', 'format', ['COMPONENT_SET']),
  /** Variable bindings by field path, including those Figma cannot store natively. */
  boundVariables: jsonPluginDataField('boundVariables', 'format', boundVariablesSchema),
  exportSettings: jsonPluginDataField('exportSettings', 'format', exportSettingsSchema),
  /** The node-local rect a TEXT_PATH layout maps onto, which Kiwi has no field for. */
  textPathBox: jsonPluginDataField('textPathBox', 'format', textPathBoxSchema),
  /** The library asset a node was inserted from. */
  librarySource: jsonPluginDataField('librarySource', 'bookkeeping', librarySourceSchema),
  /**
   * The document root's id, on the DOCUMENT node, whose own GUID is always Figma's `0:0`; the
   * root keeps it across a save as every layer keeps its GUID.
   */
  documentId: jsonPluginDataField(
    'documentId',
    'bookkeeping',
    v.pipe(v.string(), v.nonEmpty(), v.maxLength(64))
  ),
  /** Libraries enabled for the document, on the DOCUMENT node. */
  enabledLibraries: jsonPluginDataField('enabledLibraries', 'bookkeeping', enabledLibrariesSchema),
  /** The library this document publishes as, on the DOCUMENT node. */
  sourceLibraryPublication: jsonPluginDataField(
    'sourceLibraryPublication',
    'bookkeeping',
    sourceLibraryPublicationSchema
  ),
  /** Canvas comment threads, deleted ones included, on the DOCUMENT node. */
  comments: jsonPluginDataField('comments', 'bookkeeping', commentThreadsSchema),
  /** 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. */
  token: jsonPluginDataField('token', 'format', tokenSchema),
  /** Mode conditions by mode id, on each VARIABLE_SET. */
  modeConditions: jsonPluginDataField(
    'modeConditions',
    'format',
    v.record(v.string(), cssTextSchema)
  ),
  /** The attribute that switches manual modes, on each VARIABLE_SET. */
  modeAttribute: jsonPluginDataField(
    'modeAttribute',
    'format',
    v.pipe(v.string(), v.trim(), v.maxLength(100), v.regex(MODE_ATTRIBUTE_PATTERN))
  ),
  /** One entry per paint picked in OkHCL, so the picker reopens on the same coordinates. */
  okhcl: jsonPluginDataField('okhcl', 'content', okhclSchema),
  /** How a main component or component set behaves as a control in preview. */
  behaviour: jsonPluginDataField('behaviour', 'content', behaviourSchema),
  /** The icon a frame draws, such as `lucide:home`, on the frame its paths are in. */
  icon: jsonPluginDataField('icon', 'content', iconSchema),
  /** Which of an icon path's paints its icon's color sets, on each path the source drew in it. */
  iconTint: jsonPluginDataField('iconTint', 'content', iconTintSchema),
  /** One entry per paint that draws a shader, matched to its image paint by the frame's hash. */
  shader: jsonPluginDataField('shader', 'content', shaderPaintSchema)
} satisfies Record<string, PluginDataKey>

const NOT_CONTENT = Object.values(OPEN_PENCIL_PLUGIN_DATA).filter(
  (field) => field.role !== 'content'
)

/**
 * A node's plugin data that is part of its content, in a stable order: OpenPencil's content
 * fields and every other plugin's entries, which the node carries wherever it goes. Format
 * copies of node fields and bookkeeping are left out.
 */
export function contentPluginData(entries: readonly PluginDataEntry[]): PluginDataEntry[] {
  return withoutPluginData(entries, NOT_CONTENT).sort(
    (a, b) => a.pluginId.localeCompare(b.pluginId) || a.key.localeCompare(b.key)
  )
}