@pairdraw/scene-graph 0.17.0 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/color/index.d.ts.map +1 -1
- package/dist/color/index.js.map +1 -1
- package/dist/copy.d.ts.map +1 -1
- package/dist/copy.js +6 -3
- package/dist/copy.js.map +1 -1
- package/dist/effects.d.ts +16 -0
- package/dist/effects.d.ts.map +1 -0
- package/dist/effects.js +78 -0
- package/dist/effects.js.map +1 -0
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +5 -0
- package/dist/graph.js.map +1 -1
- package/dist/node-defaults.d.ts.map +1 -1
- package/dist/node-defaults.js +4 -1
- package/dist/node-defaults.js.map +1 -1
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +5 -0
- package/dist/preview.js.map +1 -1
- package/dist/variables/index.d.ts.map +1 -1
- package/dist/variables/index.js +14 -2
- package/dist/variables/index.js.map +1 -1
- package/package.json +6 -1
- package/src/color/index.ts +1 -0
- package/src/copy.ts +6 -3
- package/src/effects.ts +76 -0
- package/src/graph.ts +4 -0
- package/src/node-defaults.ts +4 -1
- package/src/preview.ts +4 -0
- package/src/variables/index.ts +20 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/color/index.ts"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/color/index.ts"],"mappings":";;;;;;;;iBAegB,cAAc,gBAAgB;;iBAS9B,WAAW,gBAAgB;iBAI3B,WAAW,OAAO;iBAIlB,YAAY,OAAO,OAAO;iBAM1B,cAAc,OAAO;iBAIrB,eAAe,OAAO;;;;;;iBAStB,WAAW,OAAO;iBAIlB,kBAAkB,OAAO;iBAOzB,eAAe,WAAW,WAAW,WAAW,aAAQ;iBAIxD,YAAY,gBAAgB;;;;;;;;;;;iBAY5B,cAAc,IAAI,OAAO,IAAI"}
|
package/dist/color/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/color/index.ts"],"sourcesContent":["export * from './contrast'\nexport * from './management'\nexport { normalizeColor } from './normalize'\nexport * from './okhcl'\n\nimport { parse, formatHex, formatHex8, formatRgb, converter, differenceEuclidean } from 'culori'\n\nimport { BLACK } from '../constants'\nimport type { Color } from '../primitives'\nimport { normalizeColor } from './normalize'\n\nconst toRGB = converter('rgb')\n\n/** A CSS color, or null when `input` is not one. */\nexport function tryParseColor(input: string): Color | null {\n const parsed = parse(input)\n if (!parsed) return null\n const rgb = toRGB(parsed)\n // culori leaves a `none` channel out, which normalizing reads as zero.\n return normalizeColor({ r: rgb.r, g: rgb.g, b: rgb.b, a: parsed.alpha })\n}\n\n/** A CSS color, or black when `input` is not one. */\nexport function parseColor(input: string): Color {\n return tryParseColor(input) ?? { ...BLACK }\n}\n\nexport function colorToHex(color: Color): string {\n return formatHex({ mode: 'rgb', r: color.r, g: color.g, b: color.b }).toUpperCase()\n}\n\nexport function colorToHex8(color: Color, alpha?: number): string {\n const a = alpha ?? color.a\n if (a >= 1) return colorToHex(color)\n return formatHex8({ mode: 'rgb', r: color.r, g: color.g, b: color.b, alpha: a }).toUpperCase()\n}\n\nexport function colorToHexRaw(color: Color): string {\n return colorToHex(color).slice(1)\n}\n\nexport function colorToRgba255(color: Color) {\n return {\n r: Math.round(color.r * 255),\n g: Math.round(color.g * 255),\n b: Math.round(color.b * 255),\n a: color.a\n }\n}\n\nexport function colorToCSS(color: Color): string {\n return formatRgb({ mode: 'rgb', r: color.r, g: color.g, b: color.b, alpha: color.a })\n}\n\nexport function colorToCSSCompact(color: Color): string {\n const { r, g, b } = colorToRgba255(color)\n const a = Number(color.a.toFixed(3))\n if (a >= 1) return `rgb(${r},${g},${b})`\n return `rgba(${r},${g},${b},${a})`\n}\n\nexport function rgba255ToColor(r: number, g: number, b: number, a = 1): Color {\n return { r: r / 255, g: g / 255, b: b / 255, a }\n}\n\nexport function colorToFill(color: string | Color) {\n const rgba = typeof color === 'string' ? parseColor(color) : color\n return {\n type: 'SOLID' as const,\n color: { r: rgba.r, g: rgba.g, b: rgba.b, a: rgba.a },\n opacity: rgba.a,\n visible: true\n }\n}\n\nconst euclideanRGB255 = differenceEuclidean('rgb')\n\nexport function colorDistance(c1: Color, c2: Color): number {\n return (\n euclideanRGB255(\n { mode: 'rgb', r: c1.r, g: c1.g, b: c1.b },\n { mode: 'rgb', r: c2.r, g: c2.g, b: c2.b }\n ) * 255\n )\n}\nexport * from './schema'\n"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/color/index.ts"],"sourcesContent":["export * from './contrast'\nexport * from './management'\nexport { normalizeColor } from './normalize'\nexport * from './okhcl'\nexport { colorSchema } from './schema'\n\nimport { parse, formatHex, formatHex8, formatRgb, converter, differenceEuclidean } from 'culori'\n\nimport { BLACK } from '../constants'\nimport type { Color } from '../primitives'\nimport { normalizeColor } from './normalize'\n\nconst toRGB = converter('rgb')\n\n/** A CSS color, or null when `input` is not one. */\nexport function tryParseColor(input: string): Color | null {\n const parsed = parse(input)\n if (!parsed) return null\n const rgb = toRGB(parsed)\n // culori leaves a `none` channel out, which normalizing reads as zero.\n return normalizeColor({ r: rgb.r, g: rgb.g, b: rgb.b, a: parsed.alpha })\n}\n\n/** A CSS color, or black when `input` is not one. */\nexport function parseColor(input: string): Color {\n return tryParseColor(input) ?? { ...BLACK }\n}\n\nexport function colorToHex(color: Color): string {\n return formatHex({ mode: 'rgb', r: color.r, g: color.g, b: color.b }).toUpperCase()\n}\n\nexport function colorToHex8(color: Color, alpha?: number): string {\n const a = alpha ?? color.a\n if (a >= 1) return colorToHex(color)\n return formatHex8({ mode: 'rgb', r: color.r, g: color.g, b: color.b, alpha: a }).toUpperCase()\n}\n\nexport function colorToHexRaw(color: Color): string {\n return colorToHex(color).slice(1)\n}\n\nexport function colorToRgba255(color: Color) {\n return {\n r: Math.round(color.r * 255),\n g: Math.round(color.g * 255),\n b: Math.round(color.b * 255),\n a: color.a\n }\n}\n\nexport function colorToCSS(color: Color): string {\n return formatRgb({ mode: 'rgb', r: color.r, g: color.g, b: color.b, alpha: color.a })\n}\n\nexport function colorToCSSCompact(color: Color): string {\n const { r, g, b } = colorToRgba255(color)\n const a = Number(color.a.toFixed(3))\n if (a >= 1) return `rgb(${r},${g},${b})`\n return `rgba(${r},${g},${b},${a})`\n}\n\nexport function rgba255ToColor(r: number, g: number, b: number, a = 1): Color {\n return { r: r / 255, g: g / 255, b: b / 255, a }\n}\n\nexport function colorToFill(color: string | Color) {\n const rgba = typeof color === 'string' ? parseColor(color) : color\n return {\n type: 'SOLID' as const,\n color: { r: rgba.r, g: rgba.g, b: rgba.b, a: rgba.a },\n opacity: rgba.a,\n visible: true\n }\n}\n\nconst euclideanRGB255 = differenceEuclidean('rgb')\n\nexport function colorDistance(c1: Color, c2: Color): number {\n return (\n euclideanRGB255(\n { mode: 'rgb', r: c1.r, g: c1.g, b: c1.b },\n { mode: 'rgb', r: c2.r, g: c2.g, b: c2.b }\n ) * 255\n )\n}\nexport * from './schema'\n"],"mappings":";;;;;;;;AAYA,MAAM,QAAQ,UAAU,KAAK;;AAG7B,SAAgB,cAAc,OAA6B;CACzD,MAAM,SAAS,MAAM,KAAK;CAC1B,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,MAAM,MAAM,MAAM;CAExB,OAAO,eAAe;EAAE,GAAG,IAAI;EAAG,GAAG,IAAI;EAAG,GAAG,IAAI;EAAG,GAAG,OAAO;CAAM,CAAC;AACzE;;AAGA,SAAgB,WAAW,OAAsB;CAC/C,OAAO,cAAc,KAAK,KAAK,EAAE,GAAG,MAAM;AAC5C;AAEA,SAAgB,WAAW,OAAsB;CAC/C,OAAO,UAAU;EAAE,MAAM;EAAO,GAAG,MAAM;EAAG,GAAG,MAAM;EAAG,GAAG,MAAM;CAAE,CAAC,CAAC,CAAC,YAAY;AACpF;AAEA,SAAgB,YAA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;EAAE;EACpD,SAAS,KAAK;EACd,SAAS;CACX;AACF;AAEA,MAAM,kBAAkB,oBAAoB,KAAK;AAEjD,SAAgB,cAAc,IAAW,IAAmB;CAC1D,OACE,gBACE;EAAE,MAAM;EAAO,GAAG,GAAG;EAAG,GAAG,GAAG;EAAG,GAAG,GAAG;CAAE,GACzC;EAAE,MAAM;EAAO,GAAG,GAAG;EAAG,GAAG,GAAG;EAAG,GAAG,GAAG;CAAE,CAC3C,IAAI;AAER"}
|
package/dist/copy.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"copy.d.ts","names":[],"sources":["../src/copy.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"copy.d.ts","names":[],"sources":["../src/copy.ts"],"mappings":";;;iBAiCgB,SAAS,UAAU,MAAM,GAAG,IAAI;iBAehC,WAAW,GAAG,SAAS;iBAQvB,WAAW,GAAG,SAAS;iBAWvB,aAAa,GAAG,WAAW;;iBA6B3B,eAAe,kBAAkB,QAAQ,GAAG,MAAM,IAAI;;iBAMtD,kBAAkB,cAAc;iBAKhC,UAAU,OAAO,SAAS;iBAI1B,YAAY,SAAS,WAAW;iBAIhC,YAAY,SAAS,WAAW;iBAIhC,gBAAgB,OAAO,eAAe;iBAItC,cAAc,MAAM,aAAa;iBAajC,kBAAkB,OAAO,iBAAiB;;;;;;;iBAU1C,sBACd,MAAM,YACN,aACA,aACA,aACA,aACA,aACA,cACC;iBAoBa,uBACd,OAAO,gBACP,aACA,aACA,aACA,aACA,aACA,cACC;;;;;iBAUa,mBAAmB,OAAO,gBAAgB,YAAY,aAAa;;iBAmCnE,kBAAkB,QAAQ,4BAA4B;iBAatD,sBAAsB,UAAU,oBAAoB;;;;;;;;KAiBxD;iBAUI,eACd,KAAK,WACL,4BACA,OAAM,gBACL,QAAQ"}
|
package/dist/copy.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { normalizeEffects } from "./effects.js";
|
|
1
2
|
import { cloneInstanceOverrideState } from "./instances/overrides.js";
|
|
2
3
|
import { createDefaultSourceMetadata } from "./node-defaults.js";
|
|
3
4
|
import { geometryCommandCoordCount } from "./geometry.js";
|
|
@@ -35,10 +36,12 @@ function copyStroke(s) {
|
|
|
35
36
|
}
|
|
36
37
|
function copyEffect(e) {
|
|
37
38
|
if (e.type === "SHADER") return structuredClone(e);
|
|
39
|
+
const normalized = normalizeEffects([e])[0] ?? e;
|
|
40
|
+
if (normalized.type === "SHADER") return structuredClone(normalized);
|
|
38
41
|
return {
|
|
39
|
-
...
|
|
40
|
-
color: { ...
|
|
41
|
-
offset: { ...
|
|
42
|
+
...normalized,
|
|
43
|
+
color: { ...normalized.color },
|
|
44
|
+
offset: { ...normalized.offset }
|
|
42
45
|
};
|
|
43
46
|
}
|
|
44
47
|
function copyStyleRun(r) {
|
package/dist/copy.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"copy.js","names":[],"sources":["../src/copy.ts"],"sourcesContent":["/**\n * Typed shallow-copy helpers for Fill, Stroke, Effect, and StyleRun.\n *\n * These replace `structuredClone` for known scene-graph array types,\n * avoiding the ~24× overhead of the generic deep-clone algorithm.\n * Each helper spreads the top-level object and any nested objects\n * (color, offset, gradientStops, dashPattern, style) to ensure\n * no shared references between source and copy.\n */\n\nimport { geometryCommandCoordCount } from './geometry'\nimport { cloneInstanceOverrideState } from './instances/overrides'\nimport { createDefaultSourceMetadata } from './node-defaults'\nimport type {\n ArcData,\n ComponentPropertyDefinition,\n ConnectorEndpoint,\n Effect,\n DerivedTextGlyph,\n Fill,\n GeometryPath,\n GradientStop,\n LayoutGrid,\n SceneNode,\n Stroke,\n StyleRun\n} from './types'\nimport { cloneVectorNetwork } from './vector-network'\n\n// --- Individual copy functions ---\n\n/** Generic over the paint shape so a stroke keeps its own fields while the paint deep-copies. */\nexport function copyFill<T extends Fill>(f: T): T {\n const copy: T = { ...f, color: { ...f.color } }\n if (f.gradientStops) copy.gradientStops = f.gradientStops.map(copyGradientStop)\n if (f.gradientTransform) copy.gradientTransform = { ...f.gradientTransform }\n if (f.meshPoints) {\n copy.meshPoints = f.meshPoints.map((point) => ({\n position: { ...point.position },\n color: { ...point.color }\n }))\n }\n if (f.patternSpacing) copy.patternSpacing = { ...f.patternSpacing }\n if (f.noiseSize) copy.noiseSize = { ...f.noiseSize }\n return copy\n}\n\nexport function copyStroke(s: Stroke): Stroke {\n const copy = copyFill(s)\n if (s.dashPattern) {\n copy.dashPattern = [...s.dashPattern]\n }\n return copy\n}\n\nexport function copyEffect(e: Effect): Effect {\n if (e.type === 'SHADER') return structuredClone(e)\n return {\n ...e,\n color: { ...e.color },\n offset: { ...e.offset }\n }\n}\n\nexport function copyStyleRun(r: StyleRun): StyleRun {\n const copy: StyleRun = {\n ...r,\n style: {\n ...r.style,\n fills: r.style.fills ? r.style.fills.map(copyFill) : undefined,\n textDecorationFills: r.style.textDecorationFills\n ? r.style.textDecorationFills.map(copyFill)\n : undefined,\n fontVariations: r.style.fontVariations\n ? r.style.fontVariations.map((v) => ({ ...v }))\n : undefined,\n fontFeatures: r.style.fontFeatures ? r.style.fontFeatures.map((v) => ({ ...v })) : undefined\n }\n }\n if (r.style.hyperlink) copy.style.hyperlink = { ...r.style.hyperlink }\n if (r.style.lineHeight) copy.style.lineHeight = { ...r.style.lineHeight }\n if (r.style.letterSpacing) copy.style.letterSpacing = { ...r.style.letterSpacing }\n if (r.style.boundVariables) copy.style.boundVariables = { ...r.style.boundVariables }\n if (r.style.variableBindingScales)\n copy.style.variableBindingScales = { ...r.style.variableBindingScales }\n return copy\n}\n\n// --- Array copy functions ---\n\nconst internalCopySources = new WeakMap<object, object>()\n\n/** Record immutable lineage for an internal deep copy without sharing mutable values. */\nexport function markCopySource<T extends object>(source: T, copy: T): T {\n internalCopySources.set(copy, internalCopySources.get(source) ?? source)\n return copy\n}\n\n/** Compare internal deep copies in O(1) without traversing large paint or text payloads. */\nexport function hasSameCopySource(left: object, right: object): boolean {\n if (left === right) return true\n return (internalCopySources.get(left) ?? left) === (internalCopySources.get(right) ?? right)\n}\n\nexport function copyFills(fills: Fill[]): Fill[] {\n return fills.map(copyFill)\n}\n\nexport function copyStrokes(strokes: Stroke[]): Stroke[] {\n return strokes.map(copyStroke)\n}\n\nexport function copyEffects(effects: Effect[]): Effect[] {\n return effects.map(copyEffect)\n}\n\nexport function copyLayoutGrids(grids: LayoutGrid[]): LayoutGrid[] {\n return grids.map((grid) => ({ ...grid, color: grid.color ? { ...grid.color } : undefined }))\n}\n\nexport function copyStyleRuns(runs: StyleRun[]): StyleRun[] {\n return runs.map(copyStyleRun)\n}\n\n/** Keep path-level fills across copy/scale/transform (resize snapshots). */\nfunction withPathPaintMeta(path: GeometryPath, commandsBlob: Uint8Array): GeometryPath {\n return {\n windingRule: path.windingRule,\n commandsBlob,\n ...(path.fills ? { fills: copyFills(path.fills) } : {})\n }\n}\n\nexport function copyGeometryPaths(paths: GeometryPath[]): GeometryPath[] {\n return paths.map((p) => withPathPaintMeta(p, p.commandsBlob.slice()))\n}\n\n/**\n * Affine-transform every coordinate pair in a path command blob (returns a\n * copy): (x, y) → (m00·x + m01·y + tx, m10·x + m11·y + ty).\n * Command layout: 1=move/2=line (1 pair), 3=quad (2 pairs), 4=cubic (3 pairs)\n * — font-glyph blobs are quad-heavy, so skipping command 3 desyncs the walk.\n */\nexport function transformGeometryBlob(\n blob: Uint8Array,\n m00: number,\n m01: number,\n m10: number,\n m11: number,\n tx = 0,\n ty = 0\n): Uint8Array {\n const out = blob.slice()\n const dv = new DataView(out.buffer, out.byteOffset, out.byteLength)\n let offset = 0\n while (offset < out.length) {\n const command = out[offset++]\n const coords = geometryCommandCoordCount(command)\n if (coords == null) break\n for (let i = 0; i < coords; i++) {\n if (offset + 8 > out.length) break\n const x = dv.getFloat32(offset, true)\n const y = dv.getFloat32(offset + 4, true)\n dv.setFloat32(offset, m00 * x + m01 * y + tx, true)\n dv.setFloat32(offset + 4, m10 * x + m11 * y + ty, true)\n offset += 8\n }\n }\n return out\n}\n\nexport function transformGeometryPaths(\n paths: GeometryPath[],\n m00: number,\n m01: number,\n m10: number,\n m11: number,\n tx = 0,\n ty = 0\n): GeometryPath[] {\n return paths.map((g) =>\n withPathPaintMeta(g, transformGeometryBlob(g.commandsBlob, m00, m01, m10, m11, tx, ty))\n )\n}\n\n/**\n * Scale path command blob coordinates by (sx, sy).\n * Identity scale returns a deep copy (same as copyGeometryPaths).\n */\nexport function scaleGeometryPaths(paths: GeometryPath[], sx: number, sy: number): GeometryPath[] {\n if (sx === 1 && sy === 1) return copyGeometryPaths(paths)\n return transformGeometryPaths(paths, sx, 0, 0, sy)\n}\n\n// --- Internal helpers ---\n\n/** Copy an optional array: non-empty → mapped, empty → [], undefined → undefined. */\nfunction copyOpt<T, U>(arr: T[] | undefined, fn: (arr: T[]) => U[]): U[] | undefined {\n if (arr === undefined) return undefined\n return arr.length > 0 ? fn(arr) : []\n}\n\nfunction copyGradientStop(gs: GradientStop): GradientStop {\n return { color: { ...gs.color }, position: gs.position }\n}\n\nfunction copySpread<T extends object>(arr: T[] | undefined): T[] {\n return arr?.map((item) => ({ ...item })) ?? []\n}\n\nfunction copyPropertyDefs(\n defs: ComponentPropertyDefinition[] | undefined\n): ComponentPropertyDefinition[] {\n return (\n defs?.map((d) => ({\n ...d,\n variantOptions: d.variantOptions ? [...d.variantOptions] : undefined,\n preferredValues: d.preferredValues ? [...d.preferredValues] : undefined,\n slotSettings: d.slotSettings ? { ...d.slotSettings } : undefined\n })) ?? []\n )\n}\n\n/** Deep-copy path-text glyphs (fresh commandsBlob buffers). */\nexport function copyDerivedGlyphs(glyphs: DerivedTextGlyph[] | null): DerivedTextGlyph[] | null {\n return glyphs\n ? glyphs.map((g) => ({\n ...g,\n commandsBlob: new Uint8Array(g.commandsBlob),\n ...(g.emojiCodePoints ? { emojiCodePoints: [...g.emojiCodePoints] } : {})\n }))\n : null\n}\n\n// --- Complex structure copy functions ---\n// These replace structuredClone for known types, avoiding its ~24× overhead.\n\nexport function copyConnectorEndpoint(endpoint: ConnectorEndpoint): ConnectorEndpoint {\n return { ...endpoint, position: { ...endpoint.position } }\n}\n\nfunction copyArcData(a: ArcData): ArcData {\n return { startingAngle: a.startingAngle, endingAngle: a.endingAngle, innerRadius: a.innerRadius }\n}\n\n// --- Deep-copy clone props ---\n\n/**\n * Build the init props for a deep-copy clone of `src`.\n * Shares logic between SceneGraph.cloneTree and instance child cloning.\n * Explicitly deep-copies all mutable object/array fields that `...rest`\n * would otherwise share by reference. When adding a mutable SceneNode field,\n * add its copy behavior here or document why sharing is intentional.\n */\nexport type NodeCloneMode = 'deep' | 'fig-import'\n\n/** A text's line height and letter spacing, copied so a clone never shares them. */\nfunction copyTextLengths(src: SceneNode): Pick<SceneNode, 'lineHeight' | 'letterSpacing'> {\n return {\n lineHeight: src.lineHeight && { ...src.lineHeight },\n letterSpacing: { ...src.letterSpacing }\n }\n}\n\nexport function cloneNodeProps(\n src: SceneNode,\n componentId: string | null,\n mode: NodeCloneMode = 'deep'\n): Partial<SceneNode> {\n const { id: _, parentId: _p, childIds: _c, ...rest } = src\n if (mode === 'fig-import') {\n return {\n ...rest,\n ...(componentId !== null ? { componentId } : {}),\n source: createDefaultSourceMetadata(),\n boundVariables: { ...src.boundVariables },\n variableBindingScales: { ...src.variableBindingScales },\n variableAssignmentScales: { ...src.variableAssignmentScales },\n variableModes: { ...src.variableModes },\n instanceOverrides: cloneInstanceOverrideState(src.instanceOverrides),\n componentPropertyAssignments: { ...src.componentPropertyAssignments },\n\n componentPropertyValues: { ...src.componentPropertyValues }\n }\n }\n return {\n ...rest,\n ...(componentId !== null ? { componentId } : {}),\n boundVariables: { ...src.boundVariables },\n variableBindingScales: { ...src.variableBindingScales },\n variableAssignmentScales: { ...src.variableAssignmentScales },\n variableModes: { ...src.variableModes },\n instanceOverrides: cloneInstanceOverrideState(src.instanceOverrides),\n fills: copyOpt(src.fills, (value) => markCopySource(value, copyFills(value))),\n\n strokes: copyOpt(src.strokes, (value) => markCopySource(value, copyStrokes(value))),\n effects: copyOpt(src.effects, (value) => markCopySource(value, copyEffects(value))),\n layoutGrids: copyOpt(src.layoutGrids, copyLayoutGrids),\n guides: copyOpt(src.guides, (guides) => guides.map((guide) => ({ ...guide }))),\n styleRuns: copyOpt(src.styleRuns, (value) => markCopySource(value, copyStyleRuns(value))),\n // Generated instance descendants have no independent Figma provenance. Retaining the source\n // component's opaque raw payload here duplicates megabytes of metadata per instance.\n source: componentId === null ? structuredClone(src.source) : createDefaultSourceMetadata(),\n dashPattern: copyOpt(src.dashPattern, (a) => [...a]),\n fontVariations: copyOpt(src.fontVariations, (a) => a.map((v) => ({ ...v }))),\n ...copyTextLengths(src),\n fontFeatures: copyOpt(src.fontFeatures, (a) => a.map((v) => ({ ...v }))),\n textParagraphs: copyOpt(src.textParagraphs, (a) => a.map((v) => ({ ...v }))),\n textDecorationFills: copyOpt(src.textDecorationFills, copyFills),\n fillGeometry: copyOpt(src.fillGeometry, copyGeometryPaths),\n strokeGeometry: copyOpt(src.strokeGeometry, copyGeometryPaths),\n gridTemplateColumns: copySpread(src.gridTemplateColumns),\n gridTemplateRows: copySpread(src.gridTemplateRows),\n componentPropertyDefinitions: copyPropertyDefs(src.componentPropertyDefinitions),\n componentPropertyReferences: copySpread(src.componentPropertyReferences),\n componentPropertyAssignments: { ...src.componentPropertyAssignments },\n symbolLinks: copySpread(src.symbolLinks),\n variantPropSpecs: copySpread(src.variantPropSpecs),\n pluginData: copySpread(src.pluginData),\n pluginRelaunchData: copySpread(src.pluginRelaunchData),\n prototypeReactions: src.prototypeReactions.map((reaction) => structuredClone(reaction)),\n exportSettings: copySpread(src.exportSettings),\n // Generated instance descendants have no status of their own.\n status: componentId === null ? src.status : null,\n componentPropertyValues: { ...src.componentPropertyValues },\n derivedLayout: src.derivedLayout ? { ...src.derivedLayout } : null,\n arcData: src.arcData ? copyArcData(src.arcData) : null,\n vectorNetwork: src.vectorNetwork ? cloneVectorNetwork(src.vectorNetwork) : null,\n textPicture: src.textPicture ? new Uint8Array(src.textPicture) : null,\n derivedTextGlyphs: src.derivedTextGlyphs\n ? markCopySource(src.derivedTextGlyphs, copyDerivedGlyphs(src.derivedTextGlyphs) ?? [])\n : null,\n textPathData: src.textPathData ? structuredClone(src.textPathData) : null,\n textPathBox: src.textPathBox ? { ...src.textPathBox } : null,\n gridPosition: src.gridPosition ? { ...src.gridPosition } : null,\n targetAspectRatio: src.targetAspectRatio ? { ...src.targetAspectRatio } : null,\n connectorStart: src.connectorStart ? copyConnectorEndpoint(src.connectorStart) : null,\n connectorEnd: src.connectorEnd ? copyConnectorEndpoint(src.connectorEnd) : null,\n connectorControlPoints: structuredClone(src.connectorControlPoints),\n connectorCurveHandles: structuredClone(src.connectorCurveHandles),\n connectorLabelPosition: src.connectorLabelPosition ? { ...src.connectorLabelPosition } : null\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgCA,SAAgB,SAAyB,GAAS;CAChD,MAAM,OAAU;EAAE,GAAG;EAAG,OAAO,EAAE,GAAG,EAAE,MAAM;CAAE;CAC9C,IAAI,EAAE,eAAe,KAAK,gBAAgB,EAAE,cAAc,IAAI,gBAAgB;CAC9E,IAAI,EAAE,mBAAmB,KAAK,oBAAoB,EAAE,GAAG,EAAE,kBAAkB;CAC3E,IAAI,EAAE,YACJ,KAAK,aAAa,EAAE,WAAW,KAAK,WAAW;EAC7C,UAAU,EAAE,GAAG,MAAM,SAAS;EAC9B,OAAO,EAAE,GAAG,MAAM,MAAM;CAC1B,EAAE;CAEJ,IAAI,EAAE,gBAAgB,KAAK,iBAAiB,EAAE,GAAG,EAAE,eAAe;CAClE,IAAI,EAAE,WAAW,KAAK,YAAY,EAAE,GAAG,EAAE,UAAU;CACnD,OAAO;AACT;AAEA,SAAgB,WAAW,GAAmB;CAC5C,MAAM,OAAO,SAAS,CAAC;CACvB,IAAI,EAAE,aACJ,KAAK,cAAc,CAAC,GAAG,EAAE,WAAW;CAEtC,OAAO;AACT;AAEA,SAA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AAW,IAAI,gBAAgB;EACjD,YAAY,WAAW,IAAI,UAAU;EACrC,oBAAoB,WAAW,IAAI,kBAAkB;EACrD,oBAAoB,IAAI,mBAAmB,KAAK,aAAa,gBAAgB,QAAQ,CAAC;EACtF,gBAAgB,WAAW,IAAI,cAAc;EAE7C,QAAQ,gBAAgB,OAAO,IAAI,SAAS;EAC5C,yBAAyB,EAAE,GAAG,IAAI,wBAAwB;EAC1D,eAAe,IAAI,gBAAgB,EAAE,GAAG,IAAI,cAAc,IAAI;EAC9D,SAAS,IAAI,UAAU,YAAY,IAAI,OAAO,IAAI;EAClD,eAAe,IAAI,gBAAgB,mBAAmB,IAAI,aAAa,IAAI;EAC3E,aAAa,IAAI,cAAc,IAAI,WAAW,IAAI,WAAW,IAAI;EACjE,mBAAmB,IAAI,oBACnB,eAAe,IAAI,mBAAmB,kBAAkB,IAAI,iBAAiB,KAAK,CAAC,CAAC,IACpF;EACJ,cAAc,IAAI,eAAe,gBAAgB,IAAI,YAAY,IAAI;EACrE,aAAa,IAAI,cAAc,EAAE,GAAG,IAAI,YAAY,IAAI;EACxD,cAAc,IAAI,eAAe,EAAE,GAAG,IAAI,aAAa,IAAI;EAC3D,mBAAmB,IAAI,oBAAoB,EAAE,GAAG,IAAI,kBAAkB,IAAI;EAC1E,gBAAgB,IAAI,iBAAiB,sBAAsB,IAAI,cAAc,IAAI;EACjF,cAAc,IAAI,eAAe,sBAAsB,IAAI,YAAY,IAAI;EAC3E,wBAAwB,gBAAgB,IAAI,sBAAsB;EAClE,uBAAuB,gBAAgB,IAAI,qBAAqB;EAChE,wBAAwB,IAAI,yBAAyB,EAAE,GAAG,IAAI,uBAAuB,IAAI;CAC3F;AACF"}
|
|
1
|
+
{"version":3,"file":"copy.js","names":[],"sources":["../src/copy.ts"],"sourcesContent":["/**\n * Typed shallow-copy helpers for Fill, Stroke, Effect, and StyleRun.\n *\n * These replace `structuredClone` for known scene-graph array types,\n * avoiding the ~24× overhead of the generic deep-clone algorithm.\n * Each helper spreads the top-level object and any nested objects\n * (color, offset, gradientStops, dashPattern, style) to ensure\n * no shared references between source and copy.\n */\n\nimport { normalizeEffects } from './effects'\nimport { geometryCommandCoordCount } from './geometry'\nimport { cloneInstanceOverrideState } from './instances/overrides'\nimport { createDefaultSourceMetadata } from './node-defaults'\nimport type {\n ArcData,\n ComponentPropertyDefinition,\n ConnectorEndpoint,\n Effect,\n DerivedTextGlyph,\n Fill,\n GeometryPath,\n GradientStop,\n LayoutGrid,\n SceneNode,\n Stroke,\n StyleRun\n} from './types'\nimport { cloneVectorNetwork } from './vector-network'\n\n// --- Individual copy functions ---\n\n/** Generic over the paint shape so a stroke keeps its own fields while the paint deep-copies. */\nexport function copyFill<T extends Fill>(f: T): T {\n const copy: T = { ...f, color: { ...f.color } }\n if (f.gradientStops) copy.gradientStops = f.gradientStops.map(copyGradientStop)\n if (f.gradientTransform) copy.gradientTransform = { ...f.gradientTransform }\n if (f.meshPoints) {\n copy.meshPoints = f.meshPoints.map((point) => ({\n position: { ...point.position },\n color: { ...point.color }\n }))\n }\n if (f.patternSpacing) copy.patternSpacing = { ...f.patternSpacing }\n if (f.noiseSize) copy.noiseSize = { ...f.noiseSize }\n return copy\n}\n\nexport function copyStroke(s: Stroke): Stroke {\n const copy = copyFill(s)\n if (s.dashPattern) {\n copy.dashPattern = [...s.dashPattern]\n }\n return copy\n}\n\nexport function copyEffect(e: Effect): Effect {\n if (e.type === 'SHADER') return structuredClone(e)\n const normalized = normalizeEffects([e])[0] ?? e\n if (normalized.type === 'SHADER') return structuredClone(normalized)\n return {\n ...normalized,\n color: { ...normalized.color },\n offset: { ...normalized.offset }\n }\n}\n\nexport function copyStyleRun(r: StyleRun): StyleRun {\n const copy: StyleRun = {\n ...r,\n style: {\n ...r.style,\n fills: r.style.fills ? r.style.fills.map(copyFill) : undefined,\n textDecorationFills: r.style.textDecorationFills\n ? r.style.textDecorationFills.map(copyFill)\n : undefined,\n fontVariations: r.style.fontVariations\n ? r.style.fontVariations.map((v) => ({ ...v }))\n : undefined,\n fontFeatures: r.style.fontFeatures ? r.style.fontFeatures.map((v) => ({ ...v })) : undefined\n }\n }\n if (r.style.hyperlink) copy.style.hyperlink = { ...r.style.hyperlink }\n if (r.style.lineHeight) copy.style.lineHeight = { ...r.style.lineHeight }\n if (r.style.letterSpacing) copy.style.letterSpacing = { ...r.style.letterSpacing }\n if (r.style.boundVariables) copy.style.boundVariables = { ...r.style.boundVariables }\n if (r.style.variableBindingScales)\n copy.style.variableBindingScales = { ...r.style.variableBindingScales }\n return copy\n}\n\n// --- Array copy functions ---\n\nconst internalCopySources = new WeakMap<object, object>()\n\n/** Record immutable lineage for an internal deep copy without sharing mutable values. */\nexport function markCopySource<T extends object>(source: T, copy: T): T {\n internalCopySources.set(copy, internalCopySources.get(source) ?? source)\n return copy\n}\n\n/** Compare internal deep copies in O(1) without traversing large paint or text payloads. */\nexport function hasSameCopySource(left: object, right: object): boolean {\n if (left === right) return true\n return (internalCopySources.get(left) ?? left) === (internalCopySources.get(right) ?? right)\n}\n\nexport function copyFills(fills: Fill[]): Fill[] {\n return fills.map(copyFill)\n}\n\nexport function copyStrokes(strokes: Stroke[]): Stroke[] {\n return strokes.map(copyStroke)\n}\n\nexport function copyEffects(effects: Effect[]): Effect[] {\n return effects.map(copyEffect)\n}\n\nexport function copyLayoutGrids(grids: LayoutGrid[]): LayoutGrid[] {\n return grids.map((grid) => ({ ...grid, color: grid.color ? { ...grid.color } : undefined }))\n}\n\nexport function copyStyleRuns(runs: StyleRun[]): StyleRun[] {\n return runs.map(copyStyleRun)\n}\n\n/** Keep path-level fills across copy/scale/transform (resize snapshots). */\nfunction withPathPaintMeta(path: GeometryPath, commandsBlob: Uint8Array): GeometryPath {\n return {\n windingRule: path.windingRule,\n commandsBlob,\n ...(path.fills ? { fills: copyFills(path.fills) } : {})\n }\n}\n\nexport function copyGeometryPaths(paths: GeometryPath[]): GeometryPath[] {\n return paths.map((p) => withPathPaintMeta(p, p.commandsBlob.slice()))\n}\n\n/**\n * Affine-transform every coordinate pair in a path command blob (returns a\n * copy): (x, y) → (m00·x + m01·y + tx, m10·x + m11·y + ty).\n * Command layout: 1=move/2=line (1 pair), 3=quad (2 pairs), 4=cubic (3 pairs)\n * — font-glyph blobs are quad-heavy, so skipping command 3 desyncs the walk.\n */\nexport function transformGeometryBlob(\n blob: Uint8Array,\n m00: number,\n m01: number,\n m10: number,\n m11: number,\n tx = 0,\n ty = 0\n): Uint8Array {\n const out = blob.slice()\n const dv = new DataView(out.buffer, out.byteOffset, out.byteLength)\n let offset = 0\n while (offset < out.length) {\n const command = out[offset++]\n const coords = geometryCommandCoordCount(command)\n if (coords == null) break\n for (let i = 0; i < coords; i++) {\n if (offset + 8 > out.length) break\n const x = dv.getFloat32(offset, true)\n const y = dv.getFloat32(offset + 4, true)\n dv.setFloat32(offset, m00 * x + m01 * y + tx, true)\n dv.setFloat32(offset + 4, m10 * x + m11 * y + ty, true)\n offset += 8\n }\n }\n return out\n}\n\nexport function transformGeometryPaths(\n paths: GeometryPath[],\n m00: number,\n m01: number,\n m10: number,\n m11: number,\n tx = 0,\n ty = 0\n): GeometryPath[] {\n return paths.map((g) =>\n withPathPaintMeta(g, transformGeometryBlob(g.commandsBlob, m00, m01, m10, m11, tx, ty))\n )\n}\n\n/**\n * Scale path command blob coordinates by (sx, sy).\n * Identity scale returns a deep copy (same as copyGeometryPaths).\n */\nexport function scaleGeometryPaths(paths: GeometryPath[], sx: number, sy: number): GeometryPath[] {\n if (sx === 1 && sy === 1) return copyGeometryPaths(paths)\n return transformGeometryPaths(paths, sx, 0, 0, sy)\n}\n\n// --- Internal helpers ---\n\n/** Copy an optional array: non-empty → mapped, empty → [], undefined → undefined. */\nfunction copyOpt<T, U>(arr: T[] | undefined, fn: (arr: T[]) => U[]): U[] | undefined {\n if (arr === undefined) return undefined\n return arr.length > 0 ? fn(arr) : []\n}\n\nfunction copyGradientStop(gs: GradientStop): GradientStop {\n return { color: { ...gs.color }, position: gs.position }\n}\n\nfunction copySpread<T extends object>(arr: T[] | undefined): T[] {\n return arr?.map((item) => ({ ...item })) ?? []\n}\n\nfunction copyPropertyDefs(\n defs: ComponentPropertyDefinition[] | undefined\n): ComponentPropertyDefinition[] {\n return (\n defs?.map((d) => ({\n ...d,\n variantOptions: d.variantOptions ? [...d.variantOptions] : undefined,\n preferredValues: d.preferredValues ? [...d.preferredValues] : undefined,\n slotSettings: d.slotSettings ? { ...d.slotSettings } : undefined\n })) ?? []\n )\n}\n\n/** Deep-copy path-text glyphs (fresh commandsBlob buffers). */\nexport function copyDerivedGlyphs(glyphs: DerivedTextGlyph[] | null): DerivedTextGlyph[] | null {\n return glyphs\n ? glyphs.map((g) => ({\n ...g,\n commandsBlob: new Uint8Array(g.commandsBlob),\n ...(g.emojiCodePoints ? { emojiCodePoints: [...g.emojiCodePoints] } : {})\n }))\n : null\n}\n\n// --- Complex structure copy functions ---\n// These replace structuredClone for known types, avoiding its ~24× overhead.\n\nexport function copyConnectorEndpoint(endpoint: ConnectorEndpoint): ConnectorEndpoint {\n return { ...endpoint, position: { ...endpoint.position } }\n}\n\nfunction copyArcData(a: ArcData): ArcData {\n return { startingAngle: a.startingAngle, endingAngle: a.endingAngle, innerRadius: a.innerRadius }\n}\n\n// --- Deep-copy clone props ---\n\n/**\n * Build the init props for a deep-copy clone of `src`.\n * Shares logic between SceneGraph.cloneTree and instance child cloning.\n * Explicitly deep-copies all mutable object/array fields that `...rest`\n * would otherwise share by reference. When adding a mutable SceneNode field,\n * add its copy behavior here or document why sharing is intentional.\n */\nexport type NodeCloneMode = 'deep' | 'fig-import'\n\n/** A text's line height and letter spacing, copied so a clone never shares them. */\nfunction copyTextLengths(src: SceneNode): Pick<SceneNode, 'lineHeight' | 'letterSpacing'> {\n return {\n lineHeight: src.lineHeight && { ...src.lineHeight },\n letterSpacing: { ...src.letterSpacing }\n }\n}\n\nexport function cloneNodeProps(\n src: SceneNode,\n componentId: string | null,\n mode: NodeCloneMode = 'deep'\n): Partial<SceneNode> {\n const { id: _, parentId: _p, childIds: _c, ...rest } = src\n if (mode === 'fig-import') {\n return {\n ...rest,\n ...(componentId !== null ? { componentId } : {}),\n source: createDefaultSourceMetadata(),\n boundVariables: { ...src.boundVariables },\n variableBindingScales: { ...src.variableBindingScales },\n variableAssignmentScales: { ...src.variableAssignmentScales },\n variableModes: { ...src.variableModes },\n instanceOverrides: cloneInstanceOverrideState(src.instanceOverrides),\n componentPropertyAssignments: { ...src.componentPropertyAssignments },\n\n componentPropertyValues: { ...src.componentPropertyValues }\n }\n }\n return {\n ...rest,\n ...(componentId !== null ? { componentId } : {}),\n boundVariables: { ...src.boundVariables },\n variableBindingScales: { ...src.variableBindingScales },\n variableAssignmentScales: { ...src.variableAssignmentScales },\n variableModes: { ...src.variableModes },\n instanceOverrides: cloneInstanceOverrideState(src.instanceOverrides),\n fills: copyOpt(src.fills, (value) => markCopySource(value, copyFills(value))),\n\n strokes: copyOpt(src.strokes, (value) => markCopySource(value, copyStrokes(value))),\n effects: copyOpt(src.effects, (value) => markCopySource(value, copyEffects(value))),\n layoutGrids: copyOpt(src.layoutGrids, copyLayoutGrids),\n guides: copyOpt(src.guides, (guides) => guides.map((guide) => ({ ...guide }))),\n styleRuns: copyOpt(src.styleRuns, (value) => markCopySource(value, copyStyleRuns(value))),\n // Generated instance descendants have no independent Figma provenance. Retaining the source\n // component's opaque raw payload here duplicates megabytes of metadata per instance.\n source: componentId === null ? structuredClone(src.source) : createDefaultSourceMetadata(),\n dashPattern: copyOpt(src.dashPattern, (a) => [...a]),\n fontVariations: copyOpt(src.fontVariations, (a) => a.map((v) => ({ ...v }))),\n ...copyTextLengths(src),\n fontFeatures: copyOpt(src.fontFeatures, (a) => a.map((v) => ({ ...v }))),\n textParagraphs: copyOpt(src.textParagraphs, (a) => a.map((v) => ({ ...v }))),\n textDecorationFills: copyOpt(src.textDecorationFills, copyFills),\n fillGeometry: copyOpt(src.fillGeometry, copyGeometryPaths),\n strokeGeometry: copyOpt(src.strokeGeometry, copyGeometryPaths),\n gridTemplateColumns: copySpread(src.gridTemplateColumns),\n gridTemplateRows: copySpread(src.gridTemplateRows),\n componentPropertyDefinitions: copyPropertyDefs(src.componentPropertyDefinitions),\n componentPropertyReferences: copySpread(src.componentPropertyReferences),\n componentPropertyAssignments: { ...src.componentPropertyAssignments },\n symbolLinks: copySpread(src.symbolLinks),\n variantPropSpecs: copySpread(src.variantPropSpecs),\n pluginData: copySpread(src.pluginData),\n pluginRelaunchData: copySpread(src.pluginRelaunchData),\n prototypeReactions: src.prototypeReactions.map((reaction) => structuredClone(reaction)),\n exportSettings: copySpread(src.exportSettings),\n // Generated instance descendants have no status of their own.\n status: componentId === null ? src.status : null,\n componentPropertyValues: { ...src.componentPropertyValues },\n derivedLayout: src.derivedLayout ? { ...src.derivedLayout } : null,\n arcData: src.arcData ? copyArcData(src.arcData) : null,\n vectorNetwork: src.vectorNetwork ? cloneVectorNetwork(src.vectorNetwork) : null,\n textPicture: src.textPicture ? new Uint8Array(src.textPicture) : null,\n derivedTextGlyphs: src.derivedTextGlyphs\n ? markCopySource(src.derivedTextGlyphs, copyDerivedGlyphs(src.derivedTextGlyphs) ?? [])\n : null,\n textPathData: src.textPathData ? structuredClone(src.textPathData) : null,\n textPathBox: src.textPathBox ? { ...src.textPathBox } : null,\n gridPosition: src.gridPosition ? { ...src.gridPosition } : null,\n targetAspectRatio: src.targetAspectRatio ? { ...src.targetAspectRatio } : null,\n connectorStart: src.connectorStart ? copyConnectorEndpoint(src.connectorStart) : null,\n connectorEnd: src.connectorEnd ? copyConnectorEndpoint(src.connectorEnd) : null,\n connectorControlPoints: structuredClone(src.connectorControlPoints),\n connectorCurveHandles: structuredClone(src.connectorCurveHandles),\n connectorLabelPosition: src.connectorLabelPosition ? { ...src.connectorLabelPosition } : null\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiCA,SAAgB,SAAyB,GAAS;CAChD,MAAM,OAAU;EAAE,GAAG;EAAG,OAAO,EAAE,GAAG,EAAE,M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,IAAI,iBAAiB,KAAK,CAAC,CAAC,IACpF;EACJ,cAAc,IAAI,eAAe,gBAAgB,IAAI,YAAY,IAAI;EACrE,aAAa,IAAI,cAAc,EAAE,GAAG,IAAI,YAAY,IAAI;EACxD,cAAc,IAAI,eAAe,EAAE,GAAG,IAAI,aAAa,IAAI;EAC3D,mBAAmB,IAAI,oBAAoB,EAAE,GAAG,IAAI,kBAAkB,IAAI;EAC1E,gBAAgB,IAAI,iBAAiB,sBAAsB,IAAI,cAAc,IAAI;EACjF,cAAc,IAAI,eAAe,sBAAsB,IAAI,YAAY,IAAI;EAC3E,wBAAwB,gBAAgB,IAAI,sBAAsB;EAClE,uBAAuB,gBAAgB,IAAI,qBAAqB;EAChE,wBAAwB,IAAI,yBAAyB,EAAE,GAAG,IAAI,uBAAuB,IAAI;CAC3F;AACF"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Vector } from "./primitives/index.js";
|
|
2
|
+
import { Effect, ShaderEffect, ShadowEffect } from "./types.js";
|
|
3
|
+
//#region src/effects.d.ts
|
|
4
|
+
/** A shadow or blur whose offset may still be missing or only partly present. */
|
|
5
|
+
type ShadowInput = Omit<ShadowEffect, 'offset'> & {
|
|
6
|
+
offset?: Partial<Vector> | null;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Shadows and blurs keep a finite offset. A drop or inner shadow missing one uses `{x: 0, y: 4}`,
|
|
10
|
+
* the same default as `dropShadow()` and `set_effects`; a blur uses `{x: 0, y: 0}`. Shader effects
|
|
11
|
+
* are left alone. An array that is already valid is returned as itself.
|
|
12
|
+
*/
|
|
13
|
+
declare function normalizeEffects(effects: (ShaderEffect | ShadowInput)[]): Effect[];
|
|
14
|
+
//#endregion
|
|
15
|
+
export { normalizeEffects };
|
|
16
|
+
//# sourceMappingURL=effects.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"effects.d.ts","names":[],"sources":["../src/effects.ts"],"mappings":";;;;KAOK,cAAc,KAAK;EACtB,SAAS,QAAQ;;;;;;;iBAqDH,iBAAiB,UAAU,eAAe,iBAAiB"}
|
package/dist/effects.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
//#region src/effects.ts
|
|
2
|
+
const SHADOW_OFFSET = {
|
|
3
|
+
x: 0,
|
|
4
|
+
y: 4
|
|
5
|
+
};
|
|
6
|
+
const BLUR_OFFSET = {
|
|
7
|
+
x: 0,
|
|
8
|
+
y: 0
|
|
9
|
+
};
|
|
10
|
+
function fallbackOffset(type) {
|
|
11
|
+
return type === "DROP_SHADOW" || type === "INNER_SHADOW" ? SHADOW_OFFSET : BLUR_OFFSET;
|
|
12
|
+
}
|
|
13
|
+
function component(offset, key, fallback) {
|
|
14
|
+
if (!(key in offset)) return fallback;
|
|
15
|
+
const value = Reflect.get(offset, key);
|
|
16
|
+
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
|
17
|
+
}
|
|
18
|
+
/** A new offset when `effect.offset` is missing or not finite; null when it can stay. */
|
|
19
|
+
function finiteOffset(effect) {
|
|
20
|
+
const fallback = fallbackOffset(effect.type);
|
|
21
|
+
const offset = effect.offset;
|
|
22
|
+
if (offset === null || typeof offset !== "object") return {
|
|
23
|
+
x: fallback.x,
|
|
24
|
+
y: fallback.y
|
|
25
|
+
};
|
|
26
|
+
const x = component(offset, "x", fallback.x);
|
|
27
|
+
const y = component(offset, "y", fallback.y);
|
|
28
|
+
if (Reflect.get(offset, "x") === x && Reflect.get(offset, "y") === y) return null;
|
|
29
|
+
return {
|
|
30
|
+
x,
|
|
31
|
+
y
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
function isStoredShadow(effect) {
|
|
35
|
+
const offset = effect.offset;
|
|
36
|
+
return !!offset && typeof offset.x === "number" && Number.isFinite(offset.x) && typeof offset.y === "number" && Number.isFinite(offset.y);
|
|
37
|
+
}
|
|
38
|
+
function withFiniteOffset(effect) {
|
|
39
|
+
const offset = finiteOffset(effect);
|
|
40
|
+
if (!offset) {
|
|
41
|
+
if (isStoredShadow(effect)) return effect;
|
|
42
|
+
return {
|
|
43
|
+
...effect,
|
|
44
|
+
offset: fallbackOffset(effect.type)
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
...effect,
|
|
49
|
+
offset
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function isStoredEffect(effect) {
|
|
53
|
+
return effect.type === "SHADER" || isStoredShadow(effect);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Shadows and blurs keep a finite offset. A drop or inner shadow missing one uses `{x: 0, y: 4}`,
|
|
57
|
+
* the same default as `dropShadow()` and `set_effects`; a blur uses `{x: 0, y: 0}`. Shader effects
|
|
58
|
+
* are left alone. An array that is already valid is returned as itself.
|
|
59
|
+
*/
|
|
60
|
+
function normalizeEffects(effects) {
|
|
61
|
+
let next = null;
|
|
62
|
+
for (const [index, effect] of effects.entries()) {
|
|
63
|
+
const normalized = effect.type === "SHADER" ? effect : withFiniteOffset(effect);
|
|
64
|
+
if (normalized === effect) {
|
|
65
|
+
if (next && isStoredEffect(effect)) next.push(effect);
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
next ??= effects.slice(0, index).filter(isStoredEffect);
|
|
69
|
+
next.push(normalized);
|
|
70
|
+
}
|
|
71
|
+
if (next) return next;
|
|
72
|
+
if (effects.every(isStoredEffect)) return effects;
|
|
73
|
+
return effects.filter(isStoredEffect);
|
|
74
|
+
}
|
|
75
|
+
//#endregion
|
|
76
|
+
export { normalizeEffects };
|
|
77
|
+
|
|
78
|
+
//# sourceMappingURL=effects.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"effects.js","names":[],"sources":["../src/effects.ts"],"sourcesContent":["import type { Vector } from './primitives'\nimport type { Effect, ShaderEffect, ShadowEffect } from './types'\n\nconst SHADOW_OFFSET: Vector = { x: 0, y: 4 }\nconst BLUR_OFFSET: Vector = { x: 0, y: 0 }\n\n/** A shadow or blur whose offset may still be missing or only partly present. */\ntype ShadowInput = Omit<ShadowEffect, 'offset'> & {\n offset?: Partial<Vector> | null\n}\n\nfunction fallbackOffset(type: ShadowEffect['type']): Vector {\n return type === 'DROP_SHADOW' || type === 'INNER_SHADOW' ? SHADOW_OFFSET : BLUR_OFFSET\n}\n\nfunction component(offset: object, key: 'x' | 'y', fallback: number): number {\n if (!(key in offset)) return fallback\n const value: unknown = Reflect.get(offset, key)\n return typeof value === 'number' && Number.isFinite(value) ? value : fallback\n}\n\n/** A new offset when `effect.offset` is missing or not finite; null when it can stay. */\nfunction finiteOffset(effect: ShadowInput): Vector | null {\n const fallback = fallbackOffset(effect.type)\n const offset: unknown = effect.offset\n if (offset === null || typeof offset !== 'object') return { x: fallback.x, y: fallback.y }\n const x = component(offset, 'x', fallback.x)\n const y = component(offset, 'y', fallback.y)\n if (Reflect.get(offset, 'x') === x && Reflect.get(offset, 'y') === y) return null\n return { x, y }\n}\n\nfunction isStoredShadow(effect: ShadowInput): effect is ShadowEffect {\n const offset = effect.offset\n return (\n !!offset &&\n typeof offset.x === 'number' &&\n Number.isFinite(offset.x) &&\n typeof offset.y === 'number' &&\n Number.isFinite(offset.y)\n )\n}\n\nfunction withFiniteOffset(effect: ShadowInput): Effect {\n const offset = finiteOffset(effect)\n if (!offset) {\n if (isStoredShadow(effect)) return effect\n return { ...effect, offset: fallbackOffset(effect.type) }\n }\n return { ...effect, offset }\n}\n\nfunction isStoredEffect(effect: ShaderEffect | ShadowInput): effect is Effect {\n return effect.type === 'SHADER' || isStoredShadow(effect)\n}\n\n/**\n * Shadows and blurs keep a finite offset. A drop or inner shadow missing one uses `{x: 0, y: 4}`,\n * the same default as `dropShadow()` and `set_effects`; a blur uses `{x: 0, y: 0}`. Shader effects\n * are left alone. An array that is already valid is returned as itself.\n */\nexport function normalizeEffects(effects: (ShaderEffect | ShadowInput)[]): Effect[] {\n let next: Effect[] | null = null\n for (const [index, effect] of effects.entries()) {\n const normalized = effect.type === 'SHADER' ? effect : withFiniteOffset(effect)\n if (normalized === effect) {\n if (next && isStoredEffect(effect)) next.push(effect)\n continue\n }\n next ??= effects.slice(0, index).filter(isStoredEffect)\n next.push(normalized)\n }\n if (next) return next\n if (effects.every(isStoredEffect)) return effects\n return effects.filter(isStoredEffect)\n}\n"],"mappings":";AAGA,MAAM,gBAAwB;CAAE,GAAG;CAAG,GAAG;AAAE;AAC3C,MAAM,cAAsB;CAAE,GAAG;CAAG,GAAG;AAAE;AAOzC,SAAS,eAAe,MAAoC;CAC1D,OAAO,SAAS,iBAAiB,SAAS,iBAAiB,gBAAgB;AAC7E;AAEA,SAAS,UAAU,QAAgB,KAAgB,UAA0B;CAC3E,IAAI,EAAE,OAAO,SAAS,OAAO;CAC7B,MAAM,QAAiB,QAAQ,IAAI,QAAQ,GAAG;CAC9C,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;;AAGA,SAAS,aAAa,QAAoC;CACxD,MAAM,WAAW,eAAe,OAAO,IAAI;CAC3C,MAAM,SAAkB,OAAO;CAC/B,IAAI,WAAW,QAAQ,OAAO,WAAW,UAAU,OAAO;EAAE,GAAG,SAAS;EAAG,GAAG,SAAS;CAAE;CACzF,MAAM,IAAI,UAAU,QAAQ,KAAK,SAAS,CAAC;CAC3C,MAAM,IAAI,UAAU,QAAQ,KAAK,SAAS,CAAC;CAC3C,IAAI,QAAQ,IAAI,QAAQ,GAAG,MAAM,KAAK,QAAQ,IAAI,QAAQ,GAAG,MAAM,GAAG,OAAO;CAC7E,OAAO;EAAE;EAAG;CAAE;AAChB;AAEA,SAAS,eAAe,QAA6C;CACnE,MAAM,SAAS,OAAO;CACtB,OACE,CAAC,CAAC,UACF,OAAO,OAAO,MAAM,YACpB,OAAO,SAAS,OAAO,CAAC,KACxB,OAAO,OAAO,MAAM,YACpB,OAAO,SAAS,OAAO,CAAC;AAE5B;AAEA,SAAS,iBAAiB,QAA6B;CACrD,MAAM,SAAS,aAAa,MAAM;CAClC,IAAI,CAAC,QAAQ;EACX,IAAI,eAAe,MAAM,GAAG,OAAO;EACnC,OAAO;GAAE,GAAG;GAAQ,QAAQ,eAAe,OAAO,IAAI;EAAE;CAC1D;CACA,OAAO;EAAE,GAAG;EAAQ;CAAO;AAC7B;AAEA,SAAS,eAAe,QAAsD;CAC5E,OAAO,OAAO,SAAS,YAAY,eAAe,MAAM;AAC1D;;;;;;AAOA,SAAgB,iBAAiB,SAAmD;CAClF,IAAI,OAAwB;CAC5B,KAAK,MAAM,CAAC,OAAO,WAAW,QAAQ,QAAQ,GAAG;EAC/C,MAAM,aAAa,OAAO,SAAS,WAAW,SAAS,iBAAiB,MAAM;EAC9E,IAAI,eAAe,QAAQ;GACzB,IAAI,QAAQ,eAAe,MAAM,GAAG,KAAK,KAAK,MAAM;GACpD;EACF;EACA,SAAS,QAAQ,MAAM,GAAG,KAAK,CAAC,CAAC,OAAO,cAAc;EACtD,KAAK,KAAK,UAAU;CACtB;CACA,IAAI,MAAM,OAAO;CACjB,IAAI,QAAQ,MAAM,cAAc,GAAG,OAAO;CAC1C,OAAO,QAAQ,OAAO,cAAc;AACtC"}
|
package/dist/graph.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph.d.ts","names":[],"sources":["../src/graph.ts"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"graph.d.ts","names":[],"sources":["../src/graph.ts"],"mappings":";;;;;;;;;cAiDa;mBA+BkB;EA9B7B,OAAK,YAAA;EACL,QAAM,YAAA,WAAA;EACN,WAAS,YAAA;EACT,qBAAmB,YAAA;EACnB,YAAU;EACV;EACA;;EAEA,mBAAmB;EACnB,oBAAoB;EACpB,cAAc;EACd,kBAAgB,YAAA;WACP,SAAO;UACR;mBACS;UAOT;mBACS;UACT;UACA;EACR;EACA,eAAa,YAAA;;EAEb,cAAY;EAEiB,YAAA;EAW7B,QAAQ,eAAe;EAIvB,SAAS,4BAA0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yBAAyB,GAAG,UAAU,GAAG,6BAA6B;MAUlE;;;;;EAQJ,yBAAyB;MAIrB;;;;;;EASJ,oBAAoB;UAeZ;MASJ;EAGJ,0BAA0B,YAAY,WAAW;EAGjD,kBAAkB,YAAY,SAAS,QAAQ;;;;;EAa/C,WAAW,YAAY,SAAS,QAAQ;;UAYhC;;EAKR,sBACE,YACA,SAAS,QAAQ,YACjB,wBAAwB;UAMlB;;UAyCA;EAIR,aAAa,gBAAgB;;;;;;EA2C7B,cAAc,iBAAiB,kBAAkB;EAoBjD,WAAW;EAuBX,QAAQ,YAAY,YAAY,mBAAmB;;EAKnD,YAAY,YAAY,YAAY,kBAAkB,eAAU;EAIhE,kBACE,YACA,YACA,iBACA,aAAa,qBACb,eACC;EAIH,qBAAqB,YAAY,YAAY,kBAAkB;EAI/D,gBAAgB;EAIhB,cAAc,gBAAgB,YAAY;EAI1C,kBACE,YACA,YACA,YAAY,qBACZ,kBACA,UAAU,oBACT;EAIH,UACE,kBACA,kBACA,YAAW,QAAQ,aAClB;UAQK;EAyBR,eACE,qBACA,kBACA,YAAW,QAAQ,aAClB;EAIH,yBACE,oBACA,qBACA,OAAM;EAKR,sBACE,oBACA,qBACA,UAAU;EAKZ,cAAc;EAId,sBAAsB,cAAc;EAIpC,aAAa;EAIb,eAAe;EAIf,iBAAiB,qBAAqB;EAItC,aAAa,sBAAsB;EAInC,YAAY,mBAAmB,iBAAY;IAAQ,MAAM;IAAW"}
|
package/dist/graph.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { BufferedSceneEmitter } from "./buffered-events.js";
|
|
2
2
|
import { removeStaleBindings } from "./bindings.js";
|
|
3
3
|
import Matrix from "./matrix.js";
|
|
4
|
+
import { normalizeEffects } from "./effects.js";
|
|
4
5
|
import { CONTAINER_TYPES, createDefaultNode } from "./node-defaults.js";
|
|
5
6
|
import { getAbsolutePosition, getNodeLocalMatrix, getParentWorldMatrix, isTranslationOnly, localTransformFromWorld } from "./coordinate.js";
|
|
6
7
|
import { normalizeVectorNetwork } from "./vector-network.js";
|
|
@@ -461,6 +462,10 @@ var SceneGraph = class {
|
|
|
461
462
|
...changes,
|
|
462
463
|
vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork)
|
|
463
464
|
};
|
|
465
|
+
if (changes.effects) changes = {
|
|
466
|
+
...changes,
|
|
467
|
+
effects: normalizeEffects(changes.effects)
|
|
468
|
+
};
|
|
464
469
|
this.layoutWrites?.record(node, changes, this.scopeDepths.sourceMetadata === 0 && !this.isApplyingDerivedLayout);
|
|
465
470
|
Object.assign(node, changes);
|
|
466
471
|
if (changes.fills) removeStaleBindings(node, "fills", changes);
|
package/dist/graph.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph.js","names":["Variables.createVariable","Variables.createCollection","Variables.createMode","Variables.getActiveModeId","Variables.getNodeVariableModeId","Variables.resolveVariable","Variables.resolveColorVariable","Variables.resolveNumberVariable","Variables.resolveColorVariableForNode","Variables.resolveNumberVariableForNode","Variables.resolveVariableForNode","Variables.resolveStringVariableForNode","Variables.getVariablesForCollection","Variables.getVariablesByType","HitTest.hitTest","HitTest.hitTestDeep","HitTest.hitTestSelectable","HitTest.hitTestOpenContainer","HitTest.isOpenContainer","HitTest.isPointInNode","HitTest.hitTestDropTarget","Instances.createInstance","Instances.getMainComponent","Instances.getInstances"],"sources":["../src/graph.ts"],"sourcesContent":["/* eslint-disable max-lines -- SceneGraph is the facade over the domain modules */\nimport { omitBy } from 'es-toolkit/object'\nimport { isUndefined } from 'es-toolkit/predicate'\n\nimport { removeStaleBindings } from './bindings'\nimport { BufferedSceneEmitter } from './buffered-events'\nimport {\n getAbsolutePosition,\n getNodeLocalMatrix,\n getParentWorldMatrix,\n isTranslationOnly,\n localTransformFromWorld\n} from './coordinate'\nimport { cloneNodeProps, type NodeCloneMode } from './copy'\nimport { bindNodeEvents } from './events'\nimport { LAYOUT_AFFECTING_KEYS } from './fields/layout'\nimport { withGeneratedFrameSize } from './generated'\nimport * as HitTest from './hit-test'\nimport { generateId } from './ids'\nimport * as Instances from './instances'\nimport { LayoutWrites } from './layout/writes'\nimport Matrix from './matrix'\nimport { CONTAINER_TYPES, createDefaultNode } from './node-defaults'\nimport { updateNodePreview, type NodePreviewObserver } from './preview'\nimport type { Color, Rect, Vector } from './primitives'\nimport { markSourceFieldsEdited } from './source-metadata'\nimport { invalidateTextCaches } from './text/picture'\nimport type {\n DocumentColorSpace,\n DocumentKind,\n EnabledLibraryBinding,\n NodeChangeObserver,\n NodeType,\n SceneGraphEventHandlers,\n SceneNode,\n Variable,\n VariableCollection,\n VariableType,\n VariableValue,\n VariableLiteral\n} from './types'\nimport * as Variables from './variables'\nimport type { VariableModeFallback } from './variables'\nimport { normalizeVectorNetwork } from './vector-network'\n\n/** Scopes that graph methods check while a caller's callback runs; scopes nest. */\ntype GraphScope = 'preview' | 'sourceMetadata' | 'importedState' | 'layout' | 'derivedLayout'\n\nexport class SceneGraph {\n nodes = new Map<string, SceneNode>()\n images = new Map<string, Uint8Array>()\n variables = new Map<string, Variable>()\n variableCollections = new Map<string, VariableCollection>()\n activeMode = new Map<string, string>()\n rootId: string\n figKiwiVersion: number | null = null\n /** Deflated kiwi schema bytes from the original .fig file, preserved for roundtrip fidelity. */\n figSchemaDeflated: Uint8Array | null = null\n documentColorSpace: DocumentColorSpace = 'srgb'\n documentKind: DocumentKind = 'design'\n enabledLibraries = new Map<string, EnabledLibraryBinding>()\n readonly emitter = new BufferedSceneEmitter()\n private absPosCache = new Map<string, Vector>()\n private readonly scopeDepths: Record<GraphScope, number> = {\n preview: 0,\n sourceMetadata: 0,\n importedState: 0,\n layout: 0,\n derivedLayout: 0\n }\n private previewObservers: NodePreviewObserver[] = []\n private readonly changeObservers = new Set<NodeChangeObserver>()\n private importedIdGenerator: (() => string) | undefined\n private layoutWrites: LayoutWrites | null = null\n positionPreviewVersion = 0\n instanceIndex = new Map<string, Set<string>>()\n /** Every connector in the graph, so routing need not scan every layer. */\n connectorIds = new Set<string>()\n\n constructor(private readonly idGenerator: () => string = generateId) {\n const root = createDefaultNode(this.idGenerator, 'FRAME', {\n name: 'Document',\n width: 0,\n height: 0\n })\n this.rootId = root.id\n this.nodes.set(root.id, root)\n\n this.addPage('Page 1')\n }\n addPage(name: string): SceneNode {\n return this.createNode('CANVAS', this.rootId, { name, width: 0, height: 0 })\n }\n\n getPages(includeInternal = false): SceneNode[] {\n return this.getChildren(this.rootId).filter(\n (n) => n.type === 'CANVAS' && (includeInternal || !n.internalOnly)\n )\n }\n getAllNodes(): Iterable<SceneNode> {\n return this.nodes.values()\n }\n getNode(id: string): SceneNode | undefined {\n return this.nodes.get(id)\n }\n onNodeEvents(handlers: SceneGraphEventHandlers): () => void {\n return bindNodeEvents(this.emitter, handlers)\n }\n\n /**\n * Tells `observer` about each node an edit adds and, before it changes, each node it is about\n * to change, so a recorder can keep the node as it was. Unlike node events these are never\n * buffered. Graph methods report the nodes they change; code that writes into a node directly\n * reports it with `willChangeNode` first.\n */\n observeNodeChanges(observer: NodeChangeObserver): () => void {\n this.changeObservers.add(observer)\n return () => this.changeObservers.delete(observer)\n }\n\n /** Tells `observeNodeChanges` observers that `node` is about to change. */\n willChangeNode(node: SceneNode | undefined): void {\n if (!node) return\n for (const observer of this.changeObservers) observer.before(node)\n }\n\n countDescendants(nodeId: string): number {\n const node = this.nodes.get(nodeId)\n if (!node) return 0\n let count = 0\n const stack = [...node.childIds]\n while (stack.length > 0) {\n const id = stack.pop()\n if (id === undefined) break\n count++\n const child = this.nodes.get(id)\n if (child) {\n for (const childId of child.childIds) {\n stack.push(childId)\n }\n }\n }\n return count\n }\n addVariable(variable: Variable): void {\n Variables.addVariable(this, variable)\n }\n removeVariable(id: string): void {\n Variables.removeVariable(this, id)\n }\n addCollection(collection: VariableCollection): void {\n Variables.addCollection(this, collection)\n }\n createVariable(\n name: string,\n type: VariableType,\n collectionId: string,\n value?: VariableValue\n ): Variable {\n return Variables.createVariable(\n this,\n () => this.generateEntityId(),\n name,\n type,\n collectionId,\n value\n )\n }\n\n createCollection(name: string): VariableCollection {\n // The collection and its default mode are both created before either is registered.\n const issued = new Set<string>()\n return Variables.createCollection(this, () => this.generateEntityId(issued), name)\n }\n\n createMode(collectionId: string, name: string, sourceModeId?: string): string | undefined {\n return Variables.createMode(\n this,\n () => this.generateEntityId(),\n collectionId,\n name,\n sourceModeId\n )\n }\n\n /**\n * Mints IDs from this graph's generator for variables, collections, and modes built outside\n * it, such as a paste's: none is in use, and none repeats one this minter gave.\n */\n entityIdMinter(): () => string {\n const issued = new Set<string>()\n return () => this.generateEntityId(issued)\n }\n\n removeCollection(id: string): void {\n Variables.removeCollection(this, id)\n }\n\n getActiveModeId(collectionId: string): string {\n return Variables.getActiveModeId(this, collectionId)\n }\n\n getNodeVariableModeId(nodeId: string, collectionId: string): string {\n return Variables.getNodeVariableModeId(this, nodeId, collectionId)\n }\n\n setActiveMode(collectionId: string, modeId: string): void {\n Variables.setActiveMode(this, collectionId, modeId)\n }\n\n addMode(collectionId: string, modeId: string, name: string, sourceMode?: string): void {\n Variables.addMode(this, collectionId, modeId, name, sourceMode)\n }\n\n removeMode(collectionId: string, modeId: string): void {\n Variables.removeMode(this, collectionId, modeId)\n }\n\n renameMode(collectionId: string, modeId: string, name: string): void {\n Variables.renameMode(this, collectionId, modeId, name)\n }\n\n setDefaultMode(collectionId: string, modeId: string): void {\n Variables.setDefaultMode(this, collectionId, modeId)\n }\n\n resolveVariable(\n variableId: string,\n modeId?: string,\n visited?: Set<string>\n ): VariableLiteral | undefined {\n return Variables.resolveVariable(this, variableId, modeId, visited)\n }\n\n resolveColorVariable(variableId: string): Color | undefined {\n return Variables.resolveColorVariable(this, variableId)\n }\n\n resolveNumberVariable(variableId: string): number | undefined {\n return Variables.resolveNumberVariable(this, variableId)\n }\n\n resolveColorVariableForNode(\n nodeId: string,\n variableId: string,\n fallback?: VariableModeFallback\n ): Color | undefined {\n return Variables.resolveColorVariableForNode(this, nodeId, variableId, fallback)\n }\n\n resolveNumberVariableForNode(\n nodeId: string,\n variableId: string,\n fallback?: VariableModeFallback\n ): number | undefined {\n return Variables.resolveNumberVariableForNode(this, nodeId, variableId, fallback)\n }\n\n resolveVariableForNode(\n nodeId: string,\n variableId: string,\n fallback?: VariableModeFallback\n ): VariableLiteral | undefined {\n return Variables.resolveVariableForNode(this, nodeId, variableId, fallback)\n }\n\n resolveStringVariableForNode(\n nodeId: string,\n variableId: string,\n fallback?: VariableModeFallback\n ): string | undefined {\n return Variables.resolveStringVariableForNode(this, nodeId, variableId, fallback)\n }\n\n getVariablesForCollection(collectionId: string): Variable[] {\n return Variables.getVariablesForCollection(this, collectionId)\n }\n\n getVariablesByType(type: VariableType): Variable[] {\n return Variables.getVariablesByType(this, type)\n }\n\n bindVariable(nodeId: string, field: string, variableId: string): void {\n Variables.bindVariable(this, nodeId, field, variableId)\n }\n\n unbindVariable(nodeId: string, field: string): void {\n Variables.unbindVariable(this, nodeId, field)\n }\n\n getChildren(id: string): SceneNode[] {\n const node = this.nodes.get(id)\n if (!node) return []\n return node.childIds\n .map((cid) => this.nodes.get(cid))\n .filter((n): n is SceneNode => n !== undefined)\n }\n\n isContainer(id: string): boolean {\n const node = this.nodes.get(id)\n return node ? CONTAINER_TYPES.has(node.type) : false\n }\n\n isDescendant(childId: string, ancestorId: string): boolean {\n return this.closest(childId, (node) => node.id === ancestorId) !== undefined\n }\n\n /**\n * The node itself or its nearest ancestor that matches. The walk visits at most as many nodes\n * as the graph holds, so a parent cycle in bad data cannot hang it.\n */\n closest(id: string, match: (node: SceneNode) => boolean): SceneNode | undefined {\n let current = this.nodes.get(id)\n for (let steps = 0; current && steps < this.nodes.size; steps++) {\n if (match(current)) return current\n current = current.parentId ? this.nodes.get(current.parentId) : undefined\n }\n return undefined\n }\n\n /**\n * The page a node is on: the node itself for a page, its nearest page ancestor otherwise, and\n * null for the document root or a node on no page.\n */\n pageOf(id: string): string | null {\n return this.closest(id, (node) => node.type === 'CANVAS')?.id ?? null\n }\n\n clearAbsPosCache(): void {\n this.absPosCache.clear()\n }\n\n getAbsolutePosition(id: string): Vector {\n const cached = this.absPosCache.get(id)\n if (cached) return cached\n\n const node = this.getNode(id)\n if (!node) return { x: 0, y: 0 }\n\n const result = getAbsolutePosition(node, this)\n this.absPosCache.set(id, result)\n return result\n }\n\n getAbsoluteBounds(id: string): Rect {\n const pos = this.getAbsolutePosition(id)\n const node = this.nodes.get(id)\n return {\n x: pos.x,\n y: pos.y,\n width: node?.width ?? 0,\n height: node?.height ?? 0\n }\n }\n /**\n * An ID no entity uses; `issued` also excludes IDs handed out earlier in the same creation.\n * A generator that returns more taken IDs than the graph holds must be repeating itself, so\n * it counts as exhausted then; a fixed cap would reject a sequence walking past a large import.\n */\n private generateEntityId(issued?: Set<string>): string {\n let limit = Infinity\n for (let attempt = 0; attempt < limit; attempt++) {\n const id = (this.importedIdGenerator ?? this.idGenerator)()\n if (this.isEntityIdTaken(id) || issued?.has(id)) {\n if (limit === Infinity) limit = this.entityIdCount() + (issued?.size ?? 0) + 1\n continue\n }\n issued?.add(id)\n return id\n }\n throw new Error('The ID generator only returned IDs that are in use')\n }\n private entityIdCount(): number {\n let count = this.nodes.size + this.variables.size + this.variableCollections.size\n for (const collection of this.variableCollections.values()) count += collection.modes.length\n return count\n }\n /** Whether a node, variable, collection, or mode has this id. */\n isEntityIdTaken(id: string): boolean {\n if (this.nodes.has(id) || this.variables.has(id) || this.variableCollections.has(id))\n return true\n // Callers replace collection maps and edit `modes` in place (history snapshots, transfer,\n // undo), so an index of mode IDs would go stale; walk them without allocating instead.\n for (const collection of this.variableCollections.values()) {\n for (const mode of collection.modes) if (mode.modeId === id) return true\n }\n return false\n }\n private indexInstance(componentId: string, instanceId: string): void {\n let set = this.instanceIndex.get(componentId)\n if (!set) {\n set = new Set()\n this.instanceIndex.set(componentId, set)\n }\n set.add(instanceId)\n }\n private unindexInstance(componentId: string, instanceId: string): void {\n this.instanceIndex.get(componentId)?.delete(instanceId)\n }\n /**\n * The index lists instances by component, so a change of either, such as undoing a detach that\n * turns a frame back into an instance, moves the layer in it.\n */\n private reindexInstance(node: SceneNode, changes: Partial<SceneNode>): void {\n const indexedBefore = node.type === 'INSTANCE' ? node.componentId : null\n const componentAfter =\n 'componentId' in changes ? (changes.componentId ?? null) : node.componentId\n const indexedAfter = (changes.type ?? node.type) === 'INSTANCE' ? componentAfter : null\n if (indexedBefore === indexedAfter) return\n if (indexedBefore) this.unindexInstance(indexedBefore, node.id)\n if (indexedAfter) this.indexInstance(indexedAfter, node.id)\n }\n private registerNode(node: SceneNode, parentId: string | null): SceneNode {\n node.parentId = parentId\n this.nodes.set(node.id, node)\n if (node.type === 'CONNECTOR') this.connectorIds.add(node.id)\n for (const observer of this.changeObservers) observer.created(node)\n if (node.type === 'INSTANCE' && node.componentId) this.indexInstance(node.componentId, node.id)\n this.emitter.emit('node:created', node)\n return node\n }\n /** Publish synchronous graph events only after the supplied mutation succeeds. */\n withBufferedEvents<T>(action: () => T): T {\n return this.emitter.batch(action)\n }\n\n createNode(type: NodeType, parentId: string, overrides: Partial<SceneNode> = {}): SceneNode {\n const parent = this.nodes.get(parentId)\n if (!parent) throw new Error(`Parent \"${parentId}\" does not exist`)\n const node = createDefaultNode(() => this.generateEntityId(), type, overrides)\n this.willChangeNode(parent)\n parent.childIds.push(node.id)\n return this.registerNode(node, parentId)\n }\n createNodeWithId(\n id: string,\n type: NodeType,\n parentId: string | null,\n overrides: Partial<SceneNode> = {}\n ): SceneNode {\n // A caller restoring or importing a layer must know it brings a new one: replacing a layer\n // that already has the ID would drop it, and its children, from the document.\n if (this.nodes.has(id)) throw new Error(`Node \"${id}\" already exists`)\n if (parentId === id) throw new Error(`Node \"${id}\" cannot be its own parent`)\n const parent = parentId === null ? undefined : this.nodes.get(parentId)\n if (parentId !== null && !parent) throw new Error(`Parent \"${parentId}\" does not exist`)\n const node = createDefaultNode(() => id, type, overrides)\n // `overrides` may be another node's snapshot, ID included.\n node.id = id\n if (parent && !parent.childIds.includes(id)) {\n this.willChangeNode(parent)\n parent.childIds.push(id)\n }\n return this.registerNode(node, parentId)\n }\n\n private withScope<T>(scope: GraphScope, fn: () => T): T {\n this.scopeDepths[scope]++\n try {\n return fn()\n } finally {\n this.scopeDepths[scope]--\n }\n }\n\n runPreviewUpdates(fn: () => void, beforeUpdate?: NodePreviewObserver): void {\n if (beforeUpdate) this.previewObservers.push(beforeUpdate)\n try {\n this.withScope('preview', fn)\n } finally {\n if (beforeUpdate) this.previewObservers.pop()\n }\n }\n preserveSourceMetadataDuring<T>(fn: () => T): T {\n return this.withScope('sourceMetadata', fn)\n }\n get isPreservingSourceMetadata(): boolean {\n return this.scopeDepths.sourceMetadata > 0\n }\n\n applyImportedStateDuring<T>(fn: () => T, idGenerator?: () => string): T {\n const previousGenerator = this.importedIdGenerator\n this.importedIdGenerator = idGenerator ?? previousGenerator\n try {\n return this.withScope('importedState', () => this.preserveSourceMetadataDuring(fn))\n } finally {\n this.importedIdGenerator = previousGenerator\n }\n }\n\n get isApplyingImportedState(): boolean {\n return this.scopeDepths.importedState > 0\n }\n\n /**\n * Lays out what the document already holds: a page as it loads, or again once its fonts\n * arrive. What this writes derives from the document; an edit's own layout is not this.\n */\n applyDerivedLayoutDuring(fn: () => void): void {\n this.withScope('derivedLayout', fn)\n }\n\n get isApplyingDerivedLayout(): boolean {\n return this.scopeDepths.derivedLayout > 0\n }\n\n /**\n * Runs `fn` as layout. Its updates are published once the outermost layout ends, still as\n * layout, and without values a pass changed and a later pass put back (`LayoutWrites`). Outside\n * derived layout, the positions and sizes it publishes count as edited, so formats save them.\n */\n withLayoutMutations(fn: () => void): void {\n const outermost = this.scopeDepths.layout === 0\n this.scopeDepths.layout++\n if (outermost) this.layoutWrites = new LayoutWrites()\n try {\n fn()\n } finally {\n try {\n if (outermost) this.publishLayoutUpdates()\n } finally {\n this.scopeDepths.layout--\n }\n }\n }\n\n private publishLayoutUpdates(): void {\n const writes = this.layoutWrites\n this.layoutWrites = null\n if (!writes) return\n for (const [node, changes, edited] of writes.updates((nodeId) => this.nodes.get(nodeId))) {\n markSourceFieldsEdited(node, edited)\n this.emitter.emit('node:updated', node.id, changes)\n }\n }\n get isApplyingLayout(): boolean {\n return this.scopeDepths.layout > 0\n }\n updateNodePositionPreview(id: string, x: number, y: number): void {\n this.updateNodePreview(id, { x, y })\n }\n updateNodePreview(id: string, changes: Partial<SceneNode>): void {\n const node = this.nodes.get(id)\n if (node) changes = this.sizedChanges(node, changes)\n const appliedChanges = updateNodePreview(this, id, changes, (node, applied) => {\n for (const observe of this.previewObservers) observe(node, applied)\n })\n if (appliedChanges) this.emitter.emit('node:previewUpdated', id, appliedChanges)\n }\n\n /**\n * Writes fields as given. Edits detach the shared styles whose fields they change before\n * they get here (`styleDetachmentChanges`); resolving bindings or loading a file does not.\n */\n updateNode(id: string, changes: Partial<SceneNode>): void {\n if (this.scopeDepths.preview > 0) {\n this.updateNodePreview(id, changes)\n return\n }\n\n const node = this.nodes.get(id)\n if (!node) return\n this.applyNodeChanges(node, this.sizedChanges(node, omitBy(changes, isUndefined)))\n }\n\n /** A size set from outside layout, with what it also sets on a generated frame. */\n private sizedChanges(node: SceneNode, changes: Partial<SceneNode>): Partial<SceneNode> {\n return this.isApplyingLayout ? changes : withGeneratedFrameSize(node, changes)\n }\n\n /** Replay captured properties without dropping explicit undefined values or absent keys. */\n restoreNodeProperties(\n id: string,\n changes: Partial<SceneNode>,\n absent: readonly (keyof SceneNode)[]\n ): void {\n const node = this.nodes.get(id)\n if (node) this.applyNodeChanges(node, changes, absent)\n }\n\n private applyNodeChanges(\n node: SceneNode,\n changes: Partial<SceneNode>,\n absent: readonly (keyof SceneNode)[] = []\n ): void {\n const { id } = node\n this.willChangeNode(node)\n // Include removed keys in cache invalidation and update notifications.\n if (absent.length) {\n changes = { ...changes }\n for (const key of absent) Reflect.set(changes, key, undefined)\n }\n\n // Only clear absPosCache when layout-affecting properties change.\n // Fills, strokes, effects, plugin data changes do NOT affect absolute position.\n const affectsLayout = Object.keys(changes).some((k) => LAYOUT_AFFECTING_KEYS.has(k))\n if (affectsLayout) this.absPosCache.clear()\n this.reindexInstance(node, changes)\n if (node.type === 'TEXT') invalidateTextCaches(node, changes)\n if (this.scopeDepths.sourceMetadata === 0 && !this.isApplyingLayout) {\n markSourceFieldsEdited(node, Object.keys(changes))\n }\n if (changes.vectorNetwork) {\n changes = { ...changes, vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork) }\n }\n this.layoutWrites?.record(\n node,\n changes,\n this.scopeDepths.sourceMetadata === 0 && !this.isApplyingDerivedLayout\n )\n Object.assign(node, changes)\n if (changes.fills) removeStaleBindings(node, 'fills', changes)\n if (changes.strokes) removeStaleBindings(node, 'strokes', changes)\n for (const key of absent) Reflect.deleteProperty(node, key)\n this.publishNodeUpdate(id, changes)\n }\n\n /** Publishes an update now, or leaves it to the running layout, which publishes once it ends. */\n private publishNodeUpdate(id: string, changes: Partial<SceneNode>): void {\n if (!this.layoutWrites) this.emitter.emit('node:updated', id, changes)\n }\n\n reparentNode(nodeId: string, newParentId: string): void {\n const node = this.nodes.get(nodeId)\n if (!node || nodeId === this.rootId) return\n if (this.isDescendant(newParentId, nodeId)) return\n\n const oldParent = node.parentId ? this.nodes.get(node.parentId) : undefined\n const newParent = this.nodes.get(newParentId)\n if (!newParent) return\n if (node.parentId === newParentId) return\n\n const oldParentId = node.parentId\n this.willChangeNode(node)\n this.willChangeNode(oldParent)\n this.willChangeNode(newParent)\n this.absPosCache.clear()\n\n const oldParentWorld = getParentWorldMatrix(oldParent, this)\n const newParentWorld = getParentWorldMatrix(newParent, this)\n\n if (oldParent) {\n oldParent.childIds = oldParent.childIds.filter((cid) => cid !== nodeId)\n }\n\n node.parentId = newParentId\n newParent.childIds.push(nodeId)\n\n if (isTranslationOnly(oldParentWorld) && isTranslationOnly(newParentWorld)) {\n node.x += oldParentWorld[2] - newParentWorld[2]\n node.y += oldParentWorld[5] - newParentWorld[5]\n } else {\n const world = Matrix.multiply(oldParentWorld, getNodeLocalMatrix(node))\n const local = localTransformFromWorld(node, world, newParentWorld)\n if (local) Object.assign(node, local)\n }\n\n this.emitter.emit('node:reparented', nodeId, oldParentId, newParentId)\n }\n\n /**\n * Moves a node to `index` among `parentId`'s children, from wherever it was, without changing\n * its own coordinates. An index past the end appends; a move into the node itself or one of\n * its descendants is ignored.\n */\n insertChildAt(childId: string, parentId: string, index: number): void {\n const node = this.nodes.get(childId)\n const newParent = this.nodes.get(parentId)\n if (!node || !newParent || this.isDescendant(parentId, childId)) return\n const previousParentId = node.parentId\n const oldParent = previousParentId ? this.nodes.get(previousParentId) : undefined\n this.willChangeNode(node)\n this.willChangeNode(oldParent)\n this.willChangeNode(newParent)\n if (oldParent) {\n oldParent.childIds = oldParent.childIds.filter((id) => id !== childId)\n }\n newParent.childIds = newParent.childIds.filter((id) => id !== childId)\n const at = Math.min(index, newParent.childIds.length)\n newParent.childIds.splice(at, 0, childId)\n node.parentId = parentId\n this.absPosCache.clear()\n this.emitter.emit('node:reordered', childId, parentId, at, previousParentId)\n }\n\n deleteNode(id: string): void {\n const node = this.nodes.get(id)\n if (!node || id === this.rootId) return\n this.willChangeNode(node)\n\n if (node.parentId) {\n const parent = this.nodes.get(node.parentId)\n this.willChangeNode(parent)\n if (parent) {\n parent.childIds = parent.childIds.filter((cid) => cid !== id)\n }\n }\n\n for (const childId of Array.from(node.childIds)) {\n this.deleteNode(childId)\n }\n\n if (node.type === 'INSTANCE' && node.componentId) this.unindexInstance(node.componentId, id)\n this.connectorIds.delete(id)\n this.nodes.delete(id)\n this.emitter.emit('node:deleted', id, node.parentId)\n }\n\n hitTest(px: number, py: number, scopeId?: string): SceneNode | null {\n return HitTest.hitTest(this, px, py, scopeId)\n }\n\n /** `pad`, in canvas units, grows each shape's box, as Figma takes clicks just outside one. */\n hitTestDeep(px: number, py: number, scopeId?: string, pad = 0): SceneNode | null {\n return HitTest.hitTestDeep(this, px, py, scopeId, pad)\n }\n\n hitTestSelectable(\n px: number,\n py: number,\n scopeId: string,\n selectedIds: ReadonlySet<string>,\n pad = 0\n ): SceneNode | null {\n return HitTest.hitTestSelectable(this, px, py, scopeId, selectedIds, pad)\n }\n\n hitTestOpenContainer(px: number, py: number, scopeId: string): SceneNode | null {\n return HitTest.hitTestOpenContainer(this, px, py, scopeId)\n }\n\n isOpenContainer(nodeId: string): boolean {\n return HitTest.isOpenContainer(this, nodeId)\n }\n\n isPointInNode(nodeId: string, px: number, py: number): boolean {\n return HitTest.isPointInNode(this, nodeId, px, py)\n }\n\n hitTestDropTarget(\n px: number,\n py: number,\n excludeIds: ReadonlySet<string>,\n scopeId?: string,\n options?: HitTest.DropTargetOptions\n ): SceneNode | null {\n return HitTest.hitTestDropTarget(this, px, py, excludeIds, scopeId, options)\n }\n\n cloneTree(\n sourceId: string,\n parentId: string,\n overrides: Partial<SceneNode> = {}\n ): SceneNode | null {\n const copies = new Map<string, string>()\n const clone = this.cloneSubtree(sourceId, parentId, overrides, copies)\n // A copied instance records the overrides of its own layers, which are the cloned ones.\n Instances.retargetCopiedOverrides(this, copies)\n return clone\n }\n\n private cloneSubtree(\n sourceId: string,\n parentId: string,\n overrides: Partial<SceneNode>,\n copies: Map<string, string>\n ): SceneNode | null {\n const src = this.nodes.get(sourceId)\n if (!src) return null\n\n const props = cloneNodeProps(src, null)\n // Null out Figma source identifiers so the clone is treated as local.\n if (props.source) props.source = { ...props.source, id: null, orderKey: null }\n // A copy is a new design nobody has reviewed: Figma's duplicate and clone() drop the status.\n props.status = null\n const clone = this.createNode(src.type, parentId, { ...props, ...overrides })\n copies.set(src.id, clone.id)\n if (src.status) markSourceFieldsEdited(clone, ['status'])\n\n for (const childId of src.childIds) {\n this.cloneSubtree(childId, clone.id, {}, copies)\n }\n\n return clone\n }\n\n createInstance(\n componentId: string,\n parentId: string,\n overrides: Partial<SceneNode> = {}\n ): SceneNode | null {\n return Instances.createInstance(this, componentId, parentId, overrides)\n }\n\n populateInstanceChildren(\n instanceId: string,\n componentId: string,\n mode: NodeCloneMode = 'deep'\n ): void {\n Instances.populateInstanceChildren(this, instanceId, componentId, mode)\n }\n\n swapInstanceComponent(\n instanceId: string,\n componentId: string,\n options?: Instances.SwapInstanceOptions\n ): void {\n Instances.swapInstanceComponent(this, instanceId, componentId, options)\n }\n\n syncInstances(componentId: string): void {\n Instances.syncInstances(this, componentId)\n }\n\n syncInstancesTogether(componentIds: Iterable<string>): void {\n Instances.syncInstancesTogether(this, componentIds)\n }\n\n syncInstance(instanceId: string): void {\n Instances.syncInstance(this, instanceId)\n }\n\n detachInstance(instanceId: string): void {\n Instances.detachInstance(this, instanceId)\n }\n\n getMainComponent(instanceId: string): SceneNode | undefined {\n return Instances.getMainComponent(this, instanceId)\n }\n\n getInstances(componentId: string): SceneNode[] {\n return Instances.getInstances(this, componentId)\n }\n\n flattenTree(parentId?: string, depth = 0): Array<{ node: SceneNode; depth: number }> {\n const id = parentId ?? this.rootId\n const parent = this.nodes.get(id)\n if (!parent) return []\n const result: Array<{ node: SceneNode; depth: number }> = []\n for (const childId of parent.childIds) {\n const child = this.nodes.get(childId)\n if (!child) continue\n result.push({ node: child, depth })\n if (child.childIds.length > 0) result.push(...this.flattenTree(childId, depth + 1))\n }\n return result\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgDA,IAAa,aAAb,MAAwB;CA+BO;CA9B7B,wBAAQ,IAAI,IAAuB;CACnC,yBAAS,IAAI,IAAwB;CACrC,4BAAY,IAAI,IAAsB;CACtC,sCAAsB,IAAI,IAAgC;CAC1D,6BAAa,IAAI,IAAoB;CACrC;CACA,iBAAgC;;CAEhC,oBAAuC;CACvC,qBAAyC;CACzC,eAA6B;CAC7B,mCAAmB,IAAI,IAAmC;CAC1D,UAAmB,IAAI,qBAAqB;CAC5C,8BAAsB,IAAI,IAAoB;CAC9C,cAA2D;EACzD,SAAS;EACT,gBAAgB;EAChB,eAAe;EACf,QAAQ;EACR,eAAe;CACjB;CACA,mBAAkD,CAAC;CACnD,kCAA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CACjD;CAEA,YAAY,UAAmB,QAAQ,GAA8C;EACnF,MAAM,KAAK,YAAY,KAAK;EAC5B,MAAM,SAAS,KAAK,MAAM,IAAI,EAAE;EAChC,IAAI,CAAC,QAAQ,OAAO,CAAC;EACrB,MAAM,SAAoD,CAAC;EAC3D,KAAK,MAAM,WAAW,OAAO,UAAU;GACrC,MAAM,QAAQ,KAAK,MAAM,IAAI,OAAO;GACpC,IAAI,CAAC,OAAO;GACZ,OAAO,KAAK;IAAE,MAAM;IAAO;GAAM,CAAC;GAClC,IAAI,MAAM,SAAS,SAAS,GAAG,OAAO,KAAK,GAAG,KAAK,YAAY,SAAS,QAAQ,CAAC,CAAC;EACpF;EACA,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"graph.js","names":["Variables.createVariable","Variables.createCollection","Variables.createMode","Variables.getActiveModeId","Variables.getNodeVariableModeId","Variables.resolveVariable","Variables.resolveColorVariable","Variables.resolveNumberVariable","Variables.resolveColorVariableForNode","Variables.resolveNumberVariableForNode","Variables.resolveVariableForNode","Variables.resolveStringVariableForNode","Variables.getVariablesForCollection","Variables.getVariablesByType","HitTest.hitTest","HitTest.hitTestDeep","HitTest.hitTestSelectable","HitTest.hitTestOpenContainer","HitTest.isOpenContainer","HitTest.isPointInNode","HitTest.hitTestDropTarget","Instances.createInstance","Instances.getMainComponent","Instances.getInstances"],"sources":["../src/graph.ts"],"sourcesContent":["/* eslint-disable max-lines -- SceneGraph is the facade over the domain modules */\nimport { omitBy } from 'es-toolkit/object'\nimport { isUndefined } from 'es-toolkit/predicate'\n\nimport { removeStaleBindings } from './bindings'\nimport { BufferedSceneEmitter } from './buffered-events'\nimport {\n getAbsolutePosition,\n getNodeLocalMatrix,\n getParentWorldMatrix,\n isTranslationOnly,\n localTransformFromWorld\n} from './coordinate'\nimport { cloneNodeProps, type NodeCloneMode } from './copy'\nimport { normalizeEffects } from './effects'\nimport { bindNodeEvents } from './events'\nimport { LAYOUT_AFFECTING_KEYS } from './fields/layout'\nimport { withGeneratedFrameSize } from './generated'\nimport * as HitTest from './hit-test'\nimport { generateId } from './ids'\nimport * as Instances from './instances'\nimport { LayoutWrites } from './layout/writes'\nimport Matrix from './matrix'\nimport { CONTAINER_TYPES, createDefaultNode } from './node-defaults'\nimport { updateNodePreview, type NodePreviewObserver } from './preview'\nimport type { Color, Rect, Vector } from './primitives'\nimport { markSourceFieldsEdited } from './source-metadata'\nimport { invalidateTextCaches } from './text/picture'\nimport type {\n DocumentColorSpace,\n DocumentKind,\n EnabledLibraryBinding,\n NodeChangeObserver,\n NodeType,\n SceneGraphEventHandlers,\n SceneNode,\n Variable,\n VariableCollection,\n VariableType,\n VariableValue,\n VariableLiteral\n} from './types'\nimport * as Variables from './variables'\nimport type { VariableModeFallback } from './variables'\nimport { normalizeVectorNetwork } from './vector-network'\n\n/** Scopes that graph methods check while a caller's callback runs; scopes nest. */\ntype GraphScope = 'preview' | 'sourceMetadata' | 'importedState' | 'layout' | 'derivedLayout'\n\nexport class SceneGraph {\n nodes = new Map<string, SceneNode>()\n images = new Map<string, Uint8Array>()\n variables = new Map<string, Variable>()\n variableCollections = new Map<string, VariableCollection>()\n activeMode = new Map<string, string>()\n rootId: string\n figKiwiVersion: number | null = null\n /** Deflated kiwi schema bytes from the original .fig file, preserved for roundtrip fidelity. */\n figSchemaDeflated: Uint8Array | null = null\n documentColorSpace: DocumentColorSpace = 'srgb'\n documentKind: DocumentKind = 'design'\n enabledLibraries = new Map<string, EnabledLibraryBinding>()\n readonly emitter = new BufferedSceneEmitter()\n private absPosCache = new Map<string, Vector>()\n private readonly scopeDepths: Record<GraphScope, number> = {\n preview: 0,\n sourceMetadata: 0,\n importedState: 0,\n layout: 0,\n derivedLayout: 0\n }\n private previewObservers: NodePreviewObserver[] = []\n private readonly changeObservers = new Set<NodeChangeObserver>()\n private importedIdGenerator: (() => string) | undefined\n private layoutWrites: LayoutWrites | null = null\n positionPreviewVersion = 0\n instanceIndex = new Map<string, Set<string>>()\n /** Every connector in the graph, so routing need not scan every layer. */\n connectorIds = new Set<string>()\n\n constructor(private readonly idGenerator: () => string = generateId) {\n const root = createDefaultNode(this.idGenerator, 'FRAME', {\n name: 'Document',\n width: 0,\n height: 0\n })\n this.rootId = root.id\n this.nodes.set(root.id, root)\n\n this.addPage('Page 1')\n }\n addPage(name: string): SceneNode {\n return this.createNode('CANVAS', this.rootId, { name, width: 0, height: 0 })\n }\n\n getPages(includeInternal = false): SceneNode[] {\n return this.getChildren(this.rootId).filter(\n (n) => n.type === 'CANVAS' && (includeInternal || !n.internalOnly)\n )\n }\n getAllNodes(): Iterable<SceneNode> {\n return this.nodes.values()\n }\n getNode(id: string): SceneNode | undefined {\n return this.nodes.get(id)\n }\n onNodeEvents(handlers: SceneGraphEventHandlers): () => void {\n return bindNodeEvents(this.emitter, handlers)\n }\n\n /**\n * Tells `observer` about each node an edit adds and, before it changes, each node it is about\n * to change, so a recorder can keep the node as it was. Unlike node events these are never\n * buffered. Graph methods report the nodes they change; code that writes into a node directly\n * reports it with `willChangeNode` first.\n */\n observeNodeChanges(observer: NodeChangeObserver): () => void {\n this.changeObservers.add(observer)\n return () => this.changeObservers.delete(observer)\n }\n\n /** Tells `observeNodeChanges` observers that `node` is about to change. */\n willChangeNode(node: SceneNode | undefined): void {\n if (!node) return\n for (const observer of this.changeObservers) observer.before(node)\n }\n\n countDescendants(nodeId: string): number {\n const node = this.nodes.get(nodeId)\n if (!node) return 0\n let count = 0\n const stack = [...node.childIds]\n while (stack.length > 0) {\n const id = stack.pop()\n if (id === undefined) break\n count++\n const child = this.nodes.get(id)\n if (child) {\n for (const childId of child.childIds) {\n stack.push(childId)\n }\n }\n }\n return count\n }\n addVariable(variable: Variable): void {\n Variables.addVariable(this, variable)\n }\n removeVariable(id: string): void {\n Variables.removeVariable(this, id)\n }\n addCollection(collection: VariableCollection): void {\n Variables.addCollection(this, collection)\n }\n createVariable(\n name: string,\n type: VariableType,\n collectionId: string,\n value?: VariableValue\n ): Variable {\n return Variables.createVariable(\n this,\n () => this.generateEntityId(),\n name,\n type,\n collectionId,\n value\n )\n }\n\n createCollection(name: string): VariableCollection {\n // The collection and its default mode are both created before either is registered.\n const issued = new Set<string>()\n return Variables.createCollection(this, () => this.generateEntityId(issued), name)\n }\n\n createMode(collectionId: string, name: string, sourceModeId?: string): string | undefined {\n return Variables.createMode(\n this,\n () => this.generateEntityId(),\n collectionId,\n name,\n sourceModeId\n )\n }\n\n /**\n * Mints IDs from this graph's generator for variables, collections, and modes built outside\n * it, such as a paste's: none is in use, and none repeats one this minter gave.\n */\n entityIdMinter(): () => string {\n const issued = new Set<string>()\n return () => this.generateEntityId(issued)\n }\n\n removeCollection(id: string): void {\n Variables.removeCollection(this, id)\n }\n\n getActiveModeId(collectionId: string): string {\n return Variables.getActiveModeId(this, collectionId)\n }\n\n getNodeVariableModeId(nodeId: string, collectionId: string): string {\n return Variables.getNodeVariableModeId(this, nodeId, collectionId)\n }\n\n setActiveMode(collectionId: string, modeId: string): void {\n Variables.setActiveMode(this, collectionId, modeId)\n }\n\n addMode(collectionId: string, modeId: string, name: string, sourceMode?: string): void {\n Variables.addMode(this, collectionId, modeId, name, sourceMode)\n }\n\n removeMode(collectionId: string, modeId: string): void {\n Variables.removeMode(this, collectionId, modeId)\n }\n\n renameMode(collectionId: string, modeId: string, name: string): void {\n Variables.renameMode(this, collectionId, modeId, name)\n }\n\n setDefaultMode(collectionId: string, modeId: string): void {\n Variables.setDefaultMode(this, collectionId, modeId)\n }\n\n resolveVariable(\n variableId: string,\n modeId?: string,\n visited?: Set<string>\n ): VariableLiteral | undefined {\n return Variables.resolveVariable(this, variableId, modeId, visited)\n }\n\n resolveColorVariable(variableId: string): Color | undefined {\n return Variables.resolveColorVariable(this, variableId)\n }\n\n resolveNumberVariable(variableId: string): number | undefined {\n return Variables.resolveNumberVariable(this, variableId)\n }\n\n resolveColorVariableForNode(\n nodeId: string,\n variableId: string,\n fallback?: VariableModeFallback\n ): Color | undefined {\n return Variables.resolveColorVariableForNode(this, nodeId, variableId, fallback)\n }\n\n resolveNumberVariableForNode(\n nodeId: string,\n variableId: string,\n fallback?: VariableModeFallback\n ): number | undefined {\n return Variables.resolveNumberVariableForNode(this, nodeId, variableId, fallback)\n }\n\n resolveVariableForNode(\n nodeId: string,\n variableId: string,\n fallback?: VariableModeFallback\n ): VariableLiteral | undefined {\n return Variables.resolveVariableForNode(this, nodeId, variableId, fallback)\n }\n\n resolveStringVariableForNode(\n nodeId: string,\n variableId: string,\n fallback?: VariableModeFallback\n ): string | undefined {\n return Variables.resolveStringVariableForNode(this, nodeId, variableId, fallback)\n }\n\n getVariablesForCollection(collectionId: string): Variable[] {\n return Variables.getVariablesForCollection(this, collectionId)\n }\n\n getVariablesByType(type: VariableType): Variable[] {\n return Variables.getVariablesByType(this, type)\n }\n\n bindVariable(nodeId: string, field: string, variableId: string): void {\n Variables.bindVariable(this, nodeId, field, variableId)\n }\n\n unbindVariable(nodeId: string, field: string): void {\n Variables.unbindVariable(this, nodeId, field)\n }\n\n getChildren(id: string): SceneNode[] {\n const node = this.nodes.get(id)\n if (!node) return []\n return node.childIds\n .map((cid) => this.nodes.get(cid))\n .filter((n): n is SceneNode => n !== undefined)\n }\n\n isContainer(id: string): boolean {\n const node = this.nodes.get(id)\n return node ? CONTAINER_TYPES.has(node.type) : false\n }\n\n isDescendant(childId: string, ancestorId: string): boolean {\n return this.closest(childId, (node) => node.id === ancestorId) !== undefined\n }\n\n /**\n * The node itself or its nearest ancestor that matches. The walk visits at most as many nodes\n * as the graph holds, so a parent cycle in bad data cannot hang it.\n */\n closest(id: string, match: (node: SceneNode) => boolean): SceneNode | undefined {\n let current = this.nodes.get(id)\n for (let steps = 0; current && steps < this.nodes.size; steps++) {\n if (match(current)) return current\n current = current.parentId ? this.nodes.get(current.parentId) : undefined\n }\n return undefined\n }\n\n /**\n * The page a node is on: the node itself for a page, its nearest page ancestor otherwise, and\n * null for the document root or a node on no page.\n */\n pageOf(id: string): string | null {\n return this.closest(id, (node) => node.type === 'CANVAS')?.id ?? null\n }\n\n clearAbsPosCache(): void {\n this.absPosCache.clear()\n }\n\n getAbsolutePosition(id: string): Vector {\n const cached = this.absPosCache.get(id)\n if (cached) return cached\n\n const node = this.getNode(id)\n if (!node) return { x: 0, y: 0 }\n\n const result = getAbsolutePosition(node, this)\n this.absPosCache.set(id, result)\n return result\n }\n\n getAbsoluteBounds(id: string): Rect {\n const pos = this.getAbsolutePosition(id)\n const node = this.nodes.get(id)\n return {\n x: pos.x,\n y: pos.y,\n width: node?.width ?? 0,\n height: node?.height ?? 0\n }\n }\n /**\n * An ID no entity uses; `issued` also excludes IDs handed out earlier in the same creation.\n * A generator that returns more taken IDs than the graph holds must be repeating itself, so\n * it counts as exhausted then; a fixed cap would reject a sequence walking past a large import.\n */\n private generateEntityId(issued?: Set<string>): string {\n let limit = Infinity\n for (let attempt = 0; attempt < limit; attempt++) {\n const id = (this.importedIdGenerator ?? this.idGenerator)()\n if (this.isEntityIdTaken(id) || issued?.has(id)) {\n if (limit === Infinity) limit = this.entityIdCount() + (issued?.size ?? 0) + 1\n continue\n }\n issued?.add(id)\n return id\n }\n throw new Error('The ID generator only returned IDs that are in use')\n }\n private entityIdCount(): number {\n let count = this.nodes.size + this.variables.size + this.variableCollections.size\n for (const collection of this.variableCollections.values()) count += collection.modes.length\n return count\n }\n /** Whether a node, variable, collection, or mode has this id. */\n isEntityIdTaken(id: string): boolean {\n if (this.nodes.has(id) || this.variables.has(id) || this.variableCollections.has(id))\n return true\n // Callers replace collection maps and edit `modes` in place (history snapshots, transfer,\n // undo), so an index of mode IDs would go stale; walk them without allocating instead.\n for (const collection of this.variableCollections.values()) {\n for (const mode of collection.modes) if (mode.modeId === id) return true\n }\n return false\n }\n private indexInstance(componentId: string, instanceId: string): void {\n let set = this.instanceIndex.get(componentId)\n if (!set) {\n set = new Set()\n this.instanceIndex.set(componentId, set)\n }\n set.add(instanceId)\n }\n private unindexInstance(componentId: string, instanceId: string): void {\n this.instanceIndex.get(componentId)?.delete(instanceId)\n }\n /**\n * The index lists instances by component, so a change of either, such as undoing a detach that\n * turns a frame back into an instance, moves the layer in it.\n */\n private reindexInstance(node: SceneNode, changes: Partial<SceneNode>): void {\n const indexedBefore = node.type === 'INSTANCE' ? node.componentId : null\n const componentAfter =\n 'componentId' in changes ? (changes.componentId ?? null) : node.componentId\n const indexedAfter = (changes.type ?? node.type) === 'INSTANCE' ? componentAfter : null\n if (indexedBefore === indexedAfter) return\n if (indexedBefore) this.unindexInstance(indexedBefore, node.id)\n if (indexedAfter) this.indexInstance(indexedAfter, node.id)\n }\n private registerNode(node: SceneNode, parentId: string | null): SceneNode {\n node.parentId = parentId\n this.nodes.set(node.id, node)\n if (node.type === 'CONNECTOR') this.connectorIds.add(node.id)\n for (const observer of this.changeObservers) observer.created(node)\n if (node.type === 'INSTANCE' && node.componentId) this.indexInstance(node.componentId, node.id)\n this.emitter.emit('node:created', node)\n return node\n }\n /** Publish synchronous graph events only after the supplied mutation succeeds. */\n withBufferedEvents<T>(action: () => T): T {\n return this.emitter.batch(action)\n }\n\n createNode(type: NodeType, parentId: string, overrides: Partial<SceneNode> = {}): SceneNode {\n const parent = this.nodes.get(parentId)\n if (!parent) throw new Error(`Parent \"${parentId}\" does not exist`)\n const node = createDefaultNode(() => this.generateEntityId(), type, overrides)\n this.willChangeNode(parent)\n parent.childIds.push(node.id)\n return this.registerNode(node, parentId)\n }\n createNodeWithId(\n id: string,\n type: NodeType,\n parentId: string | null,\n overrides: Partial<SceneNode> = {}\n ): SceneNode {\n // A caller restoring or importing a layer must know it brings a new one: replacing a layer\n // that already has the ID would drop it, and its children, from the document.\n if (this.nodes.has(id)) throw new Error(`Node \"${id}\" already exists`)\n if (parentId === id) throw new Error(`Node \"${id}\" cannot be its own parent`)\n const parent = parentId === null ? undefined : this.nodes.get(parentId)\n if (parentId !== null && !parent) throw new Error(`Parent \"${parentId}\" does not exist`)\n const node = createDefaultNode(() => id, type, overrides)\n // `overrides` may be another node's snapshot, ID included.\n node.id = id\n if (parent && !parent.childIds.includes(id)) {\n this.willChangeNode(parent)\n parent.childIds.push(id)\n }\n return this.registerNode(node, parentId)\n }\n\n private withScope<T>(scope: GraphScope, fn: () => T): T {\n this.scopeDepths[scope]++\n try {\n return fn()\n } finally {\n this.scopeDepths[scope]--\n }\n }\n\n runPreviewUpdates(fn: () => void, beforeUpdate?: NodePreviewObserver): void {\n if (beforeUpdate) this.previewObservers.push(beforeUpdate)\n try {\n this.withScope('preview', fn)\n } finally {\n if (beforeUpdate) this.previewObservers.pop()\n }\n }\n preserveSourceMetadataDuring<T>(fn: () => T): T {\n return this.withScope('sourceMetadata', fn)\n }\n get isPreservingSourceMetadata(): boolean {\n return this.scopeDepths.sourceMetadata > 0\n }\n\n applyImportedStateDuring<T>(fn: () => T, idGenerator?: () => string): T {\n const previousGenerator = this.importedIdGenerator\n this.importedIdGenerator = idGenerator ?? previousGenerator\n try {\n return this.withScope('importedState', () => this.preserveSourceMetadataDuring(fn))\n } finally {\n this.importedIdGenerator = previousGenerator\n }\n }\n\n get isApplyingImportedState(): boolean {\n return this.scopeDepths.importedState > 0\n }\n\n /**\n * Lays out what the document already holds: a page as it loads, or again once its fonts\n * arrive. What this writes derives from the document; an edit's own layout is not this.\n */\n applyDerivedLayoutDuring(fn: () => void): void {\n this.withScope('derivedLayout', fn)\n }\n\n get isApplyingDerivedLayout(): boolean {\n return this.scopeDepths.derivedLayout > 0\n }\n\n /**\n * Runs `fn` as layout. Its updates are published once the outermost layout ends, still as\n * layout, and without values a pass changed and a later pass put back (`LayoutWrites`). Outside\n * derived layout, the positions and sizes it publishes count as edited, so formats save them.\n */\n withLayoutMutations(fn: () => void): void {\n const outermost = this.scopeDepths.layout === 0\n this.scopeDepths.layout++\n if (outermost) this.layoutWrites = new LayoutWrites()\n try {\n fn()\n } finally {\n try {\n if (outermost) this.publishLayoutUpdates()\n } finally {\n this.scopeDepths.layout--\n }\n }\n }\n\n private publishLayoutUpdates(): void {\n const writes = this.layoutWrites\n this.layoutWrites = null\n if (!writes) return\n for (const [node, changes, edited] of writes.updates((nodeId) => this.nodes.get(nodeId))) {\n markSourceFieldsEdited(node, edited)\n this.emitter.emit('node:updated', node.id, changes)\n }\n }\n get isApplyingLayout(): boolean {\n return this.scopeDepths.layout > 0\n }\n updateNodePositionPreview(id: string, x: number, y: number): void {\n this.updateNodePreview(id, { x, y })\n }\n updateNodePreview(id: string, changes: Partial<SceneNode>): void {\n const node = this.nodes.get(id)\n if (node) changes = this.sizedChanges(node, changes)\n const appliedChanges = updateNodePreview(this, id, changes, (node, applied) => {\n for (const observe of this.previewObservers) observe(node, applied)\n })\n if (appliedChanges) this.emitter.emit('node:previewUpdated', id, appliedChanges)\n }\n\n /**\n * Writes fields as given. Edits detach the shared styles whose fields they change before\n * they get here (`styleDetachmentChanges`); resolving bindings or loading a file does not.\n */\n updateNode(id: string, changes: Partial<SceneNode>): void {\n if (this.scopeDepths.preview > 0) {\n this.updateNodePreview(id, changes)\n return\n }\n\n const node = this.nodes.get(id)\n if (!node) return\n this.applyNodeChanges(node, this.sizedChanges(node, omitBy(changes, isUndefined)))\n }\n\n /** A size set from outside layout, with what it also sets on a generated frame. */\n private sizedChanges(node: SceneNode, changes: Partial<SceneNode>): Partial<SceneNode> {\n return this.isApplyingLayout ? changes : withGeneratedFrameSize(node, changes)\n }\n\n /** Replay captured properties without dropping explicit undefined values or absent keys. */\n restoreNodeProperties(\n id: string,\n changes: Partial<SceneNode>,\n absent: readonly (keyof SceneNode)[]\n ): void {\n const node = this.nodes.get(id)\n if (node) this.applyNodeChanges(node, changes, absent)\n }\n\n private applyNodeChanges(\n node: SceneNode,\n changes: Partial<SceneNode>,\n absent: readonly (keyof SceneNode)[] = []\n ): void {\n const { id } = node\n this.willChangeNode(node)\n // Include removed keys in cache invalidation and update notifications.\n if (absent.length) {\n changes = { ...changes }\n for (const key of absent) Reflect.set(changes, key, undefined)\n }\n\n // Only clear absPosCache when layout-affecting properties change.\n // Fills, strokes, effects, plugin data changes do NOT affect absolute position.\n const affectsLayout = Object.keys(changes).some((k) => LAYOUT_AFFECTING_KEYS.has(k))\n if (affectsLayout) this.absPosCache.clear()\n this.reindexInstance(node, changes)\n if (node.type === 'TEXT') invalidateTextCaches(node, changes)\n if (this.scopeDepths.sourceMetadata === 0 && !this.isApplyingLayout) {\n markSourceFieldsEdited(node, Object.keys(changes))\n }\n if (changes.vectorNetwork) {\n changes = { ...changes, vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork) }\n }\n if (changes.effects) {\n changes = { ...changes, effects: normalizeEffects(changes.effects) }\n }\n this.layoutWrites?.record(\n node,\n changes,\n this.scopeDepths.sourceMetadata === 0 && !this.isApplyingDerivedLayout\n )\n Object.assign(node, changes)\n if (changes.fills) removeStaleBindings(node, 'fills', changes)\n if (changes.strokes) removeStaleBindings(node, 'strokes', changes)\n for (const key of absent) Reflect.deleteProperty(node, key)\n this.publishNodeUpdate(id, changes)\n }\n\n /** Publishes an update now, or leaves it to the running layout, which publishes once it ends. */\n private publishNodeUpdate(id: string, changes: Partial<SceneNode>): void {\n if (!this.layoutWrites) this.emitter.emit('node:updated', id, changes)\n }\n\n reparentNode(nodeId: string, newParentId: string): void {\n const node = this.nodes.get(nodeId)\n if (!node || nodeId === this.rootId) return\n if (this.isDescendant(newParentId, nodeId)) return\n\n const oldParent = node.parentId ? this.nodes.get(node.parentId) : undefined\n const newParent = this.nodes.get(newParentId)\n if (!newParent) return\n if (node.parentId === newParentId) return\n\n const oldParentId = node.parentId\n this.willChangeNode(node)\n this.willChangeNode(oldParent)\n this.willChangeNode(newParent)\n this.absPosCache.clear()\n\n const oldParentWorld = getParentWorldMatrix(oldParent, this)\n const newParentWorld = getParentWorldMatrix(newParent, this)\n\n if (oldParent) {\n oldParent.childIds = oldParent.childIds.filter((cid) => cid !== nodeId)\n }\n\n node.parentId = newParentId\n newParent.childIds.push(nodeId)\n\n if (isTranslationOnly(oldParentWorld) && isTranslationOnly(newParentWorld)) {\n node.x += oldParentWorld[2] - newParentWorld[2]\n node.y += oldParentWorld[5] - newParentWorld[5]\n } else {\n const world = Matrix.multiply(oldParentWorld, getNodeLocalMatrix(node))\n const local = localTransformFromWorld(node, world, newParentWorld)\n if (local) Object.assign(node, local)\n }\n\n this.emitter.emit('node:reparented', nodeId, oldParentId, newParentId)\n }\n\n /**\n * Moves a node to `index` among `parentId`'s children, from wherever it was, without changing\n * its own coordinates. An index past the end appends; a move into the node itself or one of\n * its descendants is ignored.\n */\n insertChildAt(childId: string, parentId: string, index: number): void {\n const node = this.nodes.get(childId)\n const newParent = this.nodes.get(parentId)\n if (!node || !newParent || this.isDescendant(parentId, childId)) return\n const previousParentId = node.parentId\n const oldParent = previousParentId ? this.nodes.get(previousParentId) : undefined\n this.willChangeNode(node)\n this.willChangeNode(oldParent)\n this.willChangeNode(newParent)\n if (oldParent) {\n oldParent.childIds = oldParent.childIds.filter((id) => id !== childId)\n }\n newParent.childIds = newParent.childIds.filter((id) => id !== childId)\n const at = Math.min(index, newParent.childIds.length)\n newParent.childIds.splice(at, 0, childId)\n node.parentId = parentId\n this.absPosCache.clear()\n this.emitter.emit('node:reordered', childId, parentId, at, previousParentId)\n }\n\n deleteNode(id: string): void {\n const node = this.nodes.get(id)\n if (!node || id === this.rootId) return\n this.willChangeNode(node)\n\n if (node.parentId) {\n const parent = this.nodes.get(node.parentId)\n this.willChangeNode(parent)\n if (parent) {\n parent.childIds = parent.childIds.filter((cid) => cid !== id)\n }\n }\n\n for (const childId of Array.from(node.childIds)) {\n this.deleteNode(childId)\n }\n\n if (node.type === 'INSTANCE' && node.componentId) this.unindexInstance(node.componentId, id)\n this.connectorIds.delete(id)\n this.nodes.delete(id)\n this.emitter.emit('node:deleted', id, node.parentId)\n }\n\n hitTest(px: number, py: number, scopeId?: string): SceneNode | null {\n return HitTest.hitTest(this, px, py, scopeId)\n }\n\n /** `pad`, in canvas units, grows each shape's box, as Figma takes clicks just outside one. */\n hitTestDeep(px: number, py: number, scopeId?: string, pad = 0): SceneNode | null {\n return HitTest.hitTestDeep(this, px, py, scopeId, pad)\n }\n\n hitTestSelectable(\n px: number,\n py: number,\n scopeId: string,\n selectedIds: ReadonlySet<string>,\n pad = 0\n ): SceneNode | null {\n return HitTest.hitTestSelectable(this, px, py, scopeId, selectedIds, pad)\n }\n\n hitTestOpenContainer(px: number, py: number, scopeId: string): SceneNode | null {\n return HitTest.hitTestOpenContainer(this, px, py, scopeId)\n }\n\n isOpenContainer(nodeId: string): boolean {\n return HitTest.isOpenContainer(this, nodeId)\n }\n\n isPointInNode(nodeId: string, px: number, py: number): boolean {\n return HitTest.isPointInNode(this, nodeId, px, py)\n }\n\n hitTestDropTarget(\n px: number,\n py: number,\n excludeIds: ReadonlySet<string>,\n scopeId?: string,\n options?: HitTest.DropTargetOptions\n ): SceneNode | null {\n return HitTest.hitTestDropTarget(this, px, py, excludeIds, scopeId, options)\n }\n\n cloneTree(\n sourceId: string,\n parentId: string,\n overrides: Partial<SceneNode> = {}\n ): SceneNode | null {\n const copies = new Map<string, string>()\n const clone = this.cloneSubtree(sourceId, parentId, overrides, copies)\n // A copied instance records the overrides of its own layers, which are the cloned ones.\n Instances.retargetCopiedOverrides(this, copies)\n return clone\n }\n\n private cloneSubtree(\n sourceId: string,\n parentId: string,\n overrides: Partial<SceneNode>,\n copies: Map<string, string>\n ): SceneNode | null {\n const src = this.nodes.get(sourceId)\n if (!src) return null\n\n const props = cloneNodeProps(src, null)\n // Null out Figma source identifiers so the clone is treated as local.\n if (props.source) props.source = { ...props.source, id: null, orderKey: null }\n // A copy is a new design nobody has reviewed: Figma's duplicate and clone() drop the status.\n props.status = null\n const clone = this.createNode(src.type, parentId, { ...props, ...overrides })\n copies.set(src.id, clone.id)\n if (src.status) markSourceFieldsEdited(clone, ['status'])\n\n for (const childId of src.childIds) {\n this.cloneSubtree(childId, clone.id, {}, copies)\n }\n\n return clone\n }\n\n createInstance(\n componentId: string,\n parentId: string,\n overrides: Partial<SceneNode> = {}\n ): SceneNode | null {\n return Instances.createInstance(this, componentId, parentId, overrides)\n }\n\n populateInstanceChildren(\n instanceId: string,\n componentId: string,\n mode: NodeCloneMode = 'deep'\n ): void {\n Instances.populateInstanceChildren(this, instanceId, componentId, mode)\n }\n\n swapInstanceComponent(\n instanceId: string,\n componentId: string,\n options?: Instances.SwapInstanceOptions\n ): void {\n Instances.swapInstanceComponent(this, instanceId, componentId, options)\n }\n\n syncInstances(componentId: string): void {\n Instances.syncInstances(this, componentId)\n }\n\n syncInstancesTogether(componentIds: Iterable<string>): void {\n Instances.syncInstancesTogether(this, componentIds)\n }\n\n syncInstance(instanceId: string): void {\n Instances.syncInstance(this, instanceId)\n }\n\n detachInstance(instanceId: string): void {\n Instances.detachInstance(this, instanceId)\n }\n\n getMainComponent(instanceId: string): SceneNode | undefined {\n return Instances.getMainComponent(this, instanceId)\n }\n\n getInstances(componentId: string): SceneNode[] {\n return Instances.getInstances(this, componentId)\n }\n\n flattenTree(parentId?: string, depth = 0): Array<{ node: SceneNode; depth: number }> {\n const id = parentId ?? this.rootId\n const parent = this.nodes.get(id)\n if (!parent) return []\n const result: Array<{ node: SceneNode; depth: number }> = []\n for (const childId of parent.childIds) {\n const child = this.nodes.get(childId)\n if (!child) continue\n result.push({ node: child, depth })\n if (child.childIds.length > 0) result.push(...this.flattenTree(childId, depth + 1))\n }\n return result\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAa,aAAb,MAAwB;CA+BO;CA9B7B,wBAAQ,IAAI,IAAuB;CACnC,yBAAS,IAAI,IAAwB;CACrC,4BAAY,IAAI,IAAsB;CACtC,sCAAsB,IAAI,IAAgC;CAC1D,6BAAa,IAAI,IAAoB;CACrC;CACA,iBAAgC;;CAEhC,oBAAuC;CACvC,qBAAyC;CACzC,eAA6B;CAC7B,mCAAmB,IAAI,IAAmC;CAC1D,UAAmB,IAAI,qBAAqB;CAC5C,8BAAsB,IAAI,IAAoB;CAC9C,cAA2D;EACzD,SAAS;EACT,gBAAgB;EA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B;EACvC,eAAyB,MAAM,UAAU;CAC3C;CAEA,iBAAiB,YAA2C;EAC1D,OAAOC,iBAA2B,MAAM,UAAU;CACpD;CAEA,aAAa,aAAkC;EAC7C,OAAOC,aAAuB,MAAM,WAAW;CACjD;CAEA,YAAY,UAAmB,QAAQ,GAA8C;EACnF,MAAM,KAAK,YAAY,KAAK;EAC5B,MAAM,SAAS,KAAK,MAAM,IAAI,EAAE;EAChC,IAAI,CAAC,QAAQ,OAAO,CAAC;EACrB,MAAM,SAAoD,CAAC;EAC3D,KAAK,MAAM,WAAW,OAAO,UAAU;GACrC,MAAM,QAAQ,KAAK,MAAM,IAAI,OAAO;GACpC,IAAI,CAAC,OAAO;GACZ,OAAO,KAAK;IAAE,MAAM;IAAO;GAAM,CAAC;GAClC,IAAI,MAAM,SAAS,SAAS,GAAG,OAAO,KAAK,GAAG,KAAK,YAAY,SAAS,QAAQ,CAAC,CAAC;EACpF;EACA,OAAO;CACT;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-defaults.d.ts","names":[],"sources":["../src/node-defaults.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"node-defaults.d.ts","names":[],"sources":["../src/node-defaults.ts"],"mappings":";;iBAWgB,+BAA+B;;iBA4B/B,mBAAmB,MAAM,WAAW;;;;;iBASpC,kBACd,MAAM,KAAK,yDACV,KAAK;iBAKQ,kBACd,0BACA,MAAM,UACN,YAAW,QAAQ,aAClB;;cAoLU,wBAAwB,YAAY;;cAMpC,mBAAmB,YAAY;cAQ/B,iBAAe,IAAA"}
|
package/dist/node-defaults.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { BLACK, DEFAULT_FONT_FAMILY } from "./constants.js";
|
|
2
|
+
import { normalizeEffects } from "./effects.js";
|
|
2
3
|
import { createInstanceOverrideState } from "./instances/overrides.js";
|
|
3
4
|
import { NO_LETTER_SPACING } from "./text/lengths.js";
|
|
4
5
|
//#region src/node-defaults.ts
|
|
@@ -38,7 +39,7 @@ function newStrokeGeometry(node) {
|
|
|
38
39
|
};
|
|
39
40
|
}
|
|
40
41
|
function createDefaultNode(generateId, type, overrides = {}) {
|
|
41
|
-
|
|
42
|
+
const node = {
|
|
42
43
|
id: generateId(),
|
|
43
44
|
type,
|
|
44
45
|
name: type.charAt(0) + type.slice(1).toLowerCase(),
|
|
@@ -216,6 +217,8 @@ function createDefaultNode(generateId, type, overrides = {}) {
|
|
|
216
217
|
booleanOperation: void 0,
|
|
217
218
|
...overrides
|
|
218
219
|
};
|
|
220
|
+
node.effects = normalizeEffects(node.effects);
|
|
221
|
+
return node;
|
|
219
222
|
}
|
|
220
223
|
/** Containers whose bounds follow their children and that set no coordinate space, as in Figma. */
|
|
221
224
|
const FITTED_CONTAINER_TYPES = /* @__PURE__ */ new Set(["GROUP", "BOOLEAN_OPERATION"]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-defaults.js","names":[],"sources":["../src/node-defaults.ts"],"sourcesContent":["import {\n BLACK,\n DEFAULT_FONT_FAMILY,\n DEFAULT_STROKE_MITER_LIMIT,\n DEFAULT_STROKE_WEIGHT\n} from './constants'\nimport { createInstanceOverrideState } from './instances/overrides'\nimport { NO_LETTER_SPACING } from './text/lengths'\nimport type { NodeType, SceneNode, SourceMetadata } from './types'\n\nexport function createDefaultSourceMetadata(): SourceMetadata {\n return {\n format: null,\n id: null,\n orderKey: null,\n editedFields: [],\n fig: {\n rawSize: null,\n rawTransform: null,\n rawNodeFields: {},\n layout: null,\n symbolOverrides: [],\n componentPropAssignments: [],\n derivedSymbolData: [],\n derivedSymbolDataLayoutVersion: null,\n uniformScaleFactor: null\n }\n }\n}\n\n/**\n * Every SceneNode field. Nodes start with all of them, so setting any field later keeps the\n * shape every node shares; a key added after creation turns a JavaScriptCore object into a\n * slower, larger dictionary.\n */\ntype CompleteNodeFields = SceneNode & Record<keyof SceneNode, unknown>\n\n/** Where Figma aligns a new node's strokes: centered on lines and vectors, outside text, else inside. */\nexport function defaultStrokeAlign(type: NodeType): SceneNode['strokeAlign'] {\n if (type === 'LINE' || type === 'VECTOR') return 'CENTER'\n return type === 'TEXT' ? 'OUTSIDE' : 'INSIDE'\n}\n\n/**\n * Weight and alignment a stroke added to `node` takes: its first stroke's, or what the node keeps\n * with none. Adding a stroke from the panel and from the plugin API both go through here.\n */\nexport function newStrokeGeometry(\n node: Pick<SceneNode, 'strokes' | 'strokeWeight' | 'strokeAlign'>\n): Pick<SceneNode['strokes'][number], 'weight' | 'align'> {\n const first = node.strokes.at(0)\n return { weight: first?.weight ?? node.strokeWeight, align: first?.align ?? node.strokeAlign }\n}\n\nexport function createDefaultNode(\n generateId: () => string,\n type: NodeType,\n overrides: Partial<SceneNode> = {}\n): SceneNode {\n return {\n id: generateId(),\n type,\n name: type.charAt(0) + type.slice(1).toLowerCase(),\n parentId: null,\n childIds: [],\n x: 0,\n y: 0,\n width: 100,\n height: 100,\n rotation: 0,\n source: createDefaultSourceMetadata(),\n derivedLayout: null,\n fills:\n type === 'TEXT' ? [{ type: 'SOLID' as const, color: BLACK, opacity: 1, visible: true }] : [],\n strokes: [],\n effects: [],\n layoutGrids: [],\n guides: [],\n fillStyleId: null,\n strokeStyleId: null,\n textStyleId: null,\n effectStyleId: null,\n gridStyleId: null,\n sharedStyleType: null,\n opacity: 1,\n cornerRadius: 0,\n topLeftRadius: 0,\n topRightRadius: 0,\n bottomRightRadius: 0,\n bottomLeftRadius: 0,\n independentCorners: false,\n cornerSmoothing: 0,\n visible: true,\n locked: false,\n clipsContent: false,\n text: '',\n fontSize: 14,\n fontFamily: DEFAULT_FONT_FAMILY,\n fontWeight: 400,\n italic: false,\n fontStyle: null,\n textAlignHorizontal: 'LEFT',\n textDirection: 'AUTO',\n textLanguage: null,\n leadingTrim: 'NONE',\n lineHeight: null,\n letterSpacing: NO_LETTER_SPACING,\n layoutMode: 'NONE',\n layoutDirection: 'AUTO',\n layoutWrap: 'NO_WRAP',\n primaryAxisAlign: 'MIN',\n counterAxisAlign: 'MIN',\n primaryAxisSizing: 'FIXED',\n counterAxisSizing: 'FIXED',\n itemSpacing: 0,\n counterAxisSpacing: 0,\n paddingTop: 0,\n paddingRight: 0,\n paddingBottom: 0,\n paddingLeft: 0,\n blendMode: 'PASS_THROUGH',\n layoutPositioning: 'AUTO',\n layoutGrow: 0,\n layoutAlignSelf: 'AUTO',\n vectorNetwork: null,\n handleMirroring: 'NONE',\n fillGeometry: [],\n strokeGeometry: [],\n arcData: null,\n textAlignVertical: 'TOP',\n textAutoResize: 'NONE',\n textCase: 'ORIGINAL',\n textDecoration: 'NONE',\n textDecorationStyle: 'SOLID',\n textDecorationThickness: null,\n textDecorationFills: [],\n textDecorationSkipInk: true,\n textUnderlineOffset: null,\n maxLines: null,\n textParagraphs: [],\n listSpacing: 0,\n paragraphSpacing: 0,\n paragraphIndent: 0,\n hangingList: false,\n styleRuns: [],\n fontVariations: [],\n opticalSizeFromFontSize: true,\n fontFeatures: [],\n horizontalConstraint: 'MIN',\n verticalConstraint: 'MIN',\n strokeCap: 'NONE',\n strokeJoin: 'MITER',\n dashPattern: [],\n borderTopWeight: 0,\n borderRightWeight: 0,\n borderBottomWeight: 0,\n borderLeftWeight: 0,\n independentStrokeWeights: false,\n strokeWeight: DEFAULT_STROKE_WEIGHT,\n strokeAlign: defaultStrokeAlign(type),\n strokeMiterLimit: DEFAULT_STROKE_MITER_LIMIT,\n minWidth: null,\n maxWidth: null,\n minHeight: null,\n maxHeight: null,\n targetAspectRatio: null,\n connectorStart: null,\n connectorEnd: null,\n connectorLineType: 'ELBOWED',\n connectorStartCap: 'ROUND',\n connectorEndCap: 'ARROW_LINES',\n connectorControlPoints: [],\n connectorCurveHandles: null,\n connectorLabelPosition: null,\n isMask: false,\n maskType: 'ALPHA',\n maskIsOutline: false,\n gridTemplateColumns: [],\n gridTemplateRows: [],\n gridColumnGap: 0,\n gridRowGap: 0,\n gridPosition: null,\n counterAxisAlignContent: 'AUTO',\n itemReverseZIndex: false,\n strokesIncludedInLayout: false,\n expanded: true,\n textTruncation: 'DISABLED',\n autoRename: true,\n pointCount: 5,\n starInnerRadius: 0.38,\n shapeWithTextType: 'SQUARE',\n shapeUserHeight: 0,\n shapeTruncates: false,\n componentId: null,\n instanceOverrides: createInstanceOverrideState(),\n componentPropertyDefinitions: [],\n componentPropertyReferences: [],\n componentPropertyAssignments: {},\n componentPropertyValues: {},\n componentKey: null,\n sourceLibraryKey: null,\n publishId: null,\n overrideKey: null,\n sharedSymbolVersion: null,\n publishedVersion: null,\n librarySource: null,\n isPublishable: false,\n isSymbolPublishable: false,\n isExposedInstance: false,\n symbolDescription: '',\n symbolLinks: [],\n variantPropSpecs: [],\n boundVariables: {},\n variableBindingScales: {},\n variableAssignmentScales: {},\n componentScale: 1,\n variableModes: {},\n exportSettings: [],\n status: null,\n pluginData: [],\n pluginRelaunchData: [],\n prototypeReactions: [],\n internalOnly: false,\n flipX: false,\n flipY: false,\n textPicture: null,\n derivedTextGlyphs: null,\n derivedTextHeight: null,\n textPathData: null,\n textPathBox: null,\n booleanOperation: undefined,\n ...overrides\n } satisfies CompleteNodeFields\n}\n\n/** Containers whose bounds follow their children and that set no coordinate space, as in Figma. */\nexport const FITTED_CONTAINER_TYPES: ReadonlySet<NodeType> = new Set<NodeType>([\n 'GROUP',\n 'BOOLEAN_OPERATION'\n])\n\n/** Layers whose stroke can take a weight per side, as Figma's `strokeTopWeight` and its siblings. */\nexport const SIDE_STROKE_TYPES: ReadonlySet<NodeType> = new Set<NodeType>([\n 'RECTANGLE',\n 'FRAME',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE'\n])\n\nexport const CONTAINER_TYPES = new Set<NodeType>([\n 'CANVAS',\n 'FRAME',\n 'GROUP',\n 'BOOLEAN_OPERATION',\n 'SECTION',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE'\n])\n"],"mappings":";;;;AAUA,SAAgB,8BAA8C;CAC5D,OAAO;EACL,QAAQ;EACR,IA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aAAa;EACb,mBAAmB,4BAA4B;EAC/C,8BAA8B,CAAC;EAC/B,6BAA6B,CAAC;EAC9B,8BAA8B,CAAC;EAC/B,yBAAyB,CAAC;EAC1B,cAAc;EACd,kBAAkB;EAClB,WAAW;EACX,aAAa;EACb,qBAAqB;EACrB,kBAAkB;EAClB,eAAe;EACf,eAAe;EACf,qBAAqB;EACrB,mBAAmB;EACnB,mBAAmB;EACnB,aAAa,CAAC;EACd,kBAAkB,CAAC;EACnB,gBAAgB,CAAC;EACjB,uBAAuB,CAAC;EACxB,0BAA0B,CAAC;EAC3B,gBAAgB;EAChB,eAAe,CAAC;EAChB,gBAAgB,CAAC;EACjB,QAAQ;EACR,YAAY,CAAC;EACb,oBAAoB,CAAC;EACrB,oBAAoB,CAAC;EACrB,cAAc;EACd,OAAO;EACP,OAAO;EACP,aAAa;EACb,mBAAmB;EACnB,mBAAmB;EACnB,cAAc;EACd,aAAa;EACb,kBAAkB,KAAA;EAClB,GAAG;CACL;AACF;;AAGA,MAAa,yCAAgD,IAAI,IAAc,CAC7E,SACA,mBACF,CAAC;;AAGD,MAAa,oCAA2C,IAAI,IAAc;CACxE;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAa,kCAAkB,IAAI,IAAc;CAC/C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"node-defaults.js","names":[],"sources":["../src/node-defaults.ts"],"sourcesContent":["import {\n BLACK,\n DEFAULT_FONT_FAMILY,\n DEFAULT_STROKE_MITER_LIMIT,\n DEFAULT_STROKE_WEIGHT\n} from './constants'\nimport { normalizeEffects } from './effects'\nimport { createInstanceOverrideState } from './instances/overrides'\nimport { NO_LETTER_SPACING } from './text/lengths'\nimport type { NodeType, SceneNode, SourceMetadata } from './types'\n\nexport function createDefaultSourceMetadata(): SourceMetadata {\n return {\n format: null,\n id: null,\n orderKey: null,\n editedFields: [],\n fig: {\n rawSize: null,\n rawTransform: null,\n rawNodeFields: {},\n layout: null,\n symbolOverrides: [],\n componentPropAssignments: [],\n derivedSymbolData: [],\n derivedSymbolDataLayoutVersion: null,\n uniformScaleFactor: null\n }\n }\n}\n\n/**\n * Every SceneNode field. Nodes start with all of them, so setting any field later keeps the\n * shape every node shares; a key added after creation turns a JavaScriptCore object into a\n * slower, larger dictionary.\n */\ntype CompleteNodeFields = SceneNode & Record<keyof SceneNode, unknown>\n\n/** Where Figma aligns a new node's strokes: centered on lines and vectors, outside text, else inside. */\nexport function defaultStrokeAlign(type: NodeType): SceneNode['strokeAlign'] {\n if (type === 'LINE' || type === 'VECTOR') return 'CENTER'\n return type === 'TEXT' ? 'OUTSIDE' : 'INSIDE'\n}\n\n/**\n * Weight and alignment a stroke added to `node` takes: its first stroke's, or what the node keeps\n * with none. Adding a stroke from the panel and from the plugin API both go through here.\n */\nexport function newStrokeGeometry(\n node: Pick<SceneNode, 'strokes' | 'strokeWeight' | 'strokeAlign'>\n): Pick<SceneNode['strokes'][number], 'weight' | 'align'> {\n const first = node.strokes.at(0)\n return { weight: first?.weight ?? node.strokeWeight, align: first?.align ?? node.strokeAlign }\n}\n\nexport function createDefaultNode(\n generateId: () => string,\n type: NodeType,\n overrides: Partial<SceneNode> = {}\n): SceneNode {\n const node = {\n id: generateId(),\n type,\n name: type.charAt(0) + type.slice(1).toLowerCase(),\n parentId: null,\n childIds: [],\n x: 0,\n y: 0,\n width: 100,\n height: 100,\n rotation: 0,\n source: createDefaultSourceMetadata(),\n derivedLayout: null,\n fills:\n type === 'TEXT' ? [{ type: 'SOLID' as const, color: BLACK, opacity: 1, visible: true }] : [],\n strokes: [],\n effects: [],\n layoutGrids: [],\n guides: [],\n fillStyleId: null,\n strokeStyleId: null,\n textStyleId: null,\n effectStyleId: null,\n gridStyleId: null,\n sharedStyleType: null,\n opacity: 1,\n cornerRadius: 0,\n topLeftRadius: 0,\n topRightRadius: 0,\n bottomRightRadius: 0,\n bottomLeftRadius: 0,\n independentCorners: false,\n cornerSmoothing: 0,\n visible: true,\n locked: false,\n clipsContent: false,\n text: '',\n fontSize: 14,\n fontFamily: DEFAULT_FONT_FAMILY,\n fontWeight: 400,\n italic: false,\n fontStyle: null,\n textAlignHorizontal: 'LEFT',\n textDirection: 'AUTO',\n textLanguage: null,\n leadingTrim: 'NONE',\n lineHeight: null,\n letterSpacing: NO_LETTER_SPACING,\n layoutMode: 'NONE',\n layoutDirection: 'AUTO',\n layoutWrap: 'NO_WRAP',\n primaryAxisAlign: 'MIN',\n counterAxisAlign: 'MIN',\n primaryAxisSizing: 'FIXED',\n counterAxisSizing: 'FIXED',\n itemSpacing: 0,\n counterAxisSpacing: 0,\n paddingTop: 0,\n paddingRight: 0,\n paddingBottom: 0,\n paddingLeft: 0,\n blendMode: 'PASS_THROUGH',\n layoutPositioning: 'AUTO',\n layoutGrow: 0,\n layoutAlignSelf: 'AUTO',\n vectorNetwork: null,\n handleMirroring: 'NONE',\n fillGeometry: [],\n strokeGeometry: [],\n arcData: null,\n textAlignVertical: 'TOP',\n textAutoResize: 'NONE',\n textCase: 'ORIGINAL',\n textDecoration: 'NONE',\n textDecorationStyle: 'SOLID',\n textDecorationThickness: null,\n textDecorationFills: [],\n textDecorationSkipInk: true,\n textUnderlineOffset: null,\n maxLines: null,\n textParagraphs: [],\n listSpacing: 0,\n paragraphSpacing: 0,\n paragraphIndent: 0,\n hangingList: false,\n styleRuns: [],\n fontVariations: [],\n opticalSizeFromFontSize: true,\n fontFeatures: [],\n horizontalConstraint: 'MIN',\n verticalConstraint: 'MIN',\n strokeCap: 'NONE',\n strokeJoin: 'MITER',\n dashPattern: [],\n borderTopWeight: 0,\n borderRightWeight: 0,\n borderBottomWeight: 0,\n borderLeftWeight: 0,\n independentStrokeWeights: false,\n strokeWeight: DEFAULT_STROKE_WEIGHT,\n strokeAlign: defaultStrokeAlign(type),\n strokeMiterLimit: DEFAULT_STROKE_MITER_LIMIT,\n minWidth: null,\n maxWidth: null,\n minHeight: null,\n maxHeight: null,\n targetAspectRatio: null,\n connectorStart: null,\n connectorEnd: null,\n connectorLineType: 'ELBOWED',\n connectorStartCap: 'ROUND',\n connectorEndCap: 'ARROW_LINES',\n connectorControlPoints: [],\n connectorCurveHandles: null,\n connectorLabelPosition: null,\n isMask: false,\n maskType: 'ALPHA',\n maskIsOutline: false,\n gridTemplateColumns: [],\n gridTemplateRows: [],\n gridColumnGap: 0,\n gridRowGap: 0,\n gridPosition: null,\n counterAxisAlignContent: 'AUTO',\n itemReverseZIndex: false,\n strokesIncludedInLayout: false,\n expanded: true,\n textTruncation: 'DISABLED',\n autoRename: true,\n pointCount: 5,\n starInnerRadius: 0.38,\n shapeWithTextType: 'SQUARE',\n shapeUserHeight: 0,\n shapeTruncates: false,\n componentId: null,\n instanceOverrides: createInstanceOverrideState(),\n componentPropertyDefinitions: [],\n componentPropertyReferences: [],\n componentPropertyAssignments: {},\n componentPropertyValues: {},\n componentKey: null,\n sourceLibraryKey: null,\n publishId: null,\n overrideKey: null,\n sharedSymbolVersion: null,\n publishedVersion: null,\n librarySource: null,\n isPublishable: false,\n isSymbolPublishable: false,\n isExposedInstance: false,\n symbolDescription: '',\n symbolLinks: [],\n variantPropSpecs: [],\n boundVariables: {},\n variableBindingScales: {},\n variableAssignmentScales: {},\n componentScale: 1,\n variableModes: {},\n exportSettings: [],\n status: null,\n pluginData: [],\n pluginRelaunchData: [],\n prototypeReactions: [],\n internalOnly: false,\n flipX: false,\n flipY: false,\n textPicture: null,\n derivedTextGlyphs: null,\n derivedTextHeight: null,\n textPathData: null,\n textPathBox: null,\n booleanOperation: undefined,\n ...overrides\n } satisfies CompleteNodeFields\n node.effects = normalizeEffects(node.effects)\n return node\n}\n\n/** Containers whose bounds follow their children and that set no coordinate space, as in Figma. */\nexport const FITTED_CONTAINER_TYPES: ReadonlySet<NodeType> = new Set<NodeType>([\n 'GROUP',\n 'BOOLEAN_OPERATION'\n])\n\n/** Layers whose stroke can take a weight per side, as Figma's `strokeTopWeight` and its siblings. */\nexport const SIDE_STROKE_TYPES: ReadonlySet<NodeType> = new Set<NodeType>([\n 'RECTANGLE',\n 'FRAME',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE'\n])\n\nexport const CONTAINER_TYPES = new Set<NodeType>([\n 'CANVAS',\n 'FRAME',\n 'GROUP',\n 'BOOLEAN_OPERATION',\n 'SECTION',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE'\n])\n"],"mappings":";;;;;AAWA,SAAgB,8BAA8C;CAC5D,OAAO;EACL,QAAQ;EACR,IAAI;EACJ,UAAU;EACV,cAAc,CAAC;EACf,KAAK;GACH,SAAS;GACT,cAAc;GACd,eAAe,CAAC;GAChB,QAAQ;GACR,iBAAiB,CAAC;GAClB,0BAA0B,CAAC;GAC3B,mBAAmB,CAAC;GACpB,gCAAgC;GAChC,oBAAoB;EACtB;CACF;AACF;;AAUA,SAAgB,mBAAmB,MAA0C;CAC3E,IAAI,SAAS,UAAU,SAAS,UAAU,OAAO;CACjD,OAAO,SAAS,SAAS,YAAY;AACvC;;;;;AAMA,SAAgB,kBACd,MACwD;CACxD,MAAM,QAAQ,KAAK,QAAQ,GAAG,CAAC;CAC/B,OAAO;EAAE,QAAQ,OAAO,UAAU,KAAK;EAAc,OAAO,OAAO,SAAS,KAAK;CAAY;AAC/F;AAEA,SAAgB,kBACd,YACA,MACA,YAAgC,CAAC,GACtB;CACX,MAAM,OAAO;EACX,IAAI,WAAW;EACf;EACA,MAAM,KAAK,OAAO,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,YAAY;EACjD,UAAU;EACV,UAAU,CAAC;EACX,GAAG;EACH,GAAG;EACH,OAAO;EACP,QAAQ;EACR,UAAU;EACV,QAAQ,4BAA4B;EACpC,eAAe;EACf,OACE,SAAS,SAAS,CAAC;GAAE,MAAM;GAAkB,OAAO;GAAO,SAAS;GAAG,SAAS;EAAK,CAAC,IAAI,CAAC;EAC7F,SAAS,CAAC;EACV,SAAS,CAAC;EACV,aAAa,CAAC;EACd,Q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ANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"preview.d.ts","names":[],"sources":["../src/preview.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"preview.d.ts","names":[],"sources":["../src/preview.ts"],"mappings":";;KAKY,uBAAuB,MAAM,WAAW,SAAS,QAAQ;KAEhE;EACH,OAAO,YAAY;EACnB;EACA;;iBAwCc,kBACd,OAAO,cACP,YACA,SAAS,QAAQ,YACjB,eAAe,sBACd,QAAQ"}
|
package/dist/preview.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { normalizeEffects } from "./effects.js";
|
|
1
2
|
import { normalizeVectorNetwork } from "./vector-network.js";
|
|
2
3
|
import { textCacheInvalidationChanges } from "./text/picture.js";
|
|
3
4
|
//#region src/preview.ts
|
|
@@ -52,6 +53,10 @@ function updateNodePreview(graph, id, changes, beforeUpdate) {
|
|
|
52
53
|
...normalizedChanges,
|
|
53
54
|
vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork)
|
|
54
55
|
};
|
|
56
|
+
if (changes.effects) normalizedChanges = {
|
|
57
|
+
...normalizedChanges,
|
|
58
|
+
effects: normalizeEffects(changes.effects)
|
|
59
|
+
};
|
|
55
60
|
beforeUpdate?.(node, normalizedChanges);
|
|
56
61
|
graph.positionPreviewVersion++;
|
|
57
62
|
Object.assign(node, normalizedChanges);
|
package/dist/preview.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"preview.js","names":[],"sources":["../src/preview.ts"],"sourcesContent":["import { textCacheInvalidationChanges } from './text/picture'\nimport type { SceneNode } from './types'\nimport { normalizeVectorNetwork } from './vector-network'\n\nexport type NodePreviewObserver = (node: SceneNode, changes: Partial<SceneNode>) => void\n\ntype PreviewGraph = {\n nodes: Map<string, SceneNode>\n positionPreviewVersion: number\n clearAbsPosCache: () => void\n}\n\nconst LAYOUT_AFFECTING_KEYS = new Set<string>([\n 'x',\n 'y',\n 'width',\n 'height',\n 'rotation',\n 'flipX',\n 'flipY',\n 'parentId',\n 'childIds',\n 'layoutMode',\n 'layoutDirection',\n 'layoutWrap',\n 'primaryAxisSizing',\n 'counterAxisSizing',\n 'itemSpacing',\n 'counterAxisSpacing',\n 'paddingTop',\n 'paddingRight',\n 'paddingBottom',\n 'paddingLeft',\n 'layoutGrow',\n 'layoutAlignSelf',\n 'layoutPositioning',\n 'minWidth',\n 'maxWidth',\n 'minHeight',\n 'maxHeight',\n 'visible',\n 'text',\n 'fontSize',\n 'lineHeight',\n 'letterSpacing',\n 'styleRuns',\n 'textAutoResize'\n])\n\nexport function updateNodePreview(\n graph: PreviewGraph,\n id: string,\n changes: Partial<SceneNode>,\n beforeUpdate?: NodePreviewObserver\n): Partial<SceneNode> | null {\n const node = graph.nodes.get(id)\n if (!node) return null\n changes = Object.fromEntries(\n (Object.entries(changes) as Array<[string, unknown]>).filter(([, value]) => value !== undefined)\n )\n if ((Object.keys(changes) as (keyof SceneNode)[]).every((key) => node[key] === changes[key])) {\n return null\n }\n const affectsLayout = Object.keys(changes).some((key) => LAYOUT_AFFECTING_KEYS.has(key))\n if (affectsLayout) graph.clearAbsPosCache()\n let normalizedChanges = changes\n if (node.type === 'TEXT') {\n normalizedChanges = { ...textCacheInvalidationChanges(node, changes), ...changes }\n }\n if (changes.vectorNetwork) {\n normalizedChanges = {\n ...normalizedChanges,\n vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork)\n }\n }\n beforeUpdate?.(node, normalizedChanges)\n graph.positionPreviewVersion++\n Object.assign(node, normalizedChanges)\n return normalizedChanges\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"preview.js","names":[],"sources":["../src/preview.ts"],"sourcesContent":["import { normalizeEffects } from './effects'\nimport { textCacheInvalidationChanges } from './text/picture'\nimport type { SceneNode } from './types'\nimport { normalizeVectorNetwork } from './vector-network'\n\nexport type NodePreviewObserver = (node: SceneNode, changes: Partial<SceneNode>) => void\n\ntype PreviewGraph = {\n nodes: Map<string, SceneNode>\n positionPreviewVersion: number\n clearAbsPosCache: () => void\n}\n\nconst LAYOUT_AFFECTING_KEYS = new Set<string>([\n 'x',\n 'y',\n 'width',\n 'height',\n 'rotation',\n 'flipX',\n 'flipY',\n 'parentId',\n 'childIds',\n 'layoutMode',\n 'layoutDirection',\n 'layoutWrap',\n 'primaryAxisSizing',\n 'counterAxisSizing',\n 'itemSpacing',\n 'counterAxisSpacing',\n 'paddingTop',\n 'paddingRight',\n 'paddingBottom',\n 'paddingLeft',\n 'layoutGrow',\n 'layoutAlignSelf',\n 'layoutPositioning',\n 'minWidth',\n 'maxWidth',\n 'minHeight',\n 'maxHeight',\n 'visible',\n 'text',\n 'fontSize',\n 'lineHeight',\n 'letterSpacing',\n 'styleRuns',\n 'textAutoResize'\n])\n\nexport function updateNodePreview(\n graph: PreviewGraph,\n id: string,\n changes: Partial<SceneNode>,\n beforeUpdate?: NodePreviewObserver\n): Partial<SceneNode> | null {\n const node = graph.nodes.get(id)\n if (!node) return null\n changes = Object.fromEntries(\n (Object.entries(changes) as Array<[string, unknown]>).filter(([, value]) => value !== undefined)\n )\n if ((Object.keys(changes) as (keyof SceneNode)[]).every((key) => node[key] === changes[key])) {\n return null\n }\n const affectsLayout = Object.keys(changes).some((key) => LAYOUT_AFFECTING_KEYS.has(key))\n if (affectsLayout) graph.clearAbsPosCache()\n let normalizedChanges = changes\n if (node.type === 'TEXT') {\n normalizedChanges = { ...textCacheInvalidationChanges(node, changes), ...changes }\n }\n if (changes.vectorNetwork) {\n normalizedChanges = {\n ...normalizedChanges,\n vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork)\n }\n }\n if (changes.effects) {\n normalizedChanges = { ...normalizedChanges, effects: normalizeEffects(changes.effects) }\n }\n beforeUpdate?.(node, normalizedChanges)\n graph.positionPreviewVersion++\n Object.assign(node, normalizedChanges)\n return normalizedChanges\n}\n"],"mappings":";;;;AAaA,MAAM,wCAAwB,IAAI,IAAY;CAC5C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAgB,kBACd,OACA,IACA,SACA,cAC2B;CAC3B,MAAM,OAAO,MAAM,MAAM,IAAI,EAAE;CAC/B,IAAI,CAAC,MAAM,OAAO;CAClB,UAAU,OAAO,YACd,OAAO,QAAQ,OAAO,CAAC,CAA8B,QAAQ,GAAG,WAAW,UAAU,KAAA,CAAS,CACjG;CACA,IAAK,OAAO,KAAK,OAAO,CAAC,CAAyB,OAAO,QAAQ,KAAK,SAAS,QAAQ,IAAI,GACzF,OAAO;CAGT,IADsB,OAAO,KAAK,OAAO,CAAC,CAAC,MAAM,QAAQ,sBAAsB,IAAI,GAAG,CACtE,GAAG,MAAM,iBAAiB;CAC1C,IAAI,oBAAoB;CACxB,IAAI,KAAK,SAAS,QAChB,oBAAoB;EAAE,GAAG,6BAA6B,MAAM,OAAO;EAAG,GAAG;CAAQ;CAEnF,IAAI,QAAQ,eACV,oBAAoB;EAClB,GAAG;EACH,eAAe,uBAAuB,QAAQ,aAAa;CAC7D;CAEF,IAAI,QAAQ,SACV,oBAAoB;EAAE,GAAG;EAAmB,SAAS,iBAAiB,QAAQ,OAAO;CAAE;CAEzF,eAAe,MAAM,iBAAiB;CACtC,MAAM;CACN,OAAO,OAAO,MAAM,iBAAiB;CACrC,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/variables/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/variables/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;iBAkDgB,YAAY,OAAO,YAAY,UAAU;iBAQzC,eAAe,OAAO,YAAY;iBA8BlC,cAAc,OAAO,YAAY,YAAY;iBAe7C,eACd,OAAO,YACP,0BACA,cACA,MAAM,cACN,sBACA,QAAQ,gBACP;iBAsBa,iBACd,OAAO,YACP,0BACA,eACC;iBAca,iBAAiB,OAAO,YAAY;iBAWpC,cAAc,OAAO,YAAY,sBAAsB;iBAIvD,QACd,OAAO,YACP,sBACA,gBACA,cACA;;iBAgBc,WACd,OAAO,YACP,0BACA,sBACA,cACA;iBAQc,WAAW,OAAO,YAAY,sBAAsB;iBAgBpD,WACd,OAAO,YACP,sBACA,gBACA;iBAQc,eAAe,OAAO,YAAY,sBAAsB;;iBASxD,kBAAkB,YAAY,qBAAqB;iBAKnD,0BAA0B,OAAO,YAAY,uBAAuB;iBAQpE,mBAAmB,OAAO,YAAY,MAAM,eAAe;iBAgE3D,aACd,OAAO,YACP,gBACA,eACA;iBA4Ec,eAAe,OAAO,YAAY,gBAAgB"}
|
package/dist/variables/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { BLACK } from "../constants.js";
|
|
2
2
|
import { bindingOverrideField, setInstanceOverride } from "../instances/overrides.js";
|
|
3
|
-
import { BOOLEAN_BINDING_FIELDS, ICON_BINDING_FIELDS, STRING_BINDING_FIELDS, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, isNumericVariableBindingField, paintBindingTarget, uniformBindingTarget } from "./fields.js";
|
|
3
|
+
import { BOOLEAN_BINDING_FIELDS, ICON_BINDING_FIELDS, NUMERIC_FIELDS, STRING_BINDING_FIELDS, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, isNumericVariableBindingField, paintBindingTarget, uniformBindingTarget } from "./fields.js";
|
|
4
4
|
import { SCALED_RUN_BINDING_FIELDS, pinnedRunBindingScales, runBindingScale, scaleVariableBindingUnits, withBoundBindingScales } from "./units.js";
|
|
5
5
|
import { findInstanceAncestor } from "../instances/index.js";
|
|
6
6
|
import { isShaderSourcePaint, shaderOfPaint, withShaderPaints } from "../shaders/model.js";
|
|
@@ -171,6 +171,18 @@ function getVariablesForCollection(graph, collectionId) {
|
|
|
171
171
|
function getVariablesByType(graph, type) {
|
|
172
172
|
return [...graph.variables.values()].filter((v) => v.type === type);
|
|
173
173
|
}
|
|
174
|
+
const PAINT_BINDING_LISTS = ["fills", "strokes"];
|
|
175
|
+
/**
|
|
176
|
+
* Every field a binding takes, from the same sets `checkBindingFieldType` reads, so a refusal for
|
|
177
|
+
* an unknown one names what the caller can send instead of leaving them to guess.
|
|
178
|
+
*/
|
|
179
|
+
const ACCEPTED_BINDING_FIELDS = [
|
|
180
|
+
...NUMERIC_FIELDS,
|
|
181
|
+
...STRING_BINDING_FIELDS,
|
|
182
|
+
...BOOLEAN_BINDING_FIELDS,
|
|
183
|
+
...ICON_BINDING_FIELDS,
|
|
184
|
+
...PAINT_BINDING_LISTS.flatMap((list) => [`${list}/<n>/color`, `${list}/<n>/uniforms/<name>`])
|
|
185
|
+
];
|
|
174
186
|
/**
|
|
175
187
|
* Throws when a variable of `type` cannot bind to `field`, or for a field no binding takes. A
|
|
176
188
|
* paint target is checked by its caller, which also validates its index.
|
|
@@ -183,7 +195,7 @@ function checkBindingFieldType(field, type) {
|
|
|
183
195
|
if (ICON_BINDING_FIELDS.has(field) && type !== "STRING") throw new Error(`Cannot bind ${type} variable to icon field "${field}"`);
|
|
184
196
|
const uniform = uniformBindingTarget(field);
|
|
185
197
|
if (uniform && type !== "FLOAT" && type !== "COLOR" && type !== "BOOLEAN") throw new Error(`Cannot bind ${type} variable to shader input "${field}"`);
|
|
186
|
-
if (!(isNumericVariableBindingField(field) || STRING_BINDING_FIELDS.has(field) || BOOLEAN_BINDING_FIELDS.has(field) || ICON_BINDING_FIELDS.has(field) || paintBindingTarget(field) !== null || uniform !== null)) throw new Error(`Unknown binding field "${field}"`);
|
|
198
|
+
if (!(isNumericVariableBindingField(field) || STRING_BINDING_FIELDS.has(field) || BOOLEAN_BINDING_FIELDS.has(field) || ICON_BINDING_FIELDS.has(field) || paintBindingTarget(field) !== null || uniform !== null)) throw new Error(`Unknown binding field "${field}". Accepted: ${ACCEPTED_BINDING_FIELDS.join(", ")}`);
|
|
187
199
|
}
|
|
188
200
|
function bindVariable(graph, nodeId, field, variableId) {
|
|
189
201
|
const node = graph.nodes.get(nodeId);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/variables/index.ts"],"sourcesContent":["import { partition } from 'es-toolkit/array'\nimport { omit, omitBy } from 'es-toolkit/object'\n\nimport { BLACK } from '../constants'\nimport type { SceneGraph } from '../graph'\nimport { findInstanceAncestor } from '../instances'\nimport { bindingOverrideField, setInstanceOverride } from '../instances/overrides'\nimport { isShaderSourcePaint, shaderOfPaint, withShaderPaints } from '../shaders/model'\nimport type {\n SceneNode,\n Variable,\n VariableCollection,\n VariableCollectionMode,\n VariableType,\n VariableValue\n} from '../types'\nimport {\n isNumericVariableBindingField,\n variableBindingOwner,\n assignVariableBindingUnits\n} from './bindings'\nimport {\n BOOLEAN_BINDING_FIELDS,\n ICON_BINDING_FIELDS,\n paintBindingTarget,\n STRING_BINDING_FIELDS,\n TEXT_CONTENT_VARIABLE_TYPES,\n uniformBindingTarget,\n VISIBILITY_VARIABLE_TYPES\n} from './fields'\nimport { pinnedRunBindingScales } from './units'\n\nexport * from './resolution'\n\n/**\n * Gives the runs that bind `fields` the scale they resolve with as their own, before the layer's\n * scale for those fields changes or goes, and the change to announce.\n */\nfunction pinRunBindingScales(\n node: SceneNode,\n fields: readonly string[]\n): Pick<Partial<SceneNode>, 'styleRuns'> {\n const styleRuns = pinnedRunBindingScales(node, fields)\n if (!styleRuns) return {}\n node.styleRuns = styleRuns\n return { styleRuns }\n}\n\nexport function addVariable(graph: SceneGraph, variable: Variable): void {\n graph.variables.set(variable.id, variable)\n const collection = graph.variableCollections.get(variable.collectionId)\n if (collection && !collection.variableIds.includes(variable.id)) {\n collection.variableIds.push(variable.id)\n }\n}\n\nexport function removeVariable(graph: SceneGraph, id: string): void {\n const variable = graph.variables.get(id)\n if (!variable) return\n graph.variables.delete(id)\n const collection = graph.variableCollections.get(variable.collectionId)\n if (collection) {\n collection.variableIds = collection.variableIds.filter((vid) => vid !== id)\n }\n for (const node of graph.nodes.values()) {\n const hadBinding = Object.values(node.boundVariables).includes(id)\n if (!hadBinding) continue\n graph.willChangeNode(node)\n node.boundVariables = omitBy(node.boundVariables, (varId) => varId === id) as Record<\n string,\n string\n >\n const pruned = Object.keys(node.variableBindingScales).filter(\n (field) => !(field in node.boundVariables)\n )\n const runs = pinRunBindingScales(node, pruned)\n node.variableBindingScales = omit(node.variableBindingScales, pruned)\n graph.emitter.emit('node:updated', node.id, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales },\n ...runs\n })\n markBoundVariablesOverrideOnInstance(graph, node.id)\n }\n}\n\nexport function addCollection(graph: SceneGraph, collection: VariableCollection): void {\n graph.variableCollections.set(collection.id, collection)\n if (!graph.activeMode.has(collection.id)) {\n graph.activeMode.set(collection.id, collection.defaultModeId)\n }\n}\n\nfunction defaultVariableValue(type: VariableType, value?: VariableValue): VariableValue {\n if (value !== undefined) return value\n if (type === 'COLOR') return { ...BLACK }\n if (type === 'FLOAT') return 0\n if (type === 'BOOLEAN') return false\n return ''\n}\n\nexport function createVariable(\n graph: SceneGraph,\n generateId: () => string,\n name: string,\n type: VariableType,\n collectionId: string,\n value?: VariableValue\n): Variable {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) throw new Error(`Collection \"${collectionId}\" not found`)\n const id = generateId()\n const defaultValue = defaultVariableValue(type, value)\n const valuesByMode: Record<string, VariableValue> = {}\n for (const mode of collection.modes) {\n valuesByMode[mode.modeId] = structuredClone(defaultValue)\n }\n const variable: Variable = {\n id,\n name,\n type,\n collectionId,\n valuesByMode,\n description: '',\n hiddenFromPublishing: false\n }\n addVariable(graph, variable)\n return variable\n}\n\nexport function createCollection(\n graph: SceneGraph,\n generateId: () => string,\n name: string\n): VariableCollection {\n const id = generateId()\n const modeId = generateId()\n const collection: VariableCollection = {\n id,\n name,\n modes: [{ modeId, name: 'Mode 1' }],\n defaultModeId: modeId,\n variableIds: []\n }\n addCollection(graph, collection)\n return collection\n}\n\nexport function removeCollection(graph: SceneGraph, id: string): void {\n const collection = graph.variableCollections.get(id)\n if (collection) {\n for (const varId of Array.from(collection.variableIds)) {\n removeVariable(graph, varId)\n }\n }\n graph.variableCollections.delete(id)\n graph.activeMode.delete(id)\n}\n\nexport function setActiveMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n graph.activeMode.set(collectionId, modeId)\n}\n\nexport function addMode(\n graph: SceneGraph,\n collectionId: string,\n modeId: string,\n name: string,\n sourceMode?: string\n): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n collection.modes.push({ modeId, name })\n const sourceModeId = sourceMode ?? collection.defaultModeId\n for (const varId of collection.variableIds) {\n const variable = graph.variables.get(varId)\n if (!variable) continue\n variable.valuesByMode[modeId] = structuredClone(\n variable.valuesByMode[sourceModeId] ?? Object.values(variable.valuesByMode)[0]\n )\n }\n}\n\n/** Add a mode with a new ID from `generateId`; undo and redo replay it with `addMode`. */\nexport function createMode(\n graph: SceneGraph,\n generateId: () => string,\n collectionId: string,\n name: string,\n sourceMode?: string\n): string | undefined {\n if (!graph.variableCollections.has(collectionId)) return undefined\n const modeId = generateId()\n addMode(graph, collectionId, modeId, name, sourceMode)\n return modeId\n}\n\nexport function removeMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection || collection.modes.length <= 1) return\n collection.modes = collection.modes.filter((m) => m.modeId !== modeId)\n if (collection.defaultModeId === modeId) {\n collection.defaultModeId = collection.modes[0].modeId\n }\n for (const varId of collection.variableIds) {\n const variable = graph.variables.get(varId)\n if (variable) variable.valuesByMode = omit(variable.valuesByMode, [modeId])\n }\n if (graph.activeMode.get(collectionId) === modeId) {\n graph.activeMode.set(collectionId, collection.defaultModeId)\n }\n}\n\nexport function renameMode(\n graph: SceneGraph,\n collectionId: string,\n modeId: string,\n name: string\n): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n const mode = collection.modes.find((m) => m.modeId === modeId)\n if (mode) mode.name = name\n}\n\nexport function setDefaultMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n if (!collection.modes.some((m) => m.modeId === modeId)) return\n collection.defaultModeId = modeId\n collection.modes = modesDefaultFirst(collection)\n}\n\n/** Figma has no default-mode field: the first mode is the default. */\nexport function modesDefaultFirst(collection: VariableCollection): VariableCollectionMode[] {\n const [defaults, rest] = partition(collection.modes, (m) => m.modeId === collection.defaultModeId)\n return [...defaults, ...rest]\n}\n\nexport function getVariablesForCollection(graph: SceneGraph, collectionId: string): Variable[] {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return []\n return collection.variableIds\n .map((id) => graph.variables.get(id))\n .filter((v): v is Variable => v !== undefined)\n}\n\nexport function getVariablesByType(graph: SceneGraph, type: VariableType): Variable[] {\n return [...graph.variables.values()].filter((v) => v.type === type)\n}\n\n/**\n * Throws when a variable of `type` cannot bind to `field`, or for a field no binding takes. A\n * paint target is checked by its caller, which also validates its index.\n */\nfunction checkBindingFieldType(field: string, type: VariableType): void {\n if (isNumericVariableBindingField(field) && type !== 'FLOAT') {\n throw new Error(`Cannot bind ${type} variable to scalar field \"${field}\"`)\n }\n\n const textTypes: readonly VariableType[] =\n field === 'text' ? TEXT_CONTENT_VARIABLE_TYPES : ['STRING']\n if (STRING_BINDING_FIELDS.has(field) && !textTypes.includes(type)) {\n throw new Error(`Cannot bind ${type} variable to string field \"${field}\"`)\n }\n\n if (\n BOOLEAN_BINDING_FIELDS.has(field) &&\n !VISIBILITY_VARIABLE_TYPES.some((kind) => kind === type)\n ) {\n throw new Error(`Cannot bind ${type} variable to boolean field \"${field}\"`)\n }\n\n if (ICON_BINDING_FIELDS.has(field) && type !== 'STRING') {\n throw new Error(`Cannot bind ${type} variable to icon field \"${field}\"`)\n }\n\n // A shader uniform takes a number, a colour, or a boolean; its shader declares which.\n const uniform = uniformBindingTarget(field)\n if (uniform && type !== 'FLOAT' && type !== 'COLOR' && type !== 'BOOLEAN') {\n throw new Error(`Cannot bind ${type} variable to shader input \"${field}\"`)\n }\n\n const isKnownField =\n isNumericVariableBindingField(field) ||\n STRING_BINDING_FIELDS.has(field) ||\n BOOLEAN_BINDING_FIELDS.has(field) ||\n ICON_BINDING_FIELDS.has(field) ||\n paintBindingTarget(field) !== null ||\n uniform !== null\n\n if (!isKnownField) {\n throw new Error(`Unknown binding field \"${field}\"`)\n }\n}\nexport function bindVariable(\n graph: SceneGraph,\n nodeId: string,\n field: string,\n variableId: string\n): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n\n // Validate variable exists\n const variable = graph.variables.get(variableId)\n if (!variable) {\n throw new Error(`Variable \"${variableId}\" not found`)\n }\n\n // Color fields require COLOR variable type\n const paint = paintBindingTarget(field)\n if (paint) {\n if (variable.type !== 'COLOR') {\n throw new Error(`Cannot bind ${variable.type} variable to color field \"${field}\"`)\n }\n // Validate index is within current array bounds\n const currentLength = node[paint.list].length\n if (paint.index >= currentLength) {\n throw new Error(\n `Index ${paint.index} out of range for ${paint.list} (length ${currentLength})`\n )\n }\n // Auto-remove top-level dead binding (e.g. 'fills') when setting indexed binding\n if (paint.list in node.boundVariables) {\n node.boundVariables = omit(node.boundVariables, [paint.list])\n }\n }\n\n checkBindingFieldType(field, variable.type)\n\n // A shader input belongs to one paint, so its index must exist on the layer.\n const uniform = uniformBindingTarget(field)\n if (uniform && uniform.index >= node[uniform.list].length) {\n throw new Error(\n `Index ${uniform.index} out of range for ${uniform.list} (length ${node[uniform.list].length})`\n )\n }\n if (uniform) {\n // The binding lives with the shader entry, next to the value it resolves, so any renderer\n // that draws the paint resolves it the same way.\n const paints = node[uniform.list]\n const paint = paints.at(uniform.index)\n const shader = paint ? shaderOfPaint(node, paint) : null\n if (paint && shader && isShaderSourcePaint(shader)) {\n node.pluginData = withShaderPaints(node, paints, [\n {\n ...shader,\n uniformBindings: {\n ...shader.uniformBindings,\n [uniform.name]: variableId\n }\n }\n ])\n }\n graph.willChangeNode(node)\n graph.emitter.emit('node:updated', nodeId, {\n pluginData: node.pluginData,\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales }\n })\n return\n }\n graph.willChangeNode(node)\n node.boundVariables = { ...node.boundVariables, [field]: variableId }\n const runs = pinRunBindingScales(node, [field])\n assignVariableBindingUnits(graph, node, field)\n markBoundVariablesOverrideOnInstance(graph, nodeId, field)\n graph.emitter.emit('node:updated', nodeId, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales },\n ...runs\n })\n}\n\nexport function unbindVariable(graph: SceneGraph, nodeId: string, field: string): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n if (!(field in node.boundVariables)) return\n graph.willChangeNode(node)\n node.boundVariables = omit(node.boundVariables, [field])\n const runs = pinRunBindingScales(node, [field])\n node.variableBindingScales = omit(node.variableBindingScales, [field])\n markBoundVariablesOverrideOnInstance(graph, nodeId, field)\n graph.emitter.emit('node:updated', nodeId, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales },\n ...runs\n })\n}\n\nfunction markBoundVariablesOverrideOnInstance(\n graph: SceneGraph,\n nodeId: string,\n field?: string\n): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n\n const owner = variableBindingOwner(graph, node)\n if (owner.type !== 'INSTANCE') return\n const nearest = findInstanceAncestor(graph, nodeId)\n if (nearest) setInstanceOverride(nearest.instanceOverrides, nearest.id, nodeId, 'boundVariables')\n setInstanceOverride(owner.instanceOverrides, owner.id, nodeId, 'boundVariables')\n if (field)\n setInstanceOverride(\n owner.instanceOverrides,\n owner.id,\n nodeId,\n bindingOverrideField(field),\n node.boundVariables[field] ?? null\n )\n}\n\nexport * from './bindings'\nexport * from './corners'\nexport * from './formula'\nexport * from './formula/schema'\nexport * from './schema'\nex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,IAAI,CAAC,MAAM;CACX,IAAI,EAAE,SAAS,KAAK,iBAAiB;CACrC,MAAM,eAAe,IAAI;CACzB,KAAK,iBAAiB,KAAK,KAAK,gBAAgB,CAAC,KAAK,CAAC;CACvD,MAAM,OAAO,oBAAoB,MAAM,CAAC,KAAK,CAAC;CAC9C,KAAK,wBAAwB,KAAK,KAAK,uBAAuB,CAAC,KAAK,CAAC;CACrE,qCAAqC,OAAO,QAAQ,KAAK;CACzD,MAAM,QAAQ,KAAK,gBAAgB,QAAQ;EACzC,gBAAgB,EAAE,GAAG,KAAK,eAAe;EACzC,uBAAuB,EAAE,GAAG,KAAK,sBAAsB;EACvD,GAAG;CACL,CAAC;AACH;AAEA,SAAS,qCACP,OACA,QACA,OACM;CACN,MAAM,OAAO,MAAM,MAAM,IAAI,MAAM;CACnC,IAAI,CAAC,MAAM;CAEX,MAAM,QAAQ,qBAAqB,OAAO,IAAI;CAC9C,IAAI,MAAM,SAAS,YAAY;CAC/B,MAAM,UAAU,qBAAqB,OAAO,MAAM;CAClD,IAAI,SAAS,oBAAoB,QAAQ,mBAAmB,QAAQ,IAAI,QAAQ,gBAAgB;CAChG,oBAAoB,MAAM,mBAAmB,MAAM,IAAI,QAAQ,gBAAgB;CAC/E,IAAI,OACF,oBACE,MAAM,mBACN,MAAM,IACN,QACA,qBAAqB,KAAK,GAC1B,KAAK,eAAe,UAAU,IAChC;AACJ"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/variables/index.ts"],"sourcesContent":["import { partition } from 'es-toolkit/array'\nimport { omit, omitBy } from 'es-toolkit/object'\n\nimport { BLACK } from '../constants'\nimport type { SceneGraph } from '../graph'\nimport { findInstanceAncestor } from '../instances'\nimport { bindingOverrideField, setInstanceOverride } from '../instances/overrides'\nimport { isShaderSourcePaint, shaderOfPaint, withShaderPaints } from '../shaders/model'\nimport type {\n SceneNode,\n Variable,\n VariableCollection,\n VariableCollectionMode,\n VariableType,\n VariableValue\n} from '../types'\nimport {\n isNumericVariableBindingField,\n variableBindingOwner,\n assignVariableBindingUnits\n} from './bindings'\nimport {\n BOOLEAN_BINDING_FIELDS,\n ICON_BINDING_FIELDS,\n NUMERIC_FIELDS,\n paintBindingTarget,\n STRING_BINDING_FIELDS,\n TEXT_CONTENT_VARIABLE_TYPES,\n uniformBindingTarget,\n VISIBILITY_VARIABLE_TYPES,\n type PaintBindingList\n} from './fields'\nimport { pinnedRunBindingScales } from './units'\n\nexport * from './resolution'\n\n/**\n * Gives the runs that bind `fields` the scale they resolve with as their own, before the layer's\n * scale for those fields changes or goes, and the change to announce.\n */\nfunction pinRunBindingScales(\n node: SceneNode,\n fields: readonly string[]\n): Pick<Partial<SceneNode>, 'styleRuns'> {\n const styleRuns = pinnedRunBindingScales(node, fields)\n if (!styleRuns) return {}\n node.styleRuns = styleRuns\n return { styleRuns }\n}\n\nexport function addVariable(graph: SceneGraph, variable: Variable): void {\n graph.variables.set(variable.id, variable)\n const collection = graph.variableCollections.get(variable.collectionId)\n if (collection && !collection.variableIds.includes(variable.id)) {\n collection.variableIds.push(variable.id)\n }\n}\n\nexport function removeVariable(graph: SceneGraph, id: string): void {\n const variable = graph.variables.get(id)\n if (!variable) return\n graph.variables.delete(id)\n const collection = graph.variableCollections.get(variable.collectionId)\n if (collection) {\n collection.variableIds = collection.variableIds.filter((vid) => vid !== id)\n }\n for (const node of graph.nodes.values()) {\n const hadBinding = Object.values(node.boundVariables).includes(id)\n if (!hadBinding) continue\n graph.willChangeNode(node)\n node.boundVariables = omitBy(node.boundVariables, (varId) => varId === id) as Record<\n string,\n string\n >\n const pruned = Object.keys(node.variableBindingScales).filter(\n (field) => !(field in node.boundVariables)\n )\n const runs = pinRunBindingScales(node, pruned)\n node.variableBindingScales = omit(node.variableBindingScales, pruned)\n graph.emitter.emit('node:updated', node.id, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales },\n ...runs\n })\n markBoundVariablesOverrideOnInstance(graph, node.id)\n }\n}\n\nexport function addCollection(graph: SceneGraph, collection: VariableCollection): void {\n graph.variableCollections.set(collection.id, collection)\n if (!graph.activeMode.has(collection.id)) {\n graph.activeMode.set(collection.id, collection.defaultModeId)\n }\n}\n\nfunction defaultVariableValue(type: VariableType, value?: VariableValue): VariableValue {\n if (value !== undefined) return value\n if (type === 'COLOR') return { ...BLACK }\n if (type === 'FLOAT') return 0\n if (type === 'BOOLEAN') return false\n return ''\n}\n\nexport function createVariable(\n graph: SceneGraph,\n generateId: () => string,\n name: string,\n type: VariableType,\n collectionId: string,\n value?: VariableValue\n): Variable {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) throw new Error(`Collection \"${collectionId}\" not found`)\n const id = generateId()\n const defaultValue = defaultVariableValue(type, value)\n const valuesByMode: Record<string, VariableValue> = {}\n for (const mode of collection.modes) {\n valuesByMode[mode.modeId] = structuredClone(defaultValue)\n }\n const variable: Variable = {\n id,\n name,\n type,\n collectionId,\n valuesByMode,\n description: '',\n hiddenFromPublishing: false\n }\n addVariable(graph, variable)\n return variable\n}\n\nexport function createCollection(\n graph: SceneGraph,\n generateId: () => string,\n name: string\n): VariableCollection {\n const id = generateId()\n const modeId = generateId()\n const collection: VariableCollection = {\n id,\n name,\n modes: [{ modeId, name: 'Mode 1' }],\n defaultModeId: modeId,\n variableIds: []\n }\n addCollection(graph, collection)\n return collection\n}\n\nexport function removeCollection(graph: SceneGraph, id: string): void {\n const collection = graph.variableCollections.get(id)\n if (collection) {\n for (const varId of Array.from(collection.variableIds)) {\n removeVariable(graph, varId)\n }\n }\n graph.variableCollections.delete(id)\n graph.activeMode.delete(id)\n}\n\nexport function setActiveMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n graph.activeMode.set(collectionId, modeId)\n}\n\nexport function addMode(\n graph: SceneGraph,\n collectionId: string,\n modeId: string,\n name: string,\n sourceMode?: string\n): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n collection.modes.push({ modeId, name })\n const sourceModeId = sourceMode ?? collection.defaultModeId\n for (const varId of collection.variableIds) {\n const variable = graph.variables.get(varId)\n if (!variable) continue\n variable.valuesByMode[modeId] = structuredClone(\n variable.valuesByMode[sourceModeId] ?? Object.values(variable.valuesByMode)[0]\n )\n }\n}\n\n/** Add a mode with a new ID from `generateId`; undo and redo replay it with `addMode`. */\nexport function createMode(\n graph: SceneGraph,\n generateId: () => string,\n collectionId: string,\n name: string,\n sourceMode?: string\n): string | undefined {\n if (!graph.variableCollections.has(collectionId)) return undefined\n const modeId = generateId()\n addMode(graph, collectionId, modeId, name, sourceMode)\n return modeId\n}\n\nexport function removeMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection || collection.modes.length <= 1) return\n collection.modes = collection.modes.filter((m) => m.modeId !== modeId)\n if (collection.defaultModeId === modeId) {\n collection.defaultModeId = collection.modes[0].modeId\n }\n for (const varId of collection.variableIds) {\n const variable = graph.variables.get(varId)\n if (variable) variable.valuesByMode = omit(variable.valuesByMode, [modeId])\n }\n if (graph.activeMode.get(collectionId) === modeId) {\n graph.activeMode.set(collectionId, collection.defaultModeId)\n }\n}\n\nexport function renameMode(\n graph: SceneGraph,\n collectionId: string,\n modeId: string,\n name: string\n): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n const mode = collection.modes.find((m) => m.modeId === modeId)\n if (mode) mode.name = name\n}\n\nexport function setDefaultMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n if (!collection.modes.some((m) => m.modeId === modeId)) return\n collection.defaultModeId = modeId\n collection.modes = modesDefaultFirst(collection)\n}\n\n/** Figma has no default-mode field: the first mode is the default. */\nexport function modesDefaultFirst(collection: VariableCollection): VariableCollectionMode[] {\n const [defaults, rest] = partition(collection.modes, (m) => m.modeId === collection.defaultModeId)\n return [...defaults, ...rest]\n}\n\nexport function getVariablesForCollection(graph: SceneGraph, collectionId: string): Variable[] {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return []\n return collection.variableIds\n .map((id) => graph.variables.get(id))\n .filter((v): v is Variable => v !== undefined)\n}\n\nexport function getVariablesByType(graph: SceneGraph, type: VariableType): Variable[] {\n return [...graph.variables.values()].filter((v) => v.type === type)\n}\n\nconst PAINT_BINDING_LISTS = ['fills', 'strokes'] as const satisfies readonly PaintBindingList[]\n\n/**\n * Every field a binding takes, from the same sets `checkBindingFieldType` reads, so a refusal for\n * an unknown one names what the caller can send instead of leaving them to guess.\n */\nconst ACCEPTED_BINDING_FIELDS: readonly string[] = [\n ...NUMERIC_FIELDS,\n ...STRING_BINDING_FIELDS,\n ...BOOLEAN_BINDING_FIELDS,\n ...ICON_BINDING_FIELDS,\n ...PAINT_BINDING_LISTS.flatMap((list) => [`${list}/<n>/color`, `${list}/<n>/uniforms/<name>`])\n]\n\n/**\n * Throws when a variable of `type` cannot bind to `field`, or for a field no binding takes. A\n * paint target is checked by its caller, which also validates its index.\n */\nfunction checkBindingFieldType(field: string, type: VariableType): void {\n if (isNumericVariableBindingField(field) && type !== 'FLOAT') {\n throw new Error(`Cannot bind ${type} variable to scalar field \"${field}\"`)\n }\n\n const textTypes: readonly VariableType[] =\n field === 'text' ? TEXT_CONTENT_VARIABLE_TYPES : ['STRING']\n if (STRING_BINDING_FIELDS.has(field) && !textTypes.includes(type)) {\n throw new Error(`Cannot bind ${type} variable to string field \"${field}\"`)\n }\n\n if (\n BOOLEAN_BINDING_FIELDS.has(field) &&\n !VISIBILITY_VARIABLE_TYPES.some((kind) => kind === type)\n ) {\n throw new Error(`Cannot bind ${type} variable to boolean field \"${field}\"`)\n }\n\n if (ICON_BINDING_FIELDS.has(field) && type !== 'STRING') {\n throw new Error(`Cannot bind ${type} variable to icon field \"${field}\"`)\n }\n\n // A shader uniform takes a number, a colour, or a boolean; its shader declares which.\n const uniform = uniformBindingTarget(field)\n if (uniform && type !== 'FLOAT' && type !== 'COLOR' && type !== 'BOOLEAN') {\n throw new Error(`Cannot bind ${type} variable to shader input \"${field}\"`)\n }\n\n const isKnownField =\n isNumericVariableBindingField(field) ||\n STRING_BINDING_FIELDS.has(field) ||\n BOOLEAN_BINDING_FIELDS.has(field) ||\n ICON_BINDING_FIELDS.has(field) ||\n paintBindingTarget(field) !== null ||\n uniform !== null\n\n if (!isKnownField) {\n throw new Error(\n `Unknown binding field \"${field}\". Accepted: ${ACCEPTED_BINDING_FIELDS.join(', ')}`\n )\n }\n}\nexport function bindVariable(\n graph: SceneGraph,\n nodeId: string,\n field: string,\n variableId: string\n): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n\n // Validate variable exists\n const variable = graph.variables.get(variableId)\n if (!variable) {\n throw new Error(`Variable \"${variableId}\" not found`)\n }\n\n // Color fields require COLOR variable type\n const paint = paintBindingTarget(field)\n if (paint) {\n if (variable.type !== 'COLOR') {\n throw new Error(`Cannot bind ${variable.type} variable to color field \"${field}\"`)\n }\n // Validate index is within current array bounds\n const currentLength = node[paint.list].length\n if (paint.index >= currentLength) {\n throw new Error(\n `Index ${paint.index} out of range for ${paint.list} (length ${currentLength})`\n )\n }\n // Auto-remove top-level dead binding (e.g. 'fills') when setting indexed binding\n if (paint.list in node.boundVariables) {\n node.boundVariables = omit(node.boundVariables, [paint.list])\n }\n }\n\n checkBindingFieldType(field, variable.type)\n\n // A shader input belongs to one paint, so its index must exist on the layer.\n const uniform = uniformBindingTarget(field)\n if (uniform && uniform.index >= node[uniform.list].length) {\n throw new Error(\n `Index ${uniform.index} out of range for ${uniform.list} (length ${node[uniform.list].length})`\n )\n }\n if (uniform) {\n // The binding lives with the shader entry, next to the value it resolves, so any renderer\n // that draws the paint resolves it the same way.\n const paints = node[uniform.list]\n const paint = paints.at(uniform.index)\n const shader = paint ? shaderOfPaint(node, paint) : null\n if (paint && shader && isShaderSourcePaint(shader)) {\n node.pluginData = withShaderPaints(node, paints, [\n {\n ...shader,\n uniformBindings: {\n ...shader.uniformBindings,\n [uniform.name]: variableId\n }\n }\n ])\n }\n graph.willChangeNode(node)\n graph.emitter.emit('node:updated', nodeId, {\n pluginData: node.pluginData,\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales }\n })\n return\n }\n graph.willChangeNode(node)\n node.boundVariables = { ...node.boundVariables, [field]: variableId }\n const runs = pinRunBindingScales(node, [field])\n assignVariableBindingUnits(graph, node, field)\n markBoundVariablesOverrideOnInstance(graph, nodeId, field)\n graph.emitter.emit('node:updated', nodeId, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales },\n ...runs\n })\n}\n\nexport function unbindVariable(graph: SceneGraph, nodeId: string, field: string): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n if (!(field in node.boundVariables)) return\n graph.willChangeNode(node)\n node.boundVariables = omit(node.boundVariables, [field])\n const runs = pinRunBindingScales(node, [field])\n node.variableBindingScales = omit(node.variableBindingScales, [field])\n markBoundVariablesOverrideOnInstance(graph, nodeId, field)\n graph.emitter.emit('node:updated', nodeId, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales },\n ...runs\n })\n}\n\nfunction markBoundVariablesOverrideOnInstance(\n graph: SceneGraph,\n nodeId: string,\n field?: string\n): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n\n const owner = variableBindingOwner(graph, node)\n if (owner.type !== 'INSTANCE') return\n const nearest = findInstanceAncestor(graph, nodeId)\n if (nearest) setInstanceOverride(nearest.instanceOverrides, nearest.id, nodeId, 'boundVariables')\n setInstanceOverride(owner.instanceOverrides, owner.id, nodeId, 'boundVariables')\n if (field)\n setInstanceOverride(\n owner.instanceOverrides,\n owner.id,\n nodeId,\n bindingOverrideField(field),\n node.boundVariables[field] ?? null\n )\n}\n\nexport * from './bindings'\nexport * from './corners'\nexport * from './formula'\nexport * from './formula/schema'\nexport * from './schema'\nexport * from './text'\nexport * from './token'\nexport * from './units'\nexport * from './value'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAS,oBACP,MAC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B;EACvD,GAAG;CACL,CAAC;AACH;AAEA,SAAgB,eAAe,OAAmB,QAAgB,OAAqB;CACrF,MAAM,OAAO,MAAM,MAAM,IAAI,MAAM;CACnC,IAAI,CAAC,MAAM;CACX,IAAI,EAAE,SAAS,KAAK,iBAAiB;CACrC,MAAM,eAAe,IAAI;CACzB,KAAK,iBAAiB,KAAK,KAAK,gBAAgB,CAAC,KAAK,CAAC;CACvD,MAAM,OAAO,oBAAoB,MAAM,CAAC,KAAK,CAAC;CAC9C,KAAK,wBAAwB,KAAK,KAAK,uBAAuB,CAAC,KAAK,CAAC;CACrE,qCAAqC,OAAO,QAAQ,KAAK;CACzD,MAAM,QAAQ,KAAK,gBAAgB,QAAQ;EACzC,gBAAgB,EAAE,GAAG,KAAK,eAAe;EACzC,uBAAuB,EAAE,GAAG,KAAK,sBAAsB;EACvD,GAAG;CACL,CAAC;AACH;AAEA,SAAS,qCACP,OACA,QACA,OACM;CACN,MAAM,OAAO,MAAM,MAAM,IAAI,MAAM;CACnC,IAAI,CAAC,MAAM;CAEX,MAAM,QAAQ,qBAAqB,OAAO,IAAI;CAC9C,IAAI,MAAM,SAAS,YAAY;CAC/B,MAAM,UAAU,qBAAqB,OAAO,MAAM;CAClD,IAAI,SAAS,oBAAoB,QAAQ,mBAAmB,QAAQ,IAAI,QAAQ,gBAAgB;CAChG,oBAAoB,MAAM,mBAAmB,MAAM,IAAI,QAAQ,gBAAgB;CAC/E,IAAI,OACF,oBACE,MAAM,mBACN,MAAM,IACN,QACA,qBAAqB,KAAK,GAC1B,KAAK,eAAe,UAAU,IAChC;AACJ"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pairdraw/scene-graph",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist",
|
|
@@ -95,6 +95,11 @@
|
|
|
95
95
|
"import": "./dist/css/index.js",
|
|
96
96
|
"default": "./dist/css/index.js"
|
|
97
97
|
},
|
|
98
|
+
"./effects": {
|
|
99
|
+
"types": "./dist/effects.d.ts",
|
|
100
|
+
"import": "./dist/effects.js",
|
|
101
|
+
"default": "./dist/effects.js"
|
|
102
|
+
},
|
|
98
103
|
"./export-format": {
|
|
99
104
|
"types": "./dist/export-format.d.ts",
|
|
100
105
|
"import": "./dist/export-format.js",
|
package/src/color/index.ts
CHANGED
|
@@ -2,6 +2,7 @@ export * from './contrast'
|
|
|
2
2
|
export * from './management'
|
|
3
3
|
export { normalizeColor } from './normalize'
|
|
4
4
|
export * from './okhcl'
|
|
5
|
+
export { colorSchema } from './schema'
|
|
5
6
|
|
|
6
7
|
import { parse, formatHex, formatHex8, formatRgb, converter, differenceEuclidean } from 'culori'
|
|
7
8
|
|
package/src/copy.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* no shared references between source and copy.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
+
import { normalizeEffects } from './effects'
|
|
11
12
|
import { geometryCommandCoordCount } from './geometry'
|
|
12
13
|
import { cloneInstanceOverrideState } from './instances/overrides'
|
|
13
14
|
import { createDefaultSourceMetadata } from './node-defaults'
|
|
@@ -55,10 +56,12 @@ export function copyStroke(s: Stroke): Stroke {
|
|
|
55
56
|
|
|
56
57
|
export function copyEffect(e: Effect): Effect {
|
|
57
58
|
if (e.type === 'SHADER') return structuredClone(e)
|
|
59
|
+
const normalized = normalizeEffects([e])[0] ?? e
|
|
60
|
+
if (normalized.type === 'SHADER') return structuredClone(normalized)
|
|
58
61
|
return {
|
|
59
|
-
...
|
|
60
|
-
color: { ...
|
|
61
|
-
offset: { ...
|
|
62
|
+
...normalized,
|
|
63
|
+
color: { ...normalized.color },
|
|
64
|
+
offset: { ...normalized.offset }
|
|
62
65
|
}
|
|
63
66
|
}
|
|
64
67
|
|
package/src/effects.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { Vector } from './primitives'
|
|
2
|
+
import type { Effect, ShaderEffect, ShadowEffect } from './types'
|
|
3
|
+
|
|
4
|
+
const SHADOW_OFFSET: Vector = { x: 0, y: 4 }
|
|
5
|
+
const BLUR_OFFSET: Vector = { x: 0, y: 0 }
|
|
6
|
+
|
|
7
|
+
/** A shadow or blur whose offset may still be missing or only partly present. */
|
|
8
|
+
type ShadowInput = Omit<ShadowEffect, 'offset'> & {
|
|
9
|
+
offset?: Partial<Vector> | null
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function fallbackOffset(type: ShadowEffect['type']): Vector {
|
|
13
|
+
return type === 'DROP_SHADOW' || type === 'INNER_SHADOW' ? SHADOW_OFFSET : BLUR_OFFSET
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function component(offset: object, key: 'x' | 'y', fallback: number): number {
|
|
17
|
+
if (!(key in offset)) return fallback
|
|
18
|
+
const value: unknown = Reflect.get(offset, key)
|
|
19
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : fallback
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** A new offset when `effect.offset` is missing or not finite; null when it can stay. */
|
|
23
|
+
function finiteOffset(effect: ShadowInput): Vector | null {
|
|
24
|
+
const fallback = fallbackOffset(effect.type)
|
|
25
|
+
const offset: unknown = effect.offset
|
|
26
|
+
if (offset === null || typeof offset !== 'object') return { x: fallback.x, y: fallback.y }
|
|
27
|
+
const x = component(offset, 'x', fallback.x)
|
|
28
|
+
const y = component(offset, 'y', fallback.y)
|
|
29
|
+
if (Reflect.get(offset, 'x') === x && Reflect.get(offset, 'y') === y) return null
|
|
30
|
+
return { x, y }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function isStoredShadow(effect: ShadowInput): effect is ShadowEffect {
|
|
34
|
+
const offset = effect.offset
|
|
35
|
+
return (
|
|
36
|
+
!!offset &&
|
|
37
|
+
typeof offset.x === 'number' &&
|
|
38
|
+
Number.isFinite(offset.x) &&
|
|
39
|
+
typeof offset.y === 'number' &&
|
|
40
|
+
Number.isFinite(offset.y)
|
|
41
|
+
)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function withFiniteOffset(effect: ShadowInput): Effect {
|
|
45
|
+
const offset = finiteOffset(effect)
|
|
46
|
+
if (!offset) {
|
|
47
|
+
if (isStoredShadow(effect)) return effect
|
|
48
|
+
return { ...effect, offset: fallbackOffset(effect.type) }
|
|
49
|
+
}
|
|
50
|
+
return { ...effect, offset }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function isStoredEffect(effect: ShaderEffect | ShadowInput): effect is Effect {
|
|
54
|
+
return effect.type === 'SHADER' || isStoredShadow(effect)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Shadows and blurs keep a finite offset. A drop or inner shadow missing one uses `{x: 0, y: 4}`,
|
|
59
|
+
* the same default as `dropShadow()` and `set_effects`; a blur uses `{x: 0, y: 0}`. Shader effects
|
|
60
|
+
* are left alone. An array that is already valid is returned as itself.
|
|
61
|
+
*/
|
|
62
|
+
export function normalizeEffects(effects: (ShaderEffect | ShadowInput)[]): Effect[] {
|
|
63
|
+
let next: Effect[] | null = null
|
|
64
|
+
for (const [index, effect] of effects.entries()) {
|
|
65
|
+
const normalized = effect.type === 'SHADER' ? effect : withFiniteOffset(effect)
|
|
66
|
+
if (normalized === effect) {
|
|
67
|
+
if (next && isStoredEffect(effect)) next.push(effect)
|
|
68
|
+
continue
|
|
69
|
+
}
|
|
70
|
+
next ??= effects.slice(0, index).filter(isStoredEffect)
|
|
71
|
+
next.push(normalized)
|
|
72
|
+
}
|
|
73
|
+
if (next) return next
|
|
74
|
+
if (effects.every(isStoredEffect)) return effects
|
|
75
|
+
return effects.filter(isStoredEffect)
|
|
76
|
+
}
|
package/src/graph.ts
CHANGED
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
localTransformFromWorld
|
|
13
13
|
} from './coordinate'
|
|
14
14
|
import { cloneNodeProps, type NodeCloneMode } from './copy'
|
|
15
|
+
import { normalizeEffects } from './effects'
|
|
15
16
|
import { bindNodeEvents } from './events'
|
|
16
17
|
import { LAYOUT_AFFECTING_KEYS } from './fields/layout'
|
|
17
18
|
import { withGeneratedFrameSize } from './generated'
|
|
@@ -603,6 +604,9 @@ export class SceneGraph {
|
|
|
603
604
|
if (changes.vectorNetwork) {
|
|
604
605
|
changes = { ...changes, vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork) }
|
|
605
606
|
}
|
|
607
|
+
if (changes.effects) {
|
|
608
|
+
changes = { ...changes, effects: normalizeEffects(changes.effects) }
|
|
609
|
+
}
|
|
606
610
|
this.layoutWrites?.record(
|
|
607
611
|
node,
|
|
608
612
|
changes,
|
package/src/node-defaults.ts
CHANGED
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
DEFAULT_STROKE_MITER_LIMIT,
|
|
5
5
|
DEFAULT_STROKE_WEIGHT
|
|
6
6
|
} from './constants'
|
|
7
|
+
import { normalizeEffects } from './effects'
|
|
7
8
|
import { createInstanceOverrideState } from './instances/overrides'
|
|
8
9
|
import { NO_LETTER_SPACING } from './text/lengths'
|
|
9
10
|
import type { NodeType, SceneNode, SourceMetadata } from './types'
|
|
@@ -57,7 +58,7 @@ export function createDefaultNode(
|
|
|
57
58
|
type: NodeType,
|
|
58
59
|
overrides: Partial<SceneNode> = {}
|
|
59
60
|
): SceneNode {
|
|
60
|
-
|
|
61
|
+
const node = {
|
|
61
62
|
id: generateId(),
|
|
62
63
|
type,
|
|
63
64
|
name: type.charAt(0) + type.slice(1).toLowerCase(),
|
|
@@ -231,6 +232,8 @@ export function createDefaultNode(
|
|
|
231
232
|
booleanOperation: undefined,
|
|
232
233
|
...overrides
|
|
233
234
|
} satisfies CompleteNodeFields
|
|
235
|
+
node.effects = normalizeEffects(node.effects)
|
|
236
|
+
return node
|
|
234
237
|
}
|
|
235
238
|
|
|
236
239
|
/** Containers whose bounds follow their children and that set no coordinate space, as in Figma. */
|
package/src/preview.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { normalizeEffects } from './effects'
|
|
1
2
|
import { textCacheInvalidationChanges } from './text/picture'
|
|
2
3
|
import type { SceneNode } from './types'
|
|
3
4
|
import { normalizeVectorNetwork } from './vector-network'
|
|
@@ -73,6 +74,9 @@ export function updateNodePreview(
|
|
|
73
74
|
vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork)
|
|
74
75
|
}
|
|
75
76
|
}
|
|
77
|
+
if (changes.effects) {
|
|
78
|
+
normalizedChanges = { ...normalizedChanges, effects: normalizeEffects(changes.effects) }
|
|
79
|
+
}
|
|
76
80
|
beforeUpdate?.(node, normalizedChanges)
|
|
77
81
|
graph.positionPreviewVersion++
|
|
78
82
|
Object.assign(node, normalizedChanges)
|
package/src/variables/index.ts
CHANGED
|
@@ -22,11 +22,13 @@ import {
|
|
|
22
22
|
import {
|
|
23
23
|
BOOLEAN_BINDING_FIELDS,
|
|
24
24
|
ICON_BINDING_FIELDS,
|
|
25
|
+
NUMERIC_FIELDS,
|
|
25
26
|
paintBindingTarget,
|
|
26
27
|
STRING_BINDING_FIELDS,
|
|
27
28
|
TEXT_CONTENT_VARIABLE_TYPES,
|
|
28
29
|
uniformBindingTarget,
|
|
29
|
-
VISIBILITY_VARIABLE_TYPES
|
|
30
|
+
VISIBILITY_VARIABLE_TYPES,
|
|
31
|
+
type PaintBindingList
|
|
30
32
|
} from './fields'
|
|
31
33
|
import { pinnedRunBindingScales } from './units'
|
|
32
34
|
|
|
@@ -249,6 +251,20 @@ export function getVariablesByType(graph: SceneGraph, type: VariableType): Varia
|
|
|
249
251
|
return [...graph.variables.values()].filter((v) => v.type === type)
|
|
250
252
|
}
|
|
251
253
|
|
|
254
|
+
const PAINT_BINDING_LISTS = ['fills', 'strokes'] as const satisfies readonly PaintBindingList[]
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Every field a binding takes, from the same sets `checkBindingFieldType` reads, so a refusal for
|
|
258
|
+
* an unknown one names what the caller can send instead of leaving them to guess.
|
|
259
|
+
*/
|
|
260
|
+
const ACCEPTED_BINDING_FIELDS: readonly string[] = [
|
|
261
|
+
...NUMERIC_FIELDS,
|
|
262
|
+
...STRING_BINDING_FIELDS,
|
|
263
|
+
...BOOLEAN_BINDING_FIELDS,
|
|
264
|
+
...ICON_BINDING_FIELDS,
|
|
265
|
+
...PAINT_BINDING_LISTS.flatMap((list) => [`${list}/<n>/color`, `${list}/<n>/uniforms/<name>`])
|
|
266
|
+
]
|
|
267
|
+
|
|
252
268
|
/**
|
|
253
269
|
* Throws when a variable of `type` cannot bind to `field`, or for a field no binding takes. A
|
|
254
270
|
* paint target is checked by its caller, which also validates its index.
|
|
@@ -290,7 +306,9 @@ function checkBindingFieldType(field: string, type: VariableType): void {
|
|
|
290
306
|
uniform !== null
|
|
291
307
|
|
|
292
308
|
if (!isKnownField) {
|
|
293
|
-
throw new Error(
|
|
309
|
+
throw new Error(
|
|
310
|
+
`Unknown binding field "${field}". Accepted: ${ACCEPTED_BINDING_FIELDS.join(', ')}`
|
|
311
|
+
)
|
|
294
312
|
}
|
|
295
313
|
}
|
|
296
314
|
export function bindVariable(
|