@pairdraw/scene-graph 0.19.2 → 0.21.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 +28 -7
- package/dist/color/index.d.ts.map +1 -1
- package/dist/color/index.js +40 -15
- package/dist/color/index.js.map +1 -1
- package/dist/color/management.d.ts +19 -6
- package/dist/color/management.d.ts.map +1 -1
- package/dist/color/management.js +56 -1
- package/dist/color/management.js.map +1 -1
- package/dist/color/profile.d.ts +32 -0
- package/dist/color/profile.d.ts.map +1 -0
- package/dist/color/profile.js +140 -0
- package/dist/color/profile.js.map +1 -0
- package/dist/comments/index.d.ts +2 -2
- package/dist/comments/index.js +2 -2
- package/dist/comments/merge.d.ts.map +1 -1
- package/dist/comments/merge.js +1 -0
- package/dist/comments/merge.js.map +1 -1
- package/dist/comments/schema.d.ts +3 -1
- package/dist/comments/schema.d.ts.map +1 -1
- package/dist/comments/schema.js +19 -2
- package/dist/comments/schema.js.map +1 -1
- package/dist/comments/threads.d.ts +3 -1
- package/dist/comments/threads.d.ts.map +1 -1
- package/dist/comments/threads.js +2 -1
- package/dist/comments/threads.js.map +1 -1
- package/dist/components/index.d.ts +2 -2
- package/dist/components/index.js +2 -2
- package/dist/components/properties.d.ts.map +1 -1
- package/dist/components/properties.js +7 -7
- package/dist/components/properties.js.map +1 -1
- package/dist/components/variants.d.ts +12 -1
- package/dist/components/variants.d.ts.map +1 -1
- package/dist/components/variants.js +30 -1
- package/dist/components/variants.js.map +1 -1
- package/dist/constants.d.ts +25 -1
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +94 -1
- package/dist/constants.js.map +1 -1
- package/dist/copy.d.ts.map +1 -1
- package/dist/copy.js +17 -1
- package/dist/copy.js.map +1 -1
- package/dist/css/index.d.ts +2 -2
- package/dist/css/index.js +2 -2
- package/dist/css/shadows.d.ts +2 -2
- package/dist/css/shadows.d.ts.map +1 -1
- package/dist/css/shadows.js +4 -4
- package/dist/css/shadows.js.map +1 -1
- package/dist/css/text.d.ts +17 -1
- package/dist/css/text.d.ts.map +1 -1
- package/dist/css/text.js +62 -1
- package/dist/css/text.js.map +1 -1
- package/dist/css/values.d.ts +7 -2
- package/dist/css/values.d.ts.map +1 -1
- package/dist/css/values.js +8 -4
- package/dist/css/values.js.map +1 -1
- package/dist/design-memory/index.d.ts +3 -0
- package/dist/design-memory/index.js +3 -0
- package/dist/design-memory/model.d.ts +33 -0
- package/dist/design-memory/model.d.ts.map +1 -0
- package/dist/design-memory/model.js +142 -0
- package/dist/design-memory/model.js.map +1 -0
- package/dist/design-memory/schema.d.ts +76 -0
- package/dist/design-memory/schema.d.ts.map +1 -0
- package/dist/design-memory/schema.js +72 -0
- package/dist/design-memory/schema.js.map +1 -0
- package/dist/effects.d.ts +7 -4
- package/dist/effects.d.ts.map +1 -1
- package/dist/effects.js +9 -4
- package/dist/effects.js.map +1 -1
- package/dist/empty-values.js +102 -0
- package/dist/empty-values.js.map +1 -0
- package/dist/fields/components.d.ts +9 -0
- package/dist/fields/components.d.ts.map +1 -0
- package/dist/fields/components.js +24 -0
- package/dist/fields/components.js.map +1 -0
- package/dist/fields/index.d.ts +3 -2
- package/dist/fields/index.js +3 -2
- package/dist/fields/layout.d.ts +3 -1
- package/dist/fields/layout.d.ts.map +1 -1
- package/dist/fields/layout.js +10 -1
- package/dist/fields/layout.js.map +1 -1
- package/dist/graph.d.ts +12 -1
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +39 -7
- package/dist/graph.js.map +1 -1
- package/dist/grid-values.d.ts +10 -0
- package/dist/grid-values.d.ts.map +1 -0
- package/dist/grid-values.js +53 -0
- package/dist/grid-values.js.map +1 -0
- package/dist/hit-test/drop.d.ts +20 -0
- package/dist/hit-test/drop.d.ts.map +1 -0
- package/dist/hit-test/drop.js +54 -0
- package/dist/hit-test/drop.js.map +1 -0
- package/dist/hit-test/geometry.js +86 -0
- package/dist/hit-test/geometry.js.map +1 -0
- package/dist/hit-test/masks.d.ts +14 -0
- package/dist/hit-test/masks.d.ts.map +1 -0
- package/dist/hit-test/masks.js +41 -0
- package/dist/hit-test/masks.js.map +1 -0
- package/dist/hit-test/paint.d.ts +6 -0
- package/dist/hit-test/paint.d.ts.map +1 -0
- package/dist/hit-test/paint.js +19 -0
- package/dist/hit-test/paint.js.map +1 -0
- package/dist/hit-test.d.ts +4 -15
- package/dist/hit-test.d.ts.map +1 -1
- package/dist/hit-test.js +5 -173
- package/dist/hit-test.js.map +1 -1
- package/dist/images.d.ts +3 -2
- package/dist/images.d.ts.map +1 -1
- package/dist/images.js +18 -2
- package/dist/images.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/instances/copies.js +2 -1
- package/dist/instances/copies.js.map +1 -1
- package/dist/instances/fields.d.ts.map +1 -1
- package/dist/instances/fields.js +2 -0
- package/dist/instances/fields.js.map +1 -1
- package/dist/instances/index.d.ts +2 -1
- package/dist/instances/index.d.ts.map +1 -1
- package/dist/instances/index.js +13 -12
- package/dist/instances/index.js.map +1 -1
- package/dist/instances/overrides.d.ts +15 -1
- package/dist/instances/overrides.d.ts.map +1 -1
- package/dist/instances/overrides.js +37 -1
- package/dist/instances/overrides.js.map +1 -1
- package/dist/instances/source-walk.d.ts +12 -0
- package/dist/instances/source-walk.d.ts.map +1 -0
- package/dist/instances/swap-overrides.js +3 -3
- package/dist/instances/swap-overrides.js.map +1 -1
- package/dist/instances/sync.js +9 -7
- package/dist/instances/sync.js.map +1 -1
- package/dist/node-defaults.d.ts.map +1 -1
- package/dist/node-defaults.js +43 -38
- package/dist/node-defaults.js.map +1 -1
- package/dist/plugin-data/fields.d.ts +90 -0
- package/dist/plugin-data/fields.d.ts.map +1 -1
- package/dist/plugin-data/fields.js +33 -24
- package/dist/plugin-data/fields.js.map +1 -1
- package/dist/plugin-data/index.d.ts +2 -2
- package/dist/plugin-data/index.js +2 -2
- package/dist/plugin-data/schema.d.ts +6 -1
- package/dist/plugin-data/schema.d.ts.map +1 -1
- package/dist/plugin-data/schema.js +24 -1
- package/dist/plugin-data/schema.js.map +1 -1
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +2 -0
- package/dist/preview.js.map +1 -1
- package/dist/scaling/node.d.ts.map +1 -1
- package/dist/scaling/node.js +5 -1
- package/dist/scaling/node.js.map +1 -1
- package/dist/shaders/animation.d.ts +21 -0
- package/dist/shaders/animation.d.ts.map +1 -0
- package/dist/shaders/animation.js +25 -0
- package/dist/shaders/animation.js.map +1 -0
- package/dist/shaders/index.d.ts +2 -1
- package/dist/shaders/index.js +2 -1
- package/dist/slots/content.d.ts.map +1 -1
- package/dist/slots/content.js +4 -4
- package/dist/slots/content.js.map +1 -1
- package/dist/statuses/index.d.ts +2 -2
- package/dist/statuses/index.js +2 -2
- package/dist/statuses/workflow.d.ts +3 -1
- package/dist/statuses/workflow.d.ts.map +1 -1
- package/dist/statuses/workflow.js +6 -2
- package/dist/statuses/workflow.js.map +1 -1
- package/dist/token-sources/document.d.ts +26 -0
- package/dist/token-sources/document.d.ts.map +1 -0
- package/dist/token-sources/document.js +80 -0
- package/dist/token-sources/document.js.map +1 -0
- package/dist/token-sources/index.d.ts +3 -0
- package/dist/token-sources/index.js +3 -0
- package/dist/token-sources/schema.d.ts +43 -0
- package/dist/token-sources/schema.d.ts.map +1 -0
- package/dist/token-sources/schema.js +50 -0
- package/dist/token-sources/schema.js.map +1 -0
- package/dist/transfer/variables.d.ts.map +1 -1
- package/dist/transfer/variables.js +1 -1
- package/dist/transfer/variables.js.map +1 -1
- package/dist/types.d.ts +135 -15
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/variables/bindings.d.ts +6 -5
- package/dist/variables/bindings.d.ts.map +1 -1
- package/dist/variables/bindings.js +24 -16
- package/dist/variables/bindings.js.map +1 -1
- package/dist/variables/formula/index.d.ts.map +1 -1
- package/dist/variables/formula/index.js +12 -6
- package/dist/variables/formula/index.js.map +1 -1
- package/dist/variables/index.d.ts +14 -1
- package/dist/variables/index.d.ts.map +1 -1
- package/dist/variables/index.js +38 -10
- package/dist/variables/index.js.map +1 -1
- package/dist/variables/paints.d.ts +9 -8
- package/dist/variables/paints.d.ts.map +1 -1
- package/dist/variables/paints.js +35 -26
- package/dist/variables/paints.js.map +1 -1
- package/dist/variables/resolver.d.ts +45 -0
- package/dist/variables/resolver.d.ts.map +1 -0
- package/dist/variables/resolver.js +106 -0
- package/dist/variables/resolver.js.map +1 -0
- package/dist/variations/copy.d.ts +16 -0
- package/dist/variations/copy.d.ts.map +1 -0
- package/dist/variations/copy.js +78 -0
- package/dist/variations/copy.js.map +1 -0
- package/dist/variations/index.d.ts +6 -0
- package/dist/variations/index.js +6 -0
- package/dist/variations/match.d.ts +23 -0
- package/dist/variations/match.d.ts.map +1 -0
- package/dist/variations/match.js +80 -0
- package/dist/variations/match.js.map +1 -0
- package/dist/variations/model.d.ts +39 -0
- package/dist/variations/model.d.ts.map +1 -0
- package/dist/variations/model.js +90 -0
- package/dist/variations/model.js.map +1 -0
- package/dist/variations/pick.d.ts +43 -0
- package/dist/variations/pick.d.ts.map +1 -0
- package/dist/variations/pick.js +211 -0
- package/dist/variations/pick.js.map +1 -0
- package/dist/variations/schema.d.ts +27 -0
- package/dist/variations/schema.d.ts.map +1 -0
- package/dist/variations/schema.js +27 -0
- package/dist/variations/schema.js.map +1 -0
- package/package.json +21 -1
- package/src/color/index.ts +43 -9
- package/src/color/management.ts +54 -1
- package/src/color/profile.ts +131 -0
- package/src/comments/merge.ts +3 -0
- package/src/comments/schema.ts +32 -2
- package/src/comments/threads.ts +5 -2
- package/src/components/properties.ts +13 -7
- package/src/components/variants.ts +39 -0
- package/src/constants.ts +75 -0
- package/src/copy.ts +20 -1
- package/src/css/index.ts +7 -1
- package/src/css/shadows.ts +8 -5
- package/src/css/text.ts +62 -0
- package/src/css/values.ts +12 -5
- package/src/design-memory/index.ts +2 -0
- package/src/design-memory/model.ts +143 -0
- package/src/design-memory/schema.ts +84 -0
- package/src/effects.ts +16 -7
- package/src/empty-values.ts +117 -0
- package/src/fields/components.ts +21 -0
- package/src/fields/index.ts +1 -0
- package/src/fields/layout.ts +10 -0
- package/src/graph.ts +50 -6
- package/src/grid-values.ts +47 -0
- package/src/hit-test/drop.ts +90 -0
- package/src/hit-test/geometry.ts +131 -0
- package/src/hit-test/masks.ts +57 -0
- package/src/hit-test/paint.ts +24 -0
- package/src/hit-test.ts +8 -277
- package/src/images.ts +27 -3
- package/src/instances/copies.ts +2 -1
- package/src/instances/fields.ts +2 -0
- package/src/instances/index.ts +20 -11
- package/src/instances/overrides.ts +49 -0
- package/src/instances/swap-overrides.ts +3 -2
- package/src/instances/sync.ts +11 -7
- package/src/node-defaults.ts +51 -41
- package/src/plugin-data/fields.ts +34 -32
- package/src/plugin-data/index.ts +1 -0
- package/src/plugin-data/schema.ts +30 -0
- package/src/preview.ts +2 -0
- package/src/scaling/node.ts +7 -2
- package/src/shaders/animation.ts +39 -0
- package/src/shaders/index.ts +1 -0
- package/src/slots/content.ts +8 -4
- package/src/statuses/workflow.ts +6 -4
- package/src/token-sources/document.ts +104 -0
- package/src/token-sources/index.ts +2 -0
- package/src/token-sources/schema.ts +59 -0
- package/src/transfer/variables.ts +2 -1
- package/src/types.ts +145 -14
- package/src/variables/bindings.ts +35 -18
- package/src/variables/formula/index.ts +19 -18
- package/src/variables/index.ts +49 -10
- package/src/variables/paints.ts +64 -29
- package/src/variables/resolver.ts +178 -0
- package/src/variations/copy.ts +89 -0
- package/src/variations/index.ts +5 -0
- package/src/variations/match.ts +100 -0
- package/src/variations/model.ts +132 -0
- package/src/variations/pick.ts +293 -0
- package/src/variations/schema.ts +29 -0
package/dist/images.js
CHANGED
|
@@ -47,12 +47,28 @@ function imageHeader(data) {
|
|
|
47
47
|
height: header.height
|
|
48
48
|
} : null;
|
|
49
49
|
}
|
|
50
|
+
/** A four-character ISO media brand at `start`, or an empty string when the bytes are short. */
|
|
51
|
+
function isoBrand(data, start) {
|
|
52
|
+
if (start + 4 > data.length) return "";
|
|
53
|
+
return String.fromCharCode(data[start] ?? 0, data[start + 1] ?? 0, data[start + 2] ?? 0, data[start + 3] ?? 0);
|
|
54
|
+
}
|
|
55
|
+
/** Whether bytes are an AVIF image, whose `ftyp` box names the brand or lists it as compatible. */
|
|
56
|
+
function isAVIF(data) {
|
|
57
|
+
if (isoBrand(data, 4) !== "ftyp") return false;
|
|
58
|
+
const size = (data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]) >>> 0;
|
|
59
|
+
const isAvif = (brand) => brand === "avif" || brand === "avis";
|
|
60
|
+
if (isAvif(isoBrand(data, 8))) return true;
|
|
61
|
+
const end = Math.min(size >= 16 ? size : data.length, data.length);
|
|
62
|
+
for (let start = 16; start + 4 <= end; start += 4) if (isAvif(isoBrand(data, start))) return true;
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
50
65
|
/**
|
|
51
66
|
* The media type of encoded image bytes, read from their header, for writing them out as a data
|
|
52
|
-
* URL or file.
|
|
67
|
+
* URL or file. AVIF is read from its ISO media brand, which `image-size` does not decode. Bytes it
|
|
68
|
+
* cannot read are reported as PNG, as image fills began.
|
|
53
69
|
*/
|
|
54
70
|
function imageMimeType(data) {
|
|
55
|
-
return imageHeader(data)?.type ?? "image/png";
|
|
71
|
+
return imageHeader(data)?.type ?? (isAVIF(data) ? "image/avif" : "image/png");
|
|
56
72
|
}
|
|
57
73
|
/** An image's size in pixels, read from its header; null for bytes it cannot read. */
|
|
58
74
|
function imageSize(data) {
|
package/dist/images.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"images.js","names":["readImageHeader"],"sources":["../src/images.ts"],"sourcesContent":["import { sha1 } from '@noble/hashes/legacy.js'\nimport { bytesToHex } from '@noble/hashes/utils.js'\nimport { imageSize as readImageHeader } from 'image-size'\n\nimport type { Matrix, Size } from './primitives'\n\n/**\n * The name an image's bytes are stored under: the hex SHA-1 of the bytes, as Figma names images,\n * so `.fig` files and the Figma clipboard can carry the name as it is. Documents saved before may\n * hold images under other names; anything that hands images to Figma still checks.\n */\nexport function computeImageHash(data: Uint8Array): string {\n return bytesToHex(sha1(data))\n}\n\nexport type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp'\n\n/** The image types documents store, by the name `image-size` gives each format. */\nconst IMAGE_MIME_TYPES: Partial<Record<string, ImageMimeType>> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp'\n}\n\n/** The raster types a dropped or pasted file can be imported as an image fill from. */\nexport const IMPORTABLE_RASTER_TYPES: ReadonlySet<string> = new Set([\n 'image/png',\n 'image/jpeg',\n 'image/webp',\n 'image/gif',\n 'image/avif'\n])\n\n/** Whether a file is an SVG image, which some systems report without a media type. */\nexport function isSVGFile(file: { name: string; type: string }): boolean {\n return (\n file.type === 'image/svg+xml' || (file.type === '' && file.name.toLowerCase().endsWith('.svg'))\n )\n}\n\nexport interface ImageHeader extends Size {\n type: ImageMimeType\n}\n\n/**\n * The type and size of a PNG, JPEG, GIF, or WebP, read from its header by `image-size`; null for\n * bytes it cannot read and for other formats.\n */\nexport function imageHeader(data: Uint8Array): ImageHeader | null {\n let header: ReturnType<typeof readImageHeader>\n try {\n header = readImageHeader(data)\n } catch {\n return null\n }\n const type = header.type === undefined ? undefined : IMAGE_MIME_TYPES[header.type]\n return type ? { type, width: header.width, height: header.height } : null\n}\n\n/**\n * The media type of encoded image bytes, read from their header, for writing them out as a data\n * URL or file. Bytes it cannot read are reported as PNG, as image fills began.\n */\nexport function imageMimeType(data: Uint8Array): ImageMimeType {\n return imageHeader(data)?.type ?? 'image/png'\n}\n\n/** An image's size in pixels, read from its header; null for bytes it cannot read. */\nexport function imageSize(data: Uint8Array): Size | null {\n const header = imageHeader(data)\n return header && { width: header.width, height: header.height }\n}\n\n/**\n * The crop that shows an image as Fill does: scaled to cover a `width` × `height` layer and\n * centred. Figma starts a crop from it, as the image-space window a crop's transform holds.\n */\nexport function coverImageTransform(\n width: number,\n height: number,\n imageWidth: number,\n imageHeight: number\n): Matrix {\n const scale = Math.max(width / imageWidth, height / imageHeight)\n const m00 = width / scale / imageWidth\n const m11 = height / scale / imageHeight\n return { m00, m01: 0, m02: (1 - m00) / 2, m10: 0, m11, m12: (1 - m11) / 2 }\n}\n"],"mappings":";;;;;;;;;AAWA,SAAgB,iBAAiB,MAA0B;CACzD,OAAO,WAAW,KAAK,IAAI,CAAC;AAC9B;;AAKA,MAAM,mBAA2D;CAC/D,KAAK;CACL,KAAK;CACL,KAAK;CACL,MAAM;AACR;;AAGA,MAAa,0CAA+C,IAAI,IAAI;CAClE;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAgB,UAAU,MAA+C;CACvE,OACE,KAAK,SAAS,mBAAoB,KAAK,SAAS,MAAM,KAAK,KAAK,YAAY,CAAC,CAAC,SAAS,MAAM;AAEjG;;;;;AAUA,SAAgB,YAAY,MAAsC;CAChE,IAAI;CACJ,IAAI;EACF,SAASA,YAAgB,IAAI;CAC/B,QAAQ;EACN,OAAO;CACT;CACA,MAAM,OAAO,OAAO,SAAS,KAAA,IAAY,KAAA,IAAY,iBAAiB,OAAO;CAC7E,OAAO,OAAO;EAAE;EAAM,OAAO,OAAO;EAAO,QAAQ,OAAO;CAAO,IAAI;AACvE
|
|
1
|
+
{"version":3,"file":"images.js","names":["readImageHeader"],"sources":["../src/images.ts"],"sourcesContent":["import { sha1 } from '@noble/hashes/legacy.js'\nimport { bytesToHex } from '@noble/hashes/utils.js'\nimport { imageSize as readImageHeader } from 'image-size'\n\nimport type { Matrix, Size } from './primitives'\n\n/**\n * The name an image's bytes are stored under: the hex SHA-1 of the bytes, as Figma names images,\n * so `.fig` files and the Figma clipboard can carry the name as it is. Documents saved before may\n * hold images under other names; anything that hands images to Figma still checks.\n */\nexport function computeImageHash(data: Uint8Array): string {\n return bytesToHex(sha1(data))\n}\n\nexport type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'image/avif'\n\n/** The image types documents store, by the name `image-size` gives each format. */\nconst IMAGE_MIME_TYPES: Partial<Record<string, ImageMimeType>> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp'\n}\n\n/** The raster types a dropped or pasted file can be imported as an image fill from. */\nexport const IMPORTABLE_RASTER_TYPES: ReadonlySet<string> = new Set([\n 'image/png',\n 'image/jpeg',\n 'image/webp',\n 'image/gif',\n 'image/avif'\n])\n\n/** Whether a file is an SVG image, which some systems report without a media type. */\nexport function isSVGFile(file: { name: string; type: string }): boolean {\n return (\n file.type === 'image/svg+xml' || (file.type === '' && file.name.toLowerCase().endsWith('.svg'))\n )\n}\n\nexport interface ImageHeader extends Size {\n type: ImageMimeType\n}\n\n/**\n * The type and size of a PNG, JPEG, GIF, or WebP, read from its header by `image-size`; null for\n * bytes it cannot read and for other formats.\n */\nexport function imageHeader(data: Uint8Array): ImageHeader | null {\n let header: ReturnType<typeof readImageHeader>\n try {\n header = readImageHeader(data)\n } catch {\n return null\n }\n const type = header.type === undefined ? undefined : IMAGE_MIME_TYPES[header.type]\n return type ? { type, width: header.width, height: header.height } : null\n}\n\n/** A four-character ISO media brand at `start`, or an empty string when the bytes are short. */\nfunction isoBrand(data: Uint8Array, start: number): string {\n if (start + 4 > data.length) return ''\n return String.fromCharCode(\n data[start] ?? 0,\n data[start + 1] ?? 0,\n data[start + 2] ?? 0,\n data[start + 3] ?? 0\n )\n}\n\n/** Whether bytes are an AVIF image, whose `ftyp` box names the brand or lists it as compatible. */\nfunction isAVIF(data: Uint8Array): boolean {\n if (isoBrand(data, 4) !== 'ftyp') return false\n const size = ((data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3]) >>> 0\n const isAvif = (brand: string) => brand === 'avif' || brand === 'avis'\n if (isAvif(isoBrand(data, 8))) return true\n const end = Math.min(size >= 16 ? size : data.length, data.length)\n // The major brand is followed by a minor version, then the compatible brands.\n for (let start = 16; start + 4 <= end; start += 4) if (isAvif(isoBrand(data, start))) return true\n return false\n}\n\n/**\n * The media type of encoded image bytes, read from their header, for writing them out as a data\n * URL or file. AVIF is read from its ISO media brand, which `image-size` does not decode. Bytes it\n * cannot read are reported as PNG, as image fills began.\n */\nexport function imageMimeType(data: Uint8Array): ImageMimeType {\n return imageHeader(data)?.type ?? (isAVIF(data) ? 'image/avif' : 'image/png')\n}\n\n/** An image's size in pixels, read from its header; null for bytes it cannot read. */\nexport function imageSize(data: Uint8Array): Size | null {\n const header = imageHeader(data)\n return header && { width: header.width, height: header.height }\n}\n\n/**\n * The crop that shows an image as Fill does: scaled to cover a `width` × `height` layer and\n * centred. Figma starts a crop from it, as the image-space window a crop's transform holds.\n */\nexport function coverImageTransform(\n width: number,\n height: number,\n imageWidth: number,\n imageHeight: number\n): Matrix {\n const scale = Math.max(width / imageWidth, height / imageHeight)\n const m00 = width / scale / imageWidth\n const m11 = height / scale / imageHeight\n return { m00, m01: 0, m02: (1 - m00) / 2, m10: 0, m11, m12: (1 - m11) / 2 }\n}\n"],"mappings":";;;;;;;;;AAWA,SAAgB,iBAAiB,MAA0B;CACzD,OAAO,WAAW,KAAK,IAAI,CAAC;AAC9B;;AAKA,MAAM,mBAA2D;CAC/D,KAAK;CACL,KAAK;CACL,KAAK;CACL,MAAM;AACR;;AAGA,MAAa,0CAA+C,IAAI,IAAI;CAClE;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAgB,UAAU,MAA+C;CACvE,OACE,KAAK,SAAS,mBAAoB,KAAK,SAAS,MAAM,KAAK,KAAK,YAAY,CAAC,CAAC,SAAS,MAAM;AAEjG;;;;;AAUA,SAAgB,YAAY,MAAsC;CAChE,IAAI;CACJ,IAAI;EACF,SAASA,YAAgB,IAAI;CAC/B,QAAQ;EACN,OAAO;CACT;CACA,MAAM,OAAO,OAAO,SAAS,KAAA,IAAY,KAAA,IAAY,iBAAiB,OAAO;CAC7E,OAAO,OAAO;EAAE;EAAM,OAAO,OAAO;EAAO,QAAQ,OAAO;CAAO,IA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|
|
1
1
|
import { CommittedGraphEventError } from "./buffered-events.js";
|
|
2
2
|
import { SceneGraph } from "./graph.js";
|
|
3
|
-
import { ArcData, AxisSizingMode, BlendMode, BooleanOperation, CODE_SYNTAX_PLATFORMS, CharacterStyleOverride, CodeSyntaxPlatform, CommentReply, CommentThread, ComponentPropertyDefinition, ComponentPropertyReference, ComponentPropertyReferenceField, ComponentPropertyType, ConnectorControlPoint, ConnectorEndpoint, ConnectorLabelPosition, ConnectorLineType, ConnectorMagnet, ConstraintType, DerivedTextGlyph, DocumentColorSpace, DocumentKind, Effect, EnabledLibraryBinding, ExportSetting, FigmaLayoutMetadata, FigmaSourcePayload, Fill, FillType, FontFeature, FontVariation, GeometryPath, GradientStop, GradientTransform, GridPosition, GridTrack, GridTrackSizing, HandleMirroring, HyperlinkTarget, ImageFilters, ImageScaleMode, LayoutAlign, LayoutAlignSelf, LayoutCounterAlign, LayoutDirection, LayoutGrid, LayoutMode, LayoutSizing, LayoutWrap, LeadingTrim, LibraryAssetIdentity, LibraryAssetSource, MODE_ATTRIBUTE_PATTERN, MaskType, MeshGradientPoint, NodeChangeObserver, NodeType, NoiseType, NumericNodeProperty, PatternAlignment, PatternTileType, PluginDataEntry, PluginRelaunchDataEntry, PrototypeAction, PrototypeActionType, PrototypeBackAction, PrototypeCloseAction, PrototypeNavigationType, PrototypeNodeAction, PrototypeOverlayPositionType, PrototypeReaction, PrototypeTransition, PrototypeTransitionType, PrototypeTrigger, PrototypeTriggerType, SceneGraphEventHandlers, SceneGraphEvents, SceneNode, ShaderEffect, ShadowEffect, SharedStyle, SharedStyleKind, SharedStyleType, SlotSettings, SourceLibraryPublication, SourceMetadata, Stroke, StrokeCap, StrokeJoin, StyleRun, SymbolLink, TEXT_BINDABLE_FIELDS, TOKEN_UNITS, TextAlignVertical, TextAutoResize, TextBindableField, TextBoundVariables, TextCase, TextDecoration, TextDecorationStyle, TextDirection, TextLength, TextListType, TextParagraphSpacingField, TextParagraphStyle, TextPathData, TokenExpression, TokenUnit, VARIABLE_FORMULA_OPERATORS, VARIABLE_SCOPES, Variable, VariableAlias, VariableCollection, VariableCollectionMode, VariableColorExpression, VariableFormula, VariableFormulaNode, VariableFormulaOperation, VariableFormulaOperator, VariableLiteral, VariableModeMap, VariableScope, VariableType, VariableUnsupportedExpression, VariableValue, VariantPropSpec, VectorNetwork, VectorRegion, VectorSegment, VectorVertex, WindingRule, isLibraryCollection, isModeAttributeName } from "./types.js";
|
|
3
|
+
import { ArcData, AxisSizingMode, BlendMode, BooleanOperation, CODE_SYNTAX_PLATFORMS, CharacterStyleOverride, CodeSyntaxPlatform, ColorProfile, CommentRegion, CommentReply, CommentThread, ComponentPropertyDefinition, ComponentPropertyReference, ComponentPropertyReferenceField, ComponentPropertyType, ConnectorControlPoint, ConnectorEndpoint, ConnectorLabelPosition, ConnectorLineType, ConnectorMagnet, ConstraintType, DerivedTextGlyph, DocumentColorSpace, DocumentKind, DrawIOEdgeSource, Effect, EnabledLibraryBinding, ExportSetting, FigmaLayoutMetadata, FigmaSourcePayload, Fill, FillType, FontFeature, FontVariation, GeometryPath, GradientStop, GradientTransform, GridPosition, GridTrack, GridTrackSizing, HandleMirroring, HyperlinkTarget, ImageFilters, ImageScaleMode, LayoutAlign, LayoutAlignSelf, LayoutCounterAlign, LayoutDirection, LayoutGrid, LayoutMode, LayoutSizing, LayoutWrap, LeadingTrim, LibraryAssetIdentity, LibraryAssetSource, MODE_ATTRIBUTE_PATTERN, MaskType, MeshGradientPoint, NodeChangeObserver, NodeType, NoiseEffect, NoiseEffectParams, NoiseType, NumericNodeProperty, OverflowDirection, PatternAlignment, PatternTileType, PluginDataEntry, PluginRelaunchDataEntry, PrototypeAction, PrototypeActionType, PrototypeBackAction, PrototypeCloseAction, PrototypeEasingType, PrototypeNavigationType, PrototypeNodeAction, PrototypeOverlayPositionType, PrototypeReaction, PrototypeTransition, PrototypeTransitionType, PrototypeTrigger, PrototypeTriggerType, SceneGraphEventHandlers, SceneGraphEvents, SceneNode, ScrollBehavior, ShaderEffect, ShadowEffect, SharedStyle, SharedStyleKind, SharedStyleType, SlotSettings, SourceLibraryPublication, SourceMetadata, Stroke, StrokeCap, StrokeJoin, StyleRun, SymbolLink, TEXT_BINDABLE_FIELDS, TOKEN_UNITS, TextAlignVertical, TextAutoResize, TextBindableField, TextBoundVariables, TextCase, TextDecoration, TextDecorationStyle, TextDirection, TextLength, TextListType, TextParagraphSpacingField, TextParagraphStyle, TextPathData, TextureEffect, TextureEffectParams, TokenExpression, TokenUnit, VARIABLE_FORMULA_OPERATORS, VARIABLE_SCOPES, Variable, VariableAlias, VariableCollection, VariableCollectionMode, VariableColorExpression, VariableFormula, VariableFormulaNode, VariableFormulaOperation, VariableFormulaOperator, VariableLiteral, VariableModeMap, VariableScope, VariableType, VariableUnsupportedExpression, VariableValue, VariantPropSpec, VectorNetwork, VectorRegion, VectorSegment, VectorVertex, WindingRule, isLibraryCollection, isModeAttributeName } from "./types.js";
|
|
4
4
|
import { generateId, setIdSession } from "./ids.js";
|
|
5
|
-
export { ArcData, AxisSizingMode, BlendMode, BooleanOperation, CODE_SYNTAX_PLATFORMS, CharacterStyleOverride, CodeSyntaxPlatform, CommentReply, CommentThread, CommittedGraphEventError, ComponentPropertyDefinition, ComponentPropertyReference, ComponentPropertyReferenceField, ComponentPropertyType, ConnectorControlPoint, ConnectorEndpoint, ConnectorLabelPosition, ConnectorLineType, ConnectorMagnet, ConstraintType, DerivedTextGlyph, DocumentColorSpace, DocumentKind, Effect, EnabledLibraryBinding, ExportSetting, FigmaLayoutMetadata, FigmaSourcePayload, Fill, FillType, FontFeature, FontVariation, GeometryPath, GradientStop, GradientTransform, GridPosition, GridTrack, GridTrackSizing, HandleMirroring, HyperlinkTarget, ImageFilters, ImageScaleMode, LayoutAlign, LayoutAlignSelf, LayoutCounterAlign, LayoutDirection, LayoutGrid, LayoutMode, LayoutSizing, LayoutWrap, LeadingTrim, LibraryAssetIdentity, LibraryAssetSource, MODE_ATTRIBUTE_PATTERN, MaskType, MeshGradientPoint, NodeChangeObserver, NodeType, NoiseType, NumericNodeProperty, PatternAlignment, PatternTileType, PluginDataEntry, PluginRelaunchDataEntry, PrototypeAction, PrototypeActionType, PrototypeBackAction, PrototypeCloseAction, PrototypeNavigationType, PrototypeNodeAction, PrototypeOverlayPositionType, PrototypeReaction, PrototypeTransition, PrototypeTransitionType, PrototypeTrigger, PrototypeTriggerType, SceneGraph, SceneGraphEventHandlers, SceneGraphEvents, SceneNode, ShaderEffect, ShadowEffect, SharedStyle, SharedStyleKind, SharedStyleType, SlotSettings, SourceLibraryPublication, SourceMetadata, Stroke, StrokeCap, StrokeJoin, StyleRun, SymbolLink, TEXT_BINDABLE_FIELDS, TOKEN_UNITS, TextAlignVertical, TextAutoResize, TextBindableField, TextBoundVariables, TextCase, TextDecoration, TextDecorationStyle, TextDirection, TextLength, TextListType, TextParagraphSpacingField, TextParagraphStyle, TextPathData, TokenExpression, TokenUnit, VARIABLE_FORMULA_OPERATORS, VARIABLE_SCOPES, Variable, VariableAlias, VariableCollection, VariableCollectionMode, VariableColorExpression, VariableFormula, VariableFormulaNode, VariableFormulaOperation, VariableFormulaOperator, VariableLiteral, VariableModeMap, VariableScope, VariableType, VariableUnsupportedExpression, VariableValue, VariantPropSpec, VectorNetwork, VectorRegion, VectorSegment, VectorVertex, WindingRule, generateId, isLibraryCollection, isModeAttributeName, setIdSession };
|
|
5
|
+
export { ArcData, AxisSizingMode, BlendMode, BooleanOperation, CODE_SYNTAX_PLATFORMS, CharacterStyleOverride, CodeSyntaxPlatform, ColorProfile, CommentRegion, CommentReply, CommentThread, CommittedGraphEventError, ComponentPropertyDefinition, ComponentPropertyReference, ComponentPropertyReferenceField, ComponentPropertyType, ConnectorControlPoint, ConnectorEndpoint, ConnectorLabelPosition, ConnectorLineType, ConnectorMagnet, ConstraintType, DerivedTextGlyph, DocumentColorSpace, DocumentKind, DrawIOEdgeSource, Effect, EnabledLibraryBinding, ExportSetting, FigmaLayoutMetadata, FigmaSourcePayload, Fill, FillType, FontFeature, FontVariation, GeometryPath, GradientStop, GradientTransform, GridPosition, GridTrack, GridTrackSizing, HandleMirroring, HyperlinkTarget, ImageFilters, ImageScaleMode, LayoutAlign, LayoutAlignSelf, LayoutCounterAlign, LayoutDirection, LayoutGrid, LayoutMode, LayoutSizing, LayoutWrap, LeadingTrim, LibraryAssetIdentity, LibraryAssetSource, MODE_ATTRIBUTE_PATTERN, MaskType, MeshGradientPoint, NodeChangeObserver, NodeType, NoiseEffect, NoiseEffectParams, NoiseType, NumericNodeProperty, OverflowDirection, PatternAlignment, PatternTileType, PluginDataEntry, PluginRelaunchDataEntry, PrototypeAction, PrototypeActionType, PrototypeBackAction, PrototypeCloseAction, PrototypeEasingType, PrototypeNavigationType, PrototypeNodeAction, PrototypeOverlayPositionType, PrototypeReaction, PrototypeTransition, PrototypeTransitionType, PrototypeTrigger, PrototypeTriggerType, SceneGraph, SceneGraphEventHandlers, SceneGraphEvents, SceneNode, ScrollBehavior, ShaderEffect, ShadowEffect, SharedStyle, SharedStyleKind, SharedStyleType, SlotSettings, SourceLibraryPublication, SourceMetadata, Stroke, StrokeCap, StrokeJoin, StyleRun, SymbolLink, TEXT_BINDABLE_FIELDS, TOKEN_UNITS, TextAlignVertical, TextAutoResize, TextBindableField, TextBoundVariables, TextCase, TextDecoration, TextDecorationStyle, TextDirection, TextLength, TextListType, TextParagraphSpacingField, TextParagraphStyle, TextPathData, TextureEffect, TextureEffectParams, TokenExpression, TokenUnit, VARIABLE_FORMULA_OPERATORS, VARIABLE_SCOPES, Variable, VariableAlias, VariableCollection, VariableCollectionMode, VariableColorExpression, VariableFormula, VariableFormulaNode, VariableFormulaOperation, VariableFormulaOperator, VariableLiteral, VariableModeMap, VariableScope, VariableType, VariableUnsupportedExpression, VariableValue, VariantPropSpec, VectorNetwork, VectorRegion, VectorSegment, VectorVertex, WindingRule, generateId, isLibraryCollection, isModeAttributeName, setIdSession };
|
package/dist/instances/copies.js
CHANGED
|
@@ -138,7 +138,8 @@ function removeLeftoverCopies(graph, context, removals) {
|
|
|
138
138
|
const overrides = /* @__PURE__ */ new Map();
|
|
139
139
|
for (const removed of nodes) {
|
|
140
140
|
const fields = context.overrides.descendants.get(removed.id);
|
|
141
|
-
if (fields)
|
|
141
|
+
if (!fields) continue;
|
|
142
|
+
overrides.set(removed.id, new Map(fields));
|
|
142
143
|
context.overrides.descendants.delete(removed.id);
|
|
143
144
|
}
|
|
144
145
|
let copies = store.byInstance.get(context.instanceId);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"copies.js","names":["hasNodeInstanceOverride"],"sources":["../../src/instances/copies.ts"],"sourcesContent":["// How an instance's copies follow the component's layers when its structure changes.\nimport type { SceneGraph } from '../graph'\nimport { ownsSlotContent, slotPropertyId } from '../slots/frames'\nimport type { SceneNode } from '../types'\nimport { DEFAULT_HISTORY_LIMIT } from '../undo'\nimport {\n copiedComponentLayerId,\n hasInstanceOverride as hasNodeInstanceOverride,\n type InstanceOverrideState\n} from './overrides'\nimport { replacedComponentLayerId } from './replacements'\n\n/**\n * One instance's sync: the copies it has matched to the component's layers, the parents it\n * synced, and, built on first need, the copies the instance had before, by the layer they copy.\n * Copies follow their layers when the component's structure changes, as Figma moves them: a\n * layer moved inside the component keeps its copy and the copy's overrides, and a copy whose\n * layer left or was deleted goes.\n */\nexport interface InstanceSyncContext {\n instanceId: string\n overrides: InstanceOverrideState\n matched: Set<string>\n leftovers: Set<string>\n copies?: Map<string, SceneNode[]>\n}\n\nexport function createInstanceSyncContext(\n instanceId: string,\n overrides: InstanceOverrideState\n): InstanceSyncContext {\n return { instanceId, overrides, matched: new Set(), leftovers: new Set() }\n}\n\n/** The component layer a copy in the instance stands for, or a replaced layer stands in for. */\nfunction copiedLayerId(\n graph: SceneGraph,\n node: SceneNode,\n context: InstanceSyncContext\n): string | undefined {\n return (\n replacedComponentLayerId(graph, node) ??\n copiedComponentLayerId(context.overrides, context.instanceId, node)\n )\n}\n\n/** Whether sync goes inside a copy: not into slot content, a swapped instance, or an instance. */\nfunction syncsInside(graph: SceneGraph, node: SceneNode, context: InstanceSyncContext): boolean {\n if (node.type === 'INSTANCE') return false\n if (hasNodeInstanceOverride(context.overrides, context.instanceId, node.id, 'componentId')) {\n return false\n }\n const layer = node.componentId ? graph.nodes.get(node.componentId) : undefined\n return !layer || !ownsSlotContent(graph, node, slotPropertyId(layer))\n}\n\nfunction copiesOf(graph: SceneGraph, context: InstanceSyncContext): Map<string, SceneNode[]> {\n if (context.copies) return context.copies\n const copies = new Map<string, SceneNode[]>()\n const visit = (parent: SceneNode) => {\n for (const id of parent.childIds) {\n const child = graph.nodes.get(id)\n if (!child) continue\n const layerId = copiedLayerId(graph, child, context)\n if (layerId) copies.set(layerId, [...(copies.get(layerId) ?? []), child])\n if (syncsInside(graph, child, context)) visit(child)\n }\n }\n const instance = graph.nodes.get(context.instanceId)\n if (instance) visit(instance)\n context.copies = copies\n return copies\n}\n\n/** A copy of `layerId` the sync has not placed yet, which a moved layer takes along. */\nexport function unplacedCopy(\n graph: SceneGraph,\n context: InstanceSyncContext,\n layerId: string,\n instParentId: string\n): SceneNode | undefined {\n return copiesOf(graph, context)\n .get(layerId)\n ?.find(\n (copy) =>\n !context.matched.has(copy.id) &&\n graph.nodes.has(copy.id) &&\n copy.id !== instParentId &&\n !graph.isDescendant(instParentId, copy.id)\n )\n}\n\n/** Whether any layer in the component subtree at `layerId` already has a copy to move. */\nexport function hasUnplacedCopiesBelow(\n graph: SceneGraph,\n context: InstanceSyncContext,\n layerId: string\n): boolean {\n const copies = copiesOf(graph, context)\n if (copies.size === 0) return false\n const layer = graph.nodes.get(layerId)\n return (layer?.childIds ?? []).some(\n (id) =>\n copies.get(id)?.some((copy) => !context.matched.has(copy.id)) ||\n hasUnplacedCopiesBelow(graph, context, id)\n )\n}\n\n/** The copies one sync of a component's instances removed, by instance and layer. */\nexport interface CopyRemovals {\n keys: Array<[instanceId: string, layerId: string]>\n}\n\n/** A copy the sync removed, kept so the layer coming back, as on undo, brings it back as it was. */\ninterface RemovedCopy {\n /** The copy and everything in it, parents first. */\n nodes: SceneNode[]\n overrides: Map<string, Map<string, unknown>>\n removals: CopyRemovals\n}\n\ninterface RemovedCopyStore {\n /** Removed copies by instance, then by the layer they copied. */\n byInstance: Map<string, Map<string, RemovedCopy>>\n /** Syncs that removed copies, oldest first. */\n removals: CopyRemovals[]\n}\n\nconst removedCopies = new WeakMap<SceneGraph, RemovedCopyStore>()\n\nfunction removedCopyStore(graph: SceneGraph): RemovedCopyStore {\n let store = removedCopies.get(graph)\n if (!store) {\n store = { byInstance: new Map(), removals: [] }\n removedCopies.set(graph, store)\n }\n return store\n}\n\n/**\n * Keeps one edit's removed copies restorable. Only as many edits as undo keeps are kept, so\n * copies no undo can bring back are forgotten, oldest first.\n */\nfunction keepCopyRemovals(graph: SceneGraph, removals: CopyRemovals): void {\n if (removals.keys.length === 0) return\n const store = removedCopyStore(graph)\n store.removals.push(removals)\n while (store.removals.length > DEFAULT_HISTORY_LIMIT) {\n const oldest = store.removals.shift()\n for (const [instanceId, layerId] of oldest?.keys ?? []) {\n const copies = store.byInstance.get(instanceId)\n // A later sync may have removed the same layer's copy again; that one stays.\n if (!copies || copies.get(layerId)?.removals !== oldest) continue\n copies.delete(layerId)\n if (copies.size === 0) store.byInstance.delete(instanceId)\n }\n }\n}\n\nconst activeRemovals = new WeakMap<SceneGraph, CopyRemovals>()\n\n/**\n * Runs `fn` with every copy the syncs inside it remove kept as one group: one edit's syncs, however\n * many components they reach, take one place in the history of removals.\n */\nexport function groupCopyRemovals<T>(graph: SceneGraph, fn: (removals: CopyRemovals) => T): T {\n const active = activeRemovals.get(graph)\n if (active) return fn(active)\n const removals: CopyRemovals = { keys: [] }\n activeRemovals.set(graph, removals)\n try {\n return fn(removals)\n } finally {\n activeRemovals.delete(graph)\n keepCopyRemovals(graph, removals)\n }\n}\n\n/**\n * Brings back the copy of `layerId` the sync removed from this instance, with the same layers\n * and overrides, as Figma restores an instance's override when the layer's deletion is undone.\n */\nexport function restoreRemovedCopy(\n graph: SceneGraph,\n context: InstanceSyncContext,\n layerId: string,\n instParentId: string\n): SceneNode | undefined {\n const store = removedCopyStore(graph)\n const removed = store.byInstance.get(context.instanceId)\n const entry = removed?.get(layerId)\n if (!removed || !entry) return undefined\n removed.delete(layerId)\n if (removed.size === 0) store.byInstance.delete(context.instanceId)\n const root = entry.nodes.at(0)\n if (!root || entry.nodes.some((node) => graph.nodes.has(node.id))) return undefined\n for (const node of entry.nodes) {\n const { id, type, parentId, childIds: _childIds, ...props } = structuredClone(node)\n graph.createNodeWithId(id, type, id === root.id ? instParentId : parentId, props)\n }\n for (const [id, fields] of entry.overrides) context.overrides.descendants.set(id, new Map(fields))\n return graph.nodes.get(root.id)\n}\n\n/**\n * Deletes the copies the sync left over: ones whose layer left the component, was deleted, or\n * now has another copy. Copies the instance owns, such as slot content, are never reached.\n */\nexport function removeLeftoverCopies(\n graph: SceneGraph,\n context: InstanceSyncContext,\n removals: CopyRemovals\n): void {\n const store = removedCopyStore(graph)\n for (const id of context.leftovers) {\n const node = graph.nodes.get(id)\n const layerId = node ? copiedLayerId(graph, node, context) : undefined\n if (!node || !layerId || context.matched.has(id)) continue\n const nodes: SceneNode[] = []\n const collect = (current: SceneNode) => {\n nodes.push(structuredClone(current))\n for (const childId of current.childIds) {\n const child = graph.nodes.get(childId)\n if (child) collect(child)\n }\n }\n collect(node)\n const overrides = new Map<string, Map<string, unknown>>()\n for (const removed of nodes) {\n const fields = context.overrides.descendants.get(removed.id)\n if (fields) overrides.set(removed.id, new Map(fields))\n context.overrides.descendants.delete(removed.id)\n }\n let copies = store.byInstance.get(context.instanceId)\n if (!copies) {\n copies = new Map()\n store.byInstance.set(context.instanceId, copies)\n }\n copies.set(layerId, { nodes, overrides, removals })\n removals.keys.push([context.instanceId, layerId])\n graph.deleteNode(id)\n }\n context.leftovers.clear()\n}\n"],"mappings":";;;;;AA2BA,SAAgB,0BACd,YACA,WACqB;CACrB,OA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IAAI,KAAA;EAC7D,IAAI,CAAC,QAAQ,CAAC,WAAW,QAAQ,QAAQ,IAAI,EAAE,GAAG;EAClD,MAAM,QAAqB,CAAC;EAC5B,MAAM,WAAW,YAAuB;GACtC,MAAM,KAAK,gBAAgB,OAAO,CAAC;GACnC,KAAK,MAAM,WAAW,QAAQ,UAAU;IACtC,MAAM,QAAQ,MAAM,MAAM,IAAI,OAAO;IACrC,IAAI,OAAO,QAAQ,KAAK;GAC1B;EACF;EACA,QAAQ,IAAI;EACZ,MAAM,4BAAY,IAAI,IAAkC;EACxD,KAAK,MAAM,WAAW,OAAO;GAC3B,MAAM,SAAS,QAAQ,UAAU,YAAY,IAAI,QAAQ,EAAE;GAC3D,IAAI,QAAQ,UAAU,IAAI,QAAQ,IAAI,IAAI,IAAI,MAAM,CAAC;GACrD,QAAQ,UAAU,YAAY,OAAO,QAAQ,EAAE;EACjD;EACA,IAAI,SAAS,MAAM,WAAW,IAAI,QAAQ,UAAU;EACpD,IAAI,CAAC,QAAQ;GACX,yBAAS,IAAI,IAAI;GACjB,MAAM,WAAW,IAAI,QAAQ,YAAY,MAAM;EACjD;EACA,OAAO,IAAI,SAAS;GAAE;GAAO;GAAW;EAAS,CAAC;EAClD,SAAS,KAAK,KAAK,CAAC,QAAQ,YAAY,OAAO,CAAC;EAChD,MAAM,WAAW,EAAE;CACrB;CACA,QAAQ,UAAU,MAAM;AAC1B"}
|
|
1
|
+
{"version":3,"file":"copies.js","names":["hasNodeInstanceOverride"],"sources":["../../src/instances/copies.ts"],"sourcesContent":["// How an instance's copies follow the component's layers when its structure changes.\nimport type { SceneGraph } from '../graph'\nimport { ownsSlotContent, slotPropertyId } from '../slots/frames'\nimport type { SceneNode } from '../types'\nimport { DEFAULT_HISTORY_LIMIT } from '../undo'\nimport {\n copiedComponentLayerId,\n hasInstanceOverride as hasNodeInstanceOverride,\n type InstanceOverrideState\n} from './overrides'\nimport { replacedComponentLayerId } from './replacements'\n\n/**\n * One instance's sync: the copies it has matched to the component's layers, the parents it\n * synced, and, built on first need, the copies the instance had before, by the layer they copy.\n * Copies follow their layers when the component's structure changes, as Figma moves them: a\n * layer moved inside the component keeps its copy and the copy's overrides, and a copy whose\n * layer left or was deleted goes.\n */\nexport interface InstanceSyncContext {\n instanceId: string\n overrides: InstanceOverrideState\n matched: Set<string>\n leftovers: Set<string>\n copies?: Map<string, SceneNode[]>\n}\n\nexport function createInstanceSyncContext(\n instanceId: string,\n overrides: InstanceOverrideState\n): InstanceSyncContext {\n return { instanceId, overrides, matched: new Set(), leftovers: new Set() }\n}\n\n/** The component layer a copy in the instance stands for, or a replaced layer stands in for. */\nfunction copiedLayerId(\n graph: SceneGraph,\n node: SceneNode,\n context: InstanceSyncContext\n): string | undefined {\n return (\n replacedComponentLayerId(graph, node) ??\n copiedComponentLayerId(context.overrides, context.instanceId, node)\n )\n}\n\n/** Whether sync goes inside a copy: not into slot content, a swapped instance, or an instance. */\nfunction syncsInside(graph: SceneGraph, node: SceneNode, context: InstanceSyncContext): boolean {\n if (node.type === 'INSTANCE') return false\n if (hasNodeInstanceOverride(context.overrides, context.instanceId, node.id, 'componentId')) {\n return false\n }\n const layer = node.componentId ? graph.nodes.get(node.componentId) : undefined\n return !layer || !ownsSlotContent(graph, node, slotPropertyId(layer))\n}\n\nfunction copiesOf(graph: SceneGraph, context: InstanceSyncContext): Map<string, SceneNode[]> {\n if (context.copies) return context.copies\n const copies = new Map<string, SceneNode[]>()\n const visit = (parent: SceneNode) => {\n for (const id of parent.childIds) {\n const child = graph.nodes.get(id)\n if (!child) continue\n const layerId = copiedLayerId(graph, child, context)\n if (layerId) copies.set(layerId, [...(copies.get(layerId) ?? []), child])\n if (syncsInside(graph, child, context)) visit(child)\n }\n }\n const instance = graph.nodes.get(context.instanceId)\n if (instance) visit(instance)\n context.copies = copies\n return copies\n}\n\n/** A copy of `layerId` the sync has not placed yet, which a moved layer takes along. */\nexport function unplacedCopy(\n graph: SceneGraph,\n context: InstanceSyncContext,\n layerId: string,\n instParentId: string\n): SceneNode | undefined {\n return copiesOf(graph, context)\n .get(layerId)\n ?.find(\n (copy) =>\n !context.matched.has(copy.id) &&\n graph.nodes.has(copy.id) &&\n copy.id !== instParentId &&\n !graph.isDescendant(instParentId, copy.id)\n )\n}\n\n/** Whether any layer in the component subtree at `layerId` already has a copy to move. */\nexport function hasUnplacedCopiesBelow(\n graph: SceneGraph,\n context: InstanceSyncContext,\n layerId: string\n): boolean {\n const copies = copiesOf(graph, context)\n if (copies.size === 0) return false\n const layer = graph.nodes.get(layerId)\n return (layer?.childIds ?? []).some(\n (id) =>\n copies.get(id)?.some((copy) => !context.matched.has(copy.id)) ||\n hasUnplacedCopiesBelow(graph, context, id)\n )\n}\n\n/** The copies one sync of a component's instances removed, by instance and layer. */\nexport interface CopyRemovals {\n keys: Array<[instanceId: string, layerId: string]>\n}\n\n/** A copy the sync removed, kept so the layer coming back, as on undo, brings it back as it was. */\ninterface RemovedCopy {\n /** The copy and everything in it, parents first. */\n nodes: SceneNode[]\n overrides: Map<string, Map<string, unknown>>\n removals: CopyRemovals\n}\n\ninterface RemovedCopyStore {\n /** Removed copies by instance, then by the layer they copied. */\n byInstance: Map<string, Map<string, RemovedCopy>>\n /** Syncs that removed copies, oldest first. */\n removals: CopyRemovals[]\n}\n\nconst removedCopies = new WeakMap<SceneGraph, RemovedCopyStore>()\n\nfunction removedCopyStore(graph: SceneGraph): RemovedCopyStore {\n let store = removedCopies.get(graph)\n if (!store) {\n store = { byInstance: new Map(), removals: [] }\n removedCopies.set(graph, store)\n }\n return store\n}\n\n/**\n * Keeps one edit's removed copies restorable. Only as many edits as undo keeps are kept, so\n * copies no undo can bring back are forgotten, oldest first.\n */\nfunction keepCopyRemovals(graph: SceneGraph, removals: CopyRemovals): void {\n if (removals.keys.length === 0) return\n const store = removedCopyStore(graph)\n store.removals.push(removals)\n while (store.removals.length > DEFAULT_HISTORY_LIMIT) {\n const oldest = store.removals.shift()\n for (const [instanceId, layerId] of oldest?.keys ?? []) {\n const copies = store.byInstance.get(instanceId)\n // A later sync may have removed the same layer's copy again; that one stays.\n if (!copies || copies.get(layerId)?.removals !== oldest) continue\n copies.delete(layerId)\n if (copies.size === 0) store.byInstance.delete(instanceId)\n }\n }\n}\n\nconst activeRemovals = new WeakMap<SceneGraph, CopyRemovals>()\n\n/**\n * Runs `fn` with every copy the syncs inside it remove kept as one group: one edit's syncs, however\n * many components they reach, take one place in the history of removals.\n */\nexport function groupCopyRemovals<T>(graph: SceneGraph, fn: (removals: CopyRemovals) => T): T {\n const active = activeRemovals.get(graph)\n if (active) return fn(active)\n const removals: CopyRemovals = { keys: [] }\n activeRemovals.set(graph, removals)\n try {\n return fn(removals)\n } finally {\n activeRemovals.delete(graph)\n keepCopyRemovals(graph, removals)\n }\n}\n\n/**\n * Brings back the copy of `layerId` the sync removed from this instance, with the same layers\n * and overrides, as Figma restores an instance's override when the layer's deletion is undone.\n */\nexport function restoreRemovedCopy(\n graph: SceneGraph,\n context: InstanceSyncContext,\n layerId: string,\n instParentId: string\n): SceneNode | undefined {\n const store = removedCopyStore(graph)\n const removed = store.byInstance.get(context.instanceId)\n const entry = removed?.get(layerId)\n if (!removed || !entry) return undefined\n removed.delete(layerId)\n if (removed.size === 0) store.byInstance.delete(context.instanceId)\n const root = entry.nodes.at(0)\n if (!root || entry.nodes.some((node) => graph.nodes.has(node.id))) return undefined\n for (const node of entry.nodes) {\n const { id, type, parentId, childIds: _childIds, ...props } = structuredClone(node)\n graph.createNodeWithId(id, type, id === root.id ? instParentId : parentId, props)\n }\n for (const [id, fields] of entry.overrides) context.overrides.descendants.set(id, new Map(fields))\n return graph.nodes.get(root.id)\n}\n\n/**\n * Deletes the copies the sync left over: ones whose layer left the component, was deleted, or\n * now has another copy. Copies the instance owns, such as slot content, are never reached.\n */\nexport function removeLeftoverCopies(\n graph: SceneGraph,\n context: InstanceSyncContext,\n removals: CopyRemovals\n): void {\n const store = removedCopyStore(graph)\n for (const id of context.leftovers) {\n const node = graph.nodes.get(id)\n const layerId = node ? copiedLayerId(graph, node, context) : undefined\n if (!node || !layerId || context.matched.has(id)) continue\n const nodes: SceneNode[] = []\n const collect = (current: SceneNode) => {\n nodes.push(structuredClone(current))\n for (const childId of current.childIds) {\n const child = graph.nodes.get(childId)\n if (child) collect(child)\n }\n }\n collect(node)\n const overrides = new Map<string, Map<string, unknown>>()\n for (const removed of nodes) {\n const fields = context.overrides.descendants.get(removed.id)\n if (!fields) continue\n overrides.set(removed.id, new Map(fields))\n context.overrides.descendants.delete(removed.id)\n }\n let copies = store.byInstance.get(context.instanceId)\n if (!copies) {\n copies = new Map()\n store.byInstance.set(context.instanceId, copies)\n }\n copies.set(layerId, { nodes, overrides, removals })\n removals.keys.push([context.instanceId, layerId])\n graph.deleteNode(id)\n }\n context.leftovers.clear()\n}\n"],"mappings":";;;;;AA2BA,SAAgB,0BACd,YACA,WACqB;CACrB,OAAO;EAAE;EAAY;EAAW,yBAAS,IAAI,IAAI;EAAG,2BAAW,IAAI,IAAI;CAAE;AAC3E;;AAGA,SAAS,cACP,OACA,MACA,SACoB;CACpB,OACE,yBAAyB,OAAO,IAAI,KACpC,uBAAuB,QAAQ,WAAW,QAAQ,YAAY,IAAI;AAEtE;;AAGA,SAAS,YAAY,OAAmB,MAAiB,SAAuC;CAC9F,IAAI,KAAK,SAAS,YAAY,OAAO;CACrC,IAAIA,oBAAwB,QAAQ,WAAW,QAAQ,YAAY,KAAK,IAAI,aAAa,GACvF,OAAO;CAET,MAAM,QAAQ,KAAK,cAAc,MAAM,MAAM,IAAI,KAAK,WAAW,IAAI,KAAA;CACrE,OAAO,CAAC,SAAS,CAAC,gBAAgB,OAAO,MAAM,eAAe,KAAK,CAAC;AACtE;AAEA,SAAS,SAAS,OAAmB,SAAwD;CAC3F,IAAI,QAAQ,QAAQ,OAAO,QAAQ;CACnC,MAAM,yBAAS,IAAI,IAAyB;CAC5C,MAAM,SAAS,WAAsB;EACnC,KAAK,MAAM,MAAM,OAAO,UAAU;GAChC,MAA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W,IAAI,QAAQ,YAAY,MAAM;EACjD;EACA,OAAO,IAAI,SAAS;GAAE;GAAO;GAAW;EAAS,CAAC;EAClD,SAAS,KAAK,KAAK,CAAC,QAAQ,YAAY,OAAO,CAAC;EAChD,MAAM,WAAW,EAAE;CACrB;CACA,QAAQ,UAAU,MAAM;AAC1B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fields.d.ts","names":[],"sources":["../../src/instances/fields.ts"],"mappings":";;cASa;;;;;;cA4BA;;cAsBA,4BAA4B;;
|
|
1
|
+
{"version":3,"file":"fields.d.ts","names":[],"sources":["../../src/instances/fields.ts"],"mappings":";;cASa;;;;;;cA4BA;;cAsBA,4BAA4B;;cA6B5B,8CAAwB;;cAQxB,0CAAoB"}
|
package/dist/instances/fields.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fields.js","names":[],"sources":["../../src/instances/fields.ts"],"sourcesContent":["import { difference } from 'es-toolkit/array'\n\nimport { CORNER_FIELDS, PAINT_FIELDS, STROKE_FIELDS } from '../fields/appearance'\nimport { SIZE_FIELDS, TRANSFORM_FIELDS } from '../fields/geometry'\nimport { AUTO_LAYOUT_FIELDS, SIZE_CONSTRAINT_FIELDS } from '../fields/layout'\nimport { TEXT_STYLE_FIELDS } from '../fields/text'\nimport { STYLE_LINK_FIELDS } from '../shared-styles'\nimport type { SceneNode } from '../types'\n\nexport const INSTANCE_SYNC_TEXT_PROPS = [\n 'name',\n 'text',\n ...TEXT_STYLE_FIELDS,\n 'textDirection',\n 'textAutoResize',\n 'textTruncation',\n 'maxLines',\n 'leadingTrim',\n 'listSpacing',\n 'hangingList',\n // Styled ranges belong to the characters: an instance that overrides its text keeps them.\n 'styleRuns',\n 'textParagraphs'\n] as const\n\n/** Fields that belong to another one: overriding the owner keeps them too. */\nexport const INSTANCE_SYNC_FIELD_OWNERS: Readonly<Partial<Record<string, string>>> = {\n fillStyleId: 'fills',\n styleRuns: 'text',\n textParagraphs: 'text'\n}\n\n/**\n * Where a component's layer sits and how it is shaped, which Figma refuses to override in an\n * instance (\"This property cannot be overridden in an instance\"), so its copies always follow.\n * A layer in an auto layout flow takes its position from the layout instead.\n */\nexport const INSTANCE_FOLLOWED_FIELDS = [\n ...TRANSFORM_FIELDS,\n // A size limit has no field of its own in the file, so an instance cannot keep one of its own.\n 'minWidth',\n 'maxWidth',\n 'minHeight',\n 'maxHeight',\n 'horizontalConstraint',\n 'verticalConstraint',\n 'layoutPositioning',\n 'counterAxisAlignContent',\n 'isMask',\n 'maskType',\n 'arcData',\n 'pointCount',\n 'starInnerRadius',\n 'shapeWithTextType',\n 'shapeUserHeight',\n 'shapeTruncates'\n] as const\n\n/** Fields a component's layer gives its copies unless an instance overrides them. */\nexport const INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = difference(\n [\n ...SIZE_FIELDS,\n ...SIZE_CONSTRAINT_FIELDS,\n ...PAINT_FIELDS,\n ...STROKE_FIELDS,\n ...CORNER_FIELDS,\n ...AUTO_LAYOUT_FIELDS,\n // An instance frame and its component share one alignment in the file, so the instance\n // follows the component's instead of keeping its own.\n 'layoutAlignSelf',\n 'itemReverseZIndex',\n 'gridPosition',\n 'clipsContent',\n 'layoutGrids',\n 'boundVariables',\n 'variableModes',\n // Applied shared styles follow the component unless an instance overrides them.\n ...STYLE_LINK_FIELDS\n ],\n INSTANCE_FOLLOWED_FIELDS\n)\n\n/** How a layer inside an instance sits in its parent and whether it is locked, which its overrides may change. */\nconst INSTANCE_SYNC_CHILD_PROPS = ['layoutGrow', 'layoutAlignSelf', 'locked'] as const\n\n/** Fields an edit to a layer inside an instance records as that instance's override. */\nexport const INSTANCE_OVERRIDE_FIELDS = [\n ...INSTANCE_SYNC_PROPS,\n ...INSTANCE_SYNC_TEXT_PROPS,\n ...INSTANCE_SYNC_CHILD_PROPS,\n 'visible'\n] as const\n\n/** Fields a component's layer gives the copies of it in every instance. */\nexport const INSTANCE_SYNC_FIELDS = [\n ...INSTANCE_OVERRIDE_FIELDS,\n ...INSTANCE_FOLLOWED_FIELDS\n] as const\n\n/**\n * Fields an instance frame takes from its component frame, where the file keeps one value for\n * both: a layer inside an instance has no field of its own for them.\n */\nexport const INSTANCE_FRAME_FOLLOWED_FIELDS: (keyof SceneNode)[] = [\n 'layoutPositioning',\n 'layoutGrow',\n 'minWidth',\n 'maxWidth',\n 'minHeight',\n 'maxHeight'\n]\n"],"mappings":";;;;;;;AASA,MAAa,2BAA2B;CACtC;CACA;CACA,GAAG;CACH;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;AACF;;AAGA,MAAa,6BAAwE;CACnF,aAAa;CACb,WAAW;CACX,gBAAgB;AAClB;;;;;;AAOA,MAAa,2BAA2B;CACtC,GAAG;CAEH;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAa,sBAA2C,WACtD;CACE,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAGH;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,GAAG;AACL,GACA,wBACF;;AAGA,MAAM,4BAA4B;CAAC;CAAc;CAAmB;AAAQ;;AAG5E,MAAa,2BAA2B;CACtC,GAAG;CACH,GAAG;CACH,GAAG;CACH;AACF;;AAGA,MAAa,uBAAuB,CAClC,GAAG,0BACH,GAAG,wBACL;;;;;AAMA,MAAa,iCAAsD;CACjE;CACA;CACA;CACA;CACA;CACA;AACF"}
|
|
1
|
+
{"version":3,"file":"fields.js","names":[],"sources":["../../src/instances/fields.ts"],"sourcesContent":["import { difference } from 'es-toolkit/array'\n\nimport { CORNER_FIELDS, PAINT_FIELDS, STROKE_FIELDS } from '../fields/appearance'\nimport { SIZE_FIELDS, TRANSFORM_FIELDS } from '../fields/geometry'\nimport { AUTO_LAYOUT_FIELDS, SIZE_CONSTRAINT_FIELDS } from '../fields/layout'\nimport { TEXT_STYLE_FIELDS } from '../fields/text'\nimport { STYLE_LINK_FIELDS } from '../shared-styles'\nimport type { SceneNode } from '../types'\n\nexport const INSTANCE_SYNC_TEXT_PROPS = [\n 'name',\n 'text',\n ...TEXT_STYLE_FIELDS,\n 'textDirection',\n 'textAutoResize',\n 'textTruncation',\n 'maxLines',\n 'leadingTrim',\n 'listSpacing',\n 'hangingList',\n // Styled ranges belong to the characters: an instance that overrides its text keeps them.\n 'styleRuns',\n 'textParagraphs'\n] as const\n\n/** Fields that belong to another one: overriding the owner keeps them too. */\nexport const INSTANCE_SYNC_FIELD_OWNERS: Readonly<Partial<Record<string, string>>> = {\n fillStyleId: 'fills',\n styleRuns: 'text',\n textParagraphs: 'text'\n}\n\n/**\n * Where a component's layer sits and how it is shaped, which Figma refuses to override in an\n * instance (\"This property cannot be overridden in an instance\"), so its copies always follow.\n * A layer in an auto layout flow takes its position from the layout instead.\n */\nexport const INSTANCE_FOLLOWED_FIELDS = [\n ...TRANSFORM_FIELDS,\n // A size limit has no field of its own in the file, so an instance cannot keep one of its own.\n 'minWidth',\n 'maxWidth',\n 'minHeight',\n 'maxHeight',\n 'horizontalConstraint',\n 'verticalConstraint',\n 'layoutPositioning',\n 'counterAxisAlignContent',\n 'isMask',\n 'maskType',\n 'arcData',\n 'pointCount',\n 'starInnerRadius',\n 'shapeWithTextType',\n 'shapeUserHeight',\n 'shapeTruncates'\n] as const\n\n/** Fields a component's layer gives its copies unless an instance overrides them. */\nexport const INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = difference(\n [\n ...SIZE_FIELDS,\n ...SIZE_CONSTRAINT_FIELDS,\n ...PAINT_FIELDS,\n ...STROKE_FIELDS,\n ...CORNER_FIELDS,\n ...AUTO_LAYOUT_FIELDS,\n // An instance frame and its component share one alignment in the file, so the instance\n // follows the component's instead of keeping its own.\n 'layoutAlignSelf',\n 'itemReverseZIndex',\n 'gridPosition',\n 'clipsContent',\n 'overflowDirection',\n 'scrollBehavior',\n 'layoutGrids',\n 'boundVariables',\n 'variableModes',\n // Applied shared styles follow the component unless an instance overrides them.\n ...STYLE_LINK_FIELDS\n ],\n INSTANCE_FOLLOWED_FIELDS\n)\n\n/** How a layer inside an instance sits in its parent and whether it is locked, which its overrides may change. */\nconst INSTANCE_SYNC_CHILD_PROPS = ['layoutGrow', 'layoutAlignSelf', 'locked'] as const\n\n/** Fields an edit to a layer inside an instance records as that instance's override. */\nexport const INSTANCE_OVERRIDE_FIELDS = [\n ...INSTANCE_SYNC_PROPS,\n ...INSTANCE_SYNC_TEXT_PROPS,\n ...INSTANCE_SYNC_CHILD_PROPS,\n 'visible'\n] as const\n\n/** Fields a component's layer gives the copies of it in every instance. */\nexport const INSTANCE_SYNC_FIELDS = [\n ...INSTANCE_OVERRIDE_FIELDS,\n ...INSTANCE_FOLLOWED_FIELDS\n] as const\n\n/**\n * Fields an instance frame takes from its component frame, where the file keeps one value for\n * both: a layer inside an instance has no field of its own for them.\n */\nexport const INSTANCE_FRAME_FOLLOWED_FIELDS: (keyof SceneNode)[] = [\n 'layoutPositioning',\n 'layoutGrow',\n 'minWidth',\n 'maxWidth',\n 'minHeight',\n 'maxHeight'\n]\n"],"mappings":";;;;;;;AASA,MAAa,2BAA2B;CACtC;CACA;CACA,GAAG;CACH;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;AACF;;AAGA,MAAa,6BAAwE;CACnF,aAAa;CACb,WAAW;CACX,gBAAgB;AAClB;;;;;;AAOA,MAAa,2BAA2B;CACtC,GAAG;CAEH;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAa,sBAA2C,WACtD;CACE,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAGH;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,GAAG;AACL,GACA,wBACF;;AAGA,MAAM,4BAA4B;CAAC;CAAc;CAAmB;AAAQ;;AAG5E,MAAa,2BAA2B;CACtC,GAAG;CACH,GAAG;CACH,GAAG;CACH;AACF;;AAGA,MAAa,uBAAuB,CAClC,GAAG,0BACH,GAAG,wBACL;;;;;AAMA,MAAa,iCAAsD;CACjE;CACA;CACA;CACA;CACA;CACA;AACF"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { NodeCloneMode } from "../copy.js";
|
|
2
2
|
import { InstanceOverrideState } from "./overrides.js";
|
|
3
3
|
import { canCreateInstance, createsComponentCycle, cycleSafeParent } from "./cycles.js";
|
|
4
|
+
import { walkInstanceSources } from "./source-walk.js";
|
|
4
5
|
import { instanceMainComponent } from "./main-component.js";
|
|
5
6
|
import { isInShownReplacedLayer, isReplacedLayer, owningInstance, replacedComponentLayerId, showsReplacedLayer } from "./replacements.js";
|
|
6
7
|
import { INSTANCE_FOLLOWED_FIELDS, INSTANCE_OVERRIDE_FIELDS, INSTANCE_SYNC_FIELDS, INSTANCE_SYNC_PROPS, INSTANCE_SYNC_TEXT_PROPS } from "./fields.js";
|
|
@@ -95,5 +96,5 @@ declare function replaceInstanceLayer(graph: SceneGraph, targetId: string, repla
|
|
|
95
96
|
*/
|
|
96
97
|
declare function restoreReplacedLayer(graph: SceneGraph, nodeId: string): boolean;
|
|
97
98
|
//#endregion
|
|
98
|
-
export { AssignmentOverrideState, INSTANCE_FOLLOWED_FIELDS, INSTANCE_OVERRIDE_FIELDS, INSTANCE_SYNC_FIELDS, INSTANCE_SYNC_PROPS, INSTANCE_SYNC_TEXT_PROPS, SwapInstanceOptions, assignmentOverrideOwner, canCreateInstance, canReplaceInstanceLayer, copyInstanceComponentProps, createInstance, createsComponentCycle, cycleSafeParent, detachInstance, findInstanceAncestor, getInstances, getMainComponent, hasInstanceOverride, instanceMainComponent, instanceOverrideFields, isInShownReplacedLayer, isReplacedLayer, owningInstance, populateInstanceChildren, recordAssignmentOverride, recordInstanceOverride, replaceInstanceLayer, replacedComponentLayerId, restoreAssignmentOverrideState, restoreReplacedLayer, retargetCopiedOverrides, showsReplacedLayer, swapInstanceComponent, syncInstance, syncInstances, syncInstancesTogether, takeAssignmentOverrideState, takesOwnSize };
|
|
99
|
+
export { AssignmentOverrideState, INSTANCE_FOLLOWED_FIELDS, INSTANCE_OVERRIDE_FIELDS, INSTANCE_SYNC_FIELDS, INSTANCE_SYNC_PROPS, INSTANCE_SYNC_TEXT_PROPS, SwapInstanceOptions, assignmentOverrideOwner, canCreateInstance, canReplaceInstanceLayer, copyInstanceComponentProps, createInstance, createsComponentCycle, cycleSafeParent, detachInstance, findInstanceAncestor, getInstances, getMainComponent, hasInstanceOverride, instanceMainComponent, instanceOverrideFields, isInShownReplacedLayer, isReplacedLayer, owningInstance, populateInstanceChildren, recordAssignmentOverride, recordInstanceOverride, replaceInstanceLayer, replacedComponentLayerId, restoreAssignmentOverrideState, restoreReplacedLayer, retargetCopiedOverrides, showsReplacedLayer, swapInstanceComponent, syncInstance, syncInstances, syncInstancesTogether, takeAssignmentOverrideState, takesOwnSize, walkInstanceSources };
|
|
99
100
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/instances/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/instances/index.ts"],"mappings":";;;;;;;;;;iBAkEgB,2BAA2B,WAAW,YAAY,QAAQ;iBAiB1D,eACd,OAAO,YACP,qBACA,kBACA,YAAW,QAAQ,aAClB;iBAoBa,yBACd,OAAO,YACP,oBACA,qBACA,OAAM;UAyCS;;;;;;EAMf;;;;;;;EAOA;;iBAGc,sBACd,OAAO,YACP,oBACA,uBACE,UAAkB,qBAA2B;iBA+DjC,cAAc,OAAO,YAAY;;;;;iBAQjC,sBAAsB,OAAO,YAAY,cAAc;;iBAOvD,aAAa,OAAO,YAAY;;;;;;iBAyEhC,wBACd,OAAO,YACP,QAAQ;iBAeM,eAAe,OAAO,YAAY;iBAmElC,iBAAiB,OAAO,YAAY,qBAAqB;iBAMzD,aAAa,OAAO,YAAY,sBAAsB;;iBAYtD,qBAAqB,OAAO,YAAY,iBAAiB;;;;;iBAazD,aAAa,OAAO,YAAY,MAAM;;;;iBAOtC,oBAAoB,OAAO,YAAY,gBAAgB;;;;;iBA2CvD,wBACd,OAAO,YACP,qBACC;;UAMc;EACf;EACA,WAAW;;iBAGG,4BACd,OAAO,YACP,qBACC;iBAOa,+BACd,OAAO,YACP,OAAO;;;;;;iBAYO,yBACd,OAAO,YACP,oBACA,oBACA;;;;;iBAkBc,uBAAuB,MAAM,WAAW,SAAS,QAAQ;iBAMzD,uBACd,OAAO,YACP,gBACA,QAAQ;;iBAsDM,wBAAwB,OAAO,YAAY;;;;;;;;;iBAqB3C,qBACd,OAAO,YACP,kBACA;;;;;iBAmDc,qBAAqB,OAAO,YAAY"}
|
package/dist/instances/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { REPLACED_LAYER_OVERRIDE, assignmentOverrideField, cloneInstanceOverrideState, copiedComponentLayerId, createInstanceOverrideState, getInstanceOverride, hasInstanceOverride as hasInstanceOverride$1, overriddenAssignmentId, setInstanceOverride, variableModeOverrideField } from "./overrides.js";
|
|
1
|
+
import { REPLACED_LAYER_OVERRIDE, assignmentOverrideField, cloneInstanceOverrideState, copiedComponentLayerId, createInstanceOverrideState, getInstanceOverride, hasInstanceOverride as hasInstanceOverride$1, overriddenAssignmentId, ownInstanceOverrides, setInstanceOverride, variableModeOverrideField } from "./overrides.js";
|
|
2
2
|
import { shapeGeometryChanges } from "../resize.js";
|
|
3
3
|
import { instanceMainComponent } from "./main-component.js";
|
|
4
4
|
import { detachOwnedSlotContent, restoreOwnedSlotContent } from "../slots/frames.js";
|
|
@@ -59,9 +59,9 @@ function populateInstanceChildren(graph, instanceId, componentId, mode = "deep")
|
|
|
59
59
|
function recordNestedSwap(graph, instance, componentId) {
|
|
60
60
|
const owner = instance.parentId ? findInstanceAncestor(graph, instance.parentId) : void 0;
|
|
61
61
|
if (!owner) return;
|
|
62
|
-
if (typeof getInstanceOverride(owner.instanceOverrides, owner.id, instance.id, "sourceComponentId") !== "string" && instance.componentId) setInstanceOverride(owner
|
|
63
|
-
setInstanceOverride(owner
|
|
64
|
-
graph.updateNode(owner.id, { instanceOverrides: owner
|
|
62
|
+
if (typeof getInstanceOverride(owner.instanceOverrides, owner.id, instance.id, "sourceComponentId") !== "string" && instance.componentId) setInstanceOverride(ownInstanceOverrides(owner), owner.id, instance.id, "sourceComponentId", instance.componentId);
|
|
63
|
+
setInstanceOverride(ownInstanceOverrides(owner), owner.id, instance.id, "componentId", componentId);
|
|
64
|
+
graph.updateNode(owner.id, { instanceOverrides: ownInstanceOverrides(owner) });
|
|
65
65
|
}
|
|
66
66
|
function swapInstanceComponent(graph, instanceId, componentId, { keepName = false, restoreOverrides = true } = {}) {
|
|
67
67
|
const instance = graph.nodes.get(instanceId);
|
|
@@ -150,8 +150,9 @@ function syncInstancesOf(graph, componentId, instances) {
|
|
|
150
150
|
keepOwnContentSize(graph, updates, instance, source);
|
|
151
151
|
if (updates.width !== void 0 || updates.height !== void 0) Object.assign(updates, shapeGeometryChanges(instance, updates.width ?? instance.width, updates.height ?? instance.height));
|
|
152
152
|
updateSyncedProps(graph, instance, updates, (key) => isProtectedSyncField(instance, key, protectedField));
|
|
153
|
-
const
|
|
154
|
-
|
|
153
|
+
const owned = ownInstanceOverrides(instance);
|
|
154
|
+
const context = createInstanceSyncContext(instance.id, owned);
|
|
155
|
+
syncChildren(graph, component.id, instance.id, owned, context);
|
|
155
156
|
removeLeftoverCopies(graph, context, removals);
|
|
156
157
|
}
|
|
157
158
|
});
|
|
@@ -311,7 +312,7 @@ function restoreAssignmentOverrideState(graph, state) {
|
|
|
311
312
|
function recordAssignmentOverride(graph, instanceId, propertyId, value) {
|
|
312
313
|
const outer = assignmentOverrideOwner(graph, instanceId);
|
|
313
314
|
if (!outer) return;
|
|
314
|
-
setInstanceOverride(outer
|
|
315
|
+
setInstanceOverride(ownInstanceOverrides(outer), outer.id, instanceId, assignmentOverrideField(propertyId), value);
|
|
315
316
|
graph.updateNode(outer.id, { instanceOverrides: outer.instanceOverrides });
|
|
316
317
|
}
|
|
317
318
|
/**
|
|
@@ -349,8 +350,8 @@ function forgetOverridesOf(graph, nodeId) {
|
|
|
349
350
|
if (!parentId) return;
|
|
350
351
|
graph.closest(parentId, (ancestor) => {
|
|
351
352
|
if (ancestor.type !== "INSTANCE") return false;
|
|
352
|
-
const
|
|
353
|
-
if (ids.some((id) => descendants.delete(id))) graph.updateNode(ancestor.id, { instanceOverrides:
|
|
353
|
+
const owned = ownInstanceOverrides(ancestor);
|
|
354
|
+
if (ids.some((id) => owned.descendants.delete(id))) graph.updateNode(ancestor.id, { instanceOverrides: owned });
|
|
354
355
|
return false;
|
|
355
356
|
});
|
|
356
357
|
}
|
|
@@ -400,8 +401,8 @@ function replaceInstanceLayer(graph, targetId, replacementId) {
|
|
|
400
401
|
verticalConstraint: target.verticalConstraint
|
|
401
402
|
});
|
|
402
403
|
graph.deleteNode(target.id);
|
|
403
|
-
setInstanceOverride(owner
|
|
404
|
-
graph.updateNode(owner.id, { instanceOverrides: owner
|
|
404
|
+
setInstanceOverride(ownInstanceOverrides(owner), owner.id, replacementId, REPLACED_LAYER_OVERRIDE, layerId);
|
|
405
|
+
graph.updateNode(owner.id, { instanceOverrides: ownInstanceOverrides(owner) });
|
|
405
406
|
return true;
|
|
406
407
|
}
|
|
407
408
|
/**
|
|
@@ -422,6 +423,6 @@ function restoreReplacedLayer(graph, nodeId) {
|
|
|
422
423
|
return true;
|
|
423
424
|
}
|
|
424
425
|
//#endregion
|
|
425
|
-
export { INSTANCE_FOLLOWED_FIELDS, INSTANCE_OVERRIDE_FIELDS, INSTANCE_SYNC_FIELDS, INSTANCE_SYNC_PROPS, INSTANCE_SYNC_TEXT_PROPS, assignmentOverrideOwner, canCreateInstance, canReplaceInstanceLayer, copyInstanceComponentProps, createInstance, createsComponentCycle, cycleSafeParent, detachInstance, findInstanceAncestor, getInstances, getMainComponent, hasInstanceOverride, instanceMainComponent, instanceOverrideFields, isInShownReplacedLayer, isReplacedLayer, owningInstance, populateInstanceChildren, recordAssignmentOverride, recordInstanceOverride, replaceInstanceLayer, replacedComponentLayerId, restoreAssignmentOverrideState, restoreReplacedLayer, retargetCopiedOverrides, showsReplacedLayer, swapInstanceComponent, syncInstance, syncInstances, syncInstancesTogether, takeAssignmentOverrideState, takesOwnSize };
|
|
426
|
+
export { INSTANCE_FOLLOWED_FIELDS, INSTANCE_OVERRIDE_FIELDS, INSTANCE_SYNC_FIELDS, INSTANCE_SYNC_PROPS, INSTANCE_SYNC_TEXT_PROPS, assignmentOverrideOwner, canCreateInstance, canReplaceInstanceLayer, copyInstanceComponentProps, createInstance, createsComponentCycle, cycleSafeParent, detachInstance, findInstanceAncestor, getInstances, getMainComponent, hasInstanceOverride, instanceMainComponent, instanceOverrideFields, isInShownReplacedLayer, isReplacedLayer, owningInstance, populateInstanceChildren, recordAssignmentOverride, recordInstanceOverride, replaceInstanceLayer, replacedComponentLayerId, restoreAssignmentOverrideState, restoreReplacedLayer, retargetCopiedOverrides, showsReplacedLayer, swapInstanceComponent, syncInstance, syncInstances, syncInstancesTogether, takeAssignmentOverrideState, takesOwnSize, walkInstanceSources };
|
|
426
427
|
|
|
427
428
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["hasNodeInstanceOverride"],"sources":["../../src/instances/index.ts"],"sourcesContent":["import type { NodeCloneMode } from '../copy'\nimport type { SceneGraph } from '../graph'\nimport { shapeGeometryChanges } from '../resize'\nimport { slotScope } from '../slots/content'\nimport { detachOwnedSlotContent, restoreOwnedSlotContent } from '../slots/frames'\nimport { changesMoreThanStrokeLines } from '../strokes'\nimport type { SceneNode } from '../types'\nimport { applyBoundPaintColorsIn, keepCopyBoundPaints } from '../variables/paints'\nimport { keepOwnContentSize } from './content-size'\nimport { createInstanceSyncContext, groupCopyRemovals, removeLeftoverCopies } from './copies'\nimport { canCreateInstance, createsComponentCycle } from './cycles'\nimport {\n INSTANCE_FRAME_FOLLOWED_FIELDS,\n INSTANCE_OVERRIDE_FIELDS,\n INSTANCE_SYNC_PROPS\n} from './fields'\nimport { differingVariableModeCollections } from './modes'\nimport {\n assignmentOverrideField,\n cloneInstanceOverrideState,\n copiedComponentLayerId,\n createInstanceOverrideState,\n getInstanceOverride,\n hasInstanceOverride as hasNodeInstanceOverride,\n type InstanceOverrideState,\n overriddenAssignmentId,\n REPLACED_LAYER_OVERRIDE,\n setInstanceOverride,\n variableModeOverrideField\n} from './overrides'\nimport { owningInstance, replacedLayerIn } from './replacements'\nimport { walkInstanceSources } from './source-walk'\nimport { captureInstanceOverrides, restoreInstanceOverrides } from './swap-overrides'\nimport {\n applySyncedStrokeLines,\n bindingProtection,\n cloneChildrenWithMapping,\n copyProp,\n enclosingInstanceOverrideFields,\n isProtectedSyncField,\n sourceInTargetCoordinates,\n syncBindingFields,\n syncChildren,\n syncVariableModeFields,\n updateSyncedProps\n} from './sync'\n\nexport { canCreateInstance, createsComponentCycle, cycleSafeParent } from './cycles'\nexport { instanceMainComponent } from './main-component'\nexport {\n isInShownReplacedLayer,\n isReplacedLayer,\n owningInstance,\n replacedComponentLayerId,\n showsReplacedLayer\n} from './replacements'\nexport {\n INSTANCE_FOLLOWED_FIELDS,\n INSTANCE_OVERRIDE_FIELDS,\n INSTANCE_SYNC_FIELDS,\n INSTANCE_SYNC_PROPS,\n INSTANCE_SYNC_TEXT_PROPS\n} from './fields'\n\nexport function copyInstanceComponentProps(component: SceneNode): Partial<SceneNode> {\n const props: Partial<SceneNode> = {}\n // A new instance starts with the fields its component frame lends it, as resyncing one does.\n for (const key of [...INSTANCE_SYNC_PROPS, ...INSTANCE_FRAME_FOLLOWED_FIELDS])\n copyProp(props, component, key)\n return props\n}\n\n/**\n * The name Figma gives a new instance of `component`: its component set's name for a variant,\n * whose own name only says which variant it is, and the component's own name otherwise.\n */\nfunction instanceComponentName(graph: SceneGraph, component: SceneNode): string {\n const parent = component.parentId ? graph.nodes.get(component.parentId) : undefined\n return parent?.type === 'COMPONENT_SET' ? parent.name : component.name\n}\n\nexport function createInstance(\n graph: SceneGraph,\n componentId: string,\n parentId: string,\n overrides: Partial<SceneNode> = {}\n): SceneNode | null {\n const component = graph.nodes.get(componentId)\n if (component?.type !== 'COMPONENT' || !canCreateInstance(graph, componentId, parentId))\n return null\n\n const props: Partial<SceneNode> = {\n ...copyInstanceComponentProps(component),\n name: instanceComponentName(graph, component)\n }\n\n // The component checked above is the one the instance shows, whatever `overrides` holds.\n const instance = graph.createNode('INSTANCE', parentId, { ...props, ...overrides, componentId })\n\n cloneChildrenWithMapping(graph, component.id, instance.id)\n // A copy shows its bound paints in its own context, not as its component's paints hold them.\n applyBoundPaintColorsIn(graph, instance.id)\n\n return instance\n}\n\nexport function populateInstanceChildren(\n graph: SceneGraph,\n instanceId: string,\n componentId: string,\n mode: NodeCloneMode = 'deep'\n): void {\n const instance = graph.nodes.get(instanceId)\n const component = graph.nodes.get(componentId)\n if (!instance || !component || instance.type !== 'INSTANCE') return\n cloneChildrenWithMapping(graph, componentId, instanceId, mode)\n}\n\n/**\n * A nested instance's link to the enclosing component's record is its `componentId` when it\n * was populated by cloning. A swap replaces that field, so keep the correspondence as the\n * owner's `sourceComponentId` override and record the swap itself; materialized documents\n * already carry the correspondence and only gain the swap.\n */\nfunction recordNestedSwap(graph: SceneGraph, instance: SceneNode, componentId: string): void {\n const owner = instance.parentId ? findInstanceAncestor(graph, instance.parentId) : undefined\n if (!owner) return\n const existing = getInstanceOverride(\n owner.instanceOverrides,\n owner.id,\n instance.id,\n 'sourceComponentId'\n )\n if (typeof existing !== 'string' && instance.componentId)\n setInstanceOverride(\n owner.instanceOverrides,\n owner.id,\n instance.id,\n 'sourceComponentId',\n instance.componentId\n )\n setInstanceOverride(owner.instanceOverrides, owner.id, instance.id, 'componentId', componentId)\n graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides })\n}\n\nexport interface SwapInstanceOptions {\n /**\n * Keep the instance's name even when it is its old component's. A swap otherwise renames such\n * an instance after the new component, as Figma does; a view that only shows another variant,\n * such as preview, keeps names so layer paths stay the same.\n */\n keepName?: boolean\n /**\n * Keep the overrides the instance's layers record, matched to the layers of the new component\n * that take their places, as Figma keeps them when a variant changes. A swap that only\n * materializes a layer the caller re-applies itself, such as a pen icon's glyph, skips this:\n * what the placeholder recorded is scaffolding, not a user's edit.\n */\n restoreOverrides?: boolean\n}\n\nexport function swapInstanceComponent(\n graph: SceneGraph,\n instanceId: string,\n componentId: string,\n { keepName = false, restoreOverrides = true }: SwapInstanceOptions = {}\n): void {\n const instance = graph.nodes.get(instanceId)\n const component = graph.nodes.get(componentId)\n if (!instance || component?.type !== 'COMPONENT' || instance.type !== 'INSTANCE') return\n if (instance.parentId && !canCreateInstance(graph, componentId, instance.parentId)) return\n\n const previousComponent = instance.componentId ? graph.nodes.get(instance.componentId) : undefined\n recordNestedSwap(graph, instance, componentId)\n const updates: Partial<SceneNode> = { componentId }\n const source = sourceInTargetCoordinates(component, instance.componentScale)\n const overridden = (field: string) =>\n hasNodeInstanceOverride(instance.instanceOverrides, instance.id, instance.id, field)\n for (const key of INSTANCE_SYNC_PROPS) {\n if (key === 'variableModes' || overridden(key)) continue\n copyProp(updates, source, key)\n }\n syncVariableModeFields(instance, source, updates, overridden)\n applySyncedStrokeLines(graph, instance, updates, overridden)\n\n if (\n !keepName &&\n (!previousComponent || instance.name === instanceComponentName(graph, previousComponent))\n )\n updates.name = instanceComponentName(graph, component)\n\n keepCopyBoundPaints(graph, instance, updates)\n const childIds = Array.from(instance.childIds)\n const slotContent = detachOwnedSlotContent(graph, instance)\n swapInstanceLayers(graph, instanceId, componentId, updates, childIds, restoreOverrides)\n restoreOwnedSlotContent(graph, instance, slotContent)\n}\n\n/**\n * Replaces the instance's layers with clones of its new component's and gives the recorded\n * overrides back to the layers that take the old ones' places, matched by name path.\n */\nfunction swapInstanceLayers(\n graph: SceneGraph,\n instanceId: string,\n componentId: string,\n updates: Partial<SceneNode>,\n childIds: string[],\n restoreOverrides: boolean\n): void {\n // The clones take new IDs, so what was recorded for the removed layers only applies again once\n // it is matched to the layers of the new component that take their places.\n const capturedOverrides = restoreOverrides\n ? captureInstanceOverrides(graph, graph.nodes.get(instanceId) as SceneNode)\n : undefined\n for (const childId of childIds) {\n forgetOverridesOf(graph, childId)\n graph.deleteNode(childId)\n }\n graph.updateNode(instanceId, updates)\n cloneChildrenWithMapping(graph, componentId, instanceId)\n applyBoundPaintColorsIn(graph, instanceId)\n const swapped = graph.nodes.get(instanceId)\n if (swapped && capturedOverrides) restoreInstanceOverrides(graph, swapped, capturedOverrides)\n}\n\nconst syncingComponentsByGraph = new WeakMap<SceneGraph, Set<string>>()\n\nexport function syncInstances(graph: SceneGraph, componentId: string): void {\n syncInstancesOf(graph, componentId, getInstances(graph, componentId))\n}\n\n/**\n * Syncs each component's instances, in order, as one edit: the copies they remove stay\n * restorable together for as long as undo keeps that edit.\n */\nexport function syncInstancesTogether(graph: SceneGraph, componentIds: Iterable<string>): void {\n groupCopyRemovals(graph, () => {\n for (const id of componentIds) syncInstances(graph, id)\n })\n}\n\n/** Syncs one instance from its component, as `syncInstances` does for every instance. */\nexport function syncInstance(graph: SceneGraph, instanceId: string): void {\n const instance = graph.nodes.get(instanceId)\n if (instance?.type !== 'INSTANCE' || !instance.componentId) return\n syncInstancesOf(graph, instance.componentId, [instance])\n}\n\nfunction syncInstancesOf(\n graph: SceneGraph,\n componentId: string,\n instances: Iterable<SceneNode>\n): void {\n const component = graph.nodes.get(componentId)\n if (component?.type !== 'COMPONENT') return\n let syncing = syncingComponentsByGraph.get(graph)\n if (!syncing) {\n syncing = new Set()\n syncingComponentsByGraph.set(graph, syncing)\n }\n if (syncing.has(componentId)) return\n syncing.add(componentId)\n try {\n groupCopyRemovals(graph, (removals) => {\n for (const instance of instances) {\n const enclosing = enclosingInstanceOverrideFields(graph, instance)\n enclosing.push(new Set(instance.instanceOverrides.self.keys()))\n const protectedField = bindingProtection(enclosing)\n const source = sourceInTargetCoordinates(component, instance.componentScale)\n const updates: Partial<SceneNode> = {}\n syncBindingFields(instance, source, updates, protectedField)\n syncVariableModeFields(instance, source, updates, protectedField)\n for (const key of INSTANCE_SYNC_PROPS) {\n if (key === 'boundVariables' || key === 'variableModes') continue\n if (isProtectedSyncField(instance, key, protectedField)) continue\n copyProp(updates, source, key)\n }\n // The file keeps one value for the instance frame and its component, so the frame takes\n // those the layers inside an instance may not set.\n for (const key of INSTANCE_FRAME_FOLLOWED_FIELDS) {\n if (!isProtectedSyncField(instance, key, protectedField)) copyProp(updates, source, key)\n }\n // An instance that hugs its layers sizes to what it shows, not to the component.\n keepOwnContentSize(graph, updates, instance, source)\n // A size that follows the component invalidates outlines the file saved on the instance;\n // its live box draws them again.\n if (updates.width !== undefined || updates.height !== undefined) {\n Object.assign(\n updates,\n shapeGeometryChanges(\n instance,\n updates.width ?? instance.width,\n updates.height ?? instance.height\n )\n )\n }\n updateSyncedProps(graph, instance, updates, (key) =>\n isProtectedSyncField(instance, key, protectedField)\n )\n const context = createInstanceSyncContext(instance.id, instance.instanceOverrides)\n syncChildren(graph, component.id, instance.id, instance.instanceOverrides, context)\n removeLeftoverCopies(graph, context, removals)\n }\n })\n } finally {\n syncing.delete(componentId)\n }\n}\n\n/**\n * Renames the layers that the copied instances among `copies` record overrides for to their\n * copies, as a copied instance records its own layers' overrides. The values keep naming what\n * they name, since a copy shows the same components as its source.\n */\nexport function retargetCopiedOverrides(\n graph: SceneGraph,\n copies: ReadonlyMap<string, string>\n): void {\n for (const id of copies.values()) {\n const node = graph.nodes.get(id)\n if (node?.type !== 'INSTANCE' || node.instanceOverrides.descendants.size === 0) continue\n const descendants = new Map(\n [...node.instanceOverrides.descendants].map(([target, fields]) => [\n copies.get(target) ?? target,\n fields\n ])\n )\n graph.updateNode(id, { instanceOverrides: { ...node.instanceOverrides, descendants } })\n }\n}\n\nexport function detachInstance(graph: SceneGraph, instanceId: string): void {\n const node = graph.nodes.get(instanceId)\n if (node?.type !== 'INSTANCE') return\n for (const nested of outermostNestedInstances(graph, node))\n adoptNestedOverrides(graph, node, nested)\n // Through `updateNode`, so the instance index, change observers, and undo recorders see it.\n graph.updateNode(instanceId, {\n type: 'FRAME',\n componentId: null,\n instanceOverrides: createInstanceOverrideState()\n })\n // Its mirrored layers stand on their own: a component child id would name a layer of another\n // node, which the format never stores and a later sync would read as a link back. A nested\n // instance is not a mirror and keeps its own links, which its overrides are written through.\n const detachLinks = (parentId: string): void => {\n for (const child of graph.getChildren(parentId)) {\n if (child.type === 'INSTANCE') continue\n if (child.componentId) graph.updateNode(child.id, { componentId: null })\n detachLinks(child.id)\n }\n }\n detachLinks(instanceId)\n}\n\n// A swap's bookkeeping belongs to the instance enclosing the swapped one, never to the swapped one.\nconst OWNER_ONLY_FIELDS = new Set(['componentId', 'sourceComponentId'])\n\nfunction outermostNestedInstances(graph: SceneGraph, instance: SceneNode): SceneNode[] {\n return graph\n .getChildren(instance.id)\n .flatMap((child) =>\n child.type === 'INSTANCE' ? [child] : outermostNestedInstances(graph, child)\n )\n}\n\n/**\n * An instance a detached one holds stands on its own once that one is a frame, and so must what\n * makes it differ from its component. Cloned in, it kept the overrides of the instance it copies,\n * under that instance's layers; those, and the ones the detached instance recorded on its layers,\n * now go under its own.\n */\nfunction adoptNestedOverrides(graph: SceneGraph, detached: SceneNode, nested: SceneNode): void {\n const ownLayer = new Map<string, string>()\n walkInstanceSources(graph, nested, (source, target) => {\n ownLayer.set(source.id, target.id)\n return true\n })\n const { self, descendants: kept } = cloneInstanceOverrideState(nested.instanceOverrides)\n const outer = cloneInstanceOverrideState(detached.instanceOverrides).descendants\n const descendants = new Map<string, Map<string, unknown>>()\n const claim = (layerId: string, fields: Map<string, unknown>): void => {\n const merged = descendants.get(layerId)\n if (!merged) descendants.set(layerId, fields)\n else for (const [field, value] of fields) merged.set(field, value)\n }\n // What was recorded on its own layers is more recent than what it copied, so it is laid on top.\n for (const [layerId, fields] of kept)\n if (ownLayer.has(layerId)) claim(ownLayer.get(layerId) ?? layerId, fields)\n for (const [layerId, fields] of kept) if (!ownLayer.has(layerId)) claim(layerId, fields)\n for (const [layerId, fields] of outer) {\n if (layerId === nested.id) {\n for (const [field, value] of fields) if (!OWNER_ONLY_FIELDS.has(field)) self.set(field, value)\n } else if (graph.isDescendant(layerId, nested.id)) claim(layerId, fields)\n }\n graph.updateNode(nested.id, { instanceOverrides: { self, descendants } })\n}\n\nexport function getMainComponent(graph: SceneGraph, instanceId: string): SceneNode | undefined {\n const node = graph.nodes.get(instanceId)\n if (!node?.componentId) return undefined\n return graph.nodes.get(node.componentId)\n}\n\nexport function getInstances(graph: SceneGraph, componentId: string): SceneNode[] {\n const ids = graph.instanceIndex.get(componentId)\n if (!ids) return []\n const instances: SceneNode[] = []\n for (const id of ids) {\n const node = graph.nodes.get(id)\n if (node) instances.push(node)\n }\n return instances\n}\n\n/** Nearest INSTANCE at or above `nodeId` — self, parent, grandparent, etc. */\nexport function findInstanceAncestor(graph: SceneGraph, nodeId: string): SceneNode | undefined {\n let current = graph.nodes.get(nodeId)\n while (current) {\n if (current.type === 'INSTANCE') return current\n current = current.parentId ? graph.nodes.get(current.parentId) : undefined\n }\n return undefined\n}\n\n/**\n * Whether Figma lets this layer take a size of its own: a layer inside an instance shows its\n * component's size and cannot be resized, while an instance nested in another may be.\n */\nexport function takesOwnSize(graph: SceneGraph, node: SceneNode): boolean {\n return node.type === 'INSTANCE' || !node.parentId || !findInstanceAncestor(graph, node.parentId)\n}\n\n/**\n * True when a node field is protected from instance synchronization.\n */\nexport function hasInstanceOverride(graph: SceneGraph, nodeId: string, field: string): boolean {\n const instance = findInstanceAncestor(graph, nodeId)\n if (!instance) return false\n return hasNodeInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)\n}\n\n/**\n * The layer of the component an instance layer copies, which its overrides are measured\n * against: the instance's component for the instance itself.\n */\nfunction copiedLayer(graph: SceneGraph, instance: SceneNode, node: SceneNode) {\n const id =\n node.id === instance.id\n ? instance.componentId\n : copiedComponentLayerId(instance.instanceOverrides, instance.id, node)\n return id ? graph.nodes.get(id) : undefined\n}\n\n/**\n * The override fields an edit of these fields records. A mode edit claims only the collections\n * whose mode now differs from the component layer's, so the component's other modes still\n * reach the layer; with no layer to compare, it claims every mode.\n */\nfunction overrideFieldsOf(\n graph: SceneGraph,\n instance: SceneNode,\n nodeId: string,\n fields: string[]\n): string[] {\n if (!fields.includes('variableModes')) return fields\n const node = graph.nodes.get(nodeId)\n const source = node && copiedLayer(graph, instance, node)\n if (!node || !source) return fields\n return [\n ...fields.filter((field) => field !== 'variableModes'),\n ...differingVariableModeCollections(node, source).map(variableModeOverrideField)\n ]\n}\n\n/**\n * The instance above `instanceId` that records an assignment made through it: an assignment of a\n * nested instance's property is an edit of the instance it sits in, not of the nested instance.\n */\nexport function assignmentOverrideOwner(\n graph: SceneGraph,\n instanceId: string\n): SceneNode | undefined {\n const parentId = graph.nodes.get(instanceId)?.parentId\n return parentId ? findInstanceAncestor(graph, parentId) : undefined\n}\n\n/** The overrides an assignment edit writes on the instance above it, for undo to restore. */\nexport interface AssignmentOverrideState {\n ownerId: string\n overrides: InstanceOverrideState\n}\n\nexport function takeAssignmentOverrideState(\n graph: SceneGraph,\n instanceId: string\n): AssignmentOverrideState | undefined {\n const owner = assignmentOverrideOwner(graph, instanceId)\n return owner\n ? { ownerId: owner.id, overrides: cloneInstanceOverrideState(owner.instanceOverrides) }\n : undefined\n}\n\nexport function restoreAssignmentOverrideState(\n graph: SceneGraph,\n state: AssignmentOverrideState\n): void {\n graph.updateNode(state.ownerId, {\n instanceOverrides: cloneInstanceOverrideState(state.overrides)\n })\n}\n\n/**\n * Records that an instance assigned one of its component properties, as an edit of the instance\n * above it: the assignment is made through the outer instance, so a text override of the same\n * level does not outrank it. A top-level instance has no outer instance to record it on.\n */\nexport function recordAssignmentOverride(\n graph: SceneGraph,\n instanceId: string,\n propertyId: string,\n value: string\n): void {\n const outer = assignmentOverrideOwner(graph, instanceId)\n if (!outer) return\n setInstanceOverride(\n outer.instanceOverrides,\n outer.id,\n instanceId,\n assignmentOverrideField(propertyId),\n value\n )\n graph.updateNode(outer.id, { instanceOverrides: outer.instanceOverrides })\n}\n\n/**\n * The fields `changes` overrides on an instance layer. New strokes that change only what the\n * layer's line fields say override those fields, not the paints (`changesMoreThanStrokeLines`).\n */\nexport function instanceOverrideFields(node: SceneNode, changes: Partial<SceneNode>): string[] {\n const fields = Object.keys(changes)\n if (!changes.strokes || changesMoreThanStrokeLines(node, changes)) return fields\n return fields.filter((field) => field !== 'strokes')\n}\n\nexport function recordInstanceOverride(\n graph: SceneGraph,\n nodeId: string,\n fields: Iterable<string>\n): void {\n const instance = findInstanceAncestor(graph, nodeId)\n if (!instance) return\n\n const relevant = overrideFieldsOf(\n graph,\n instance,\n nodeId,\n [...fields].filter(\n (field) =>\n (INSTANCE_OVERRIDE_FIELDS as readonly string[]).includes(field) ||\n overriddenAssignmentId(field) !== null\n )\n )\n\n const added = relevant.filter(\n (field) => !hasNodeInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)\n )\n if (added.length === 0) return\n\n // A new state rather than an edit of the old one, so a preview that captured the old state\n // puts it back on cancel.\n const overrides = cloneInstanceOverrideState(instance.instanceOverrides)\n for (const field of added) setInstanceOverride(overrides, instance.id, nodeId, field)\n graph.updateNode(instance.id, { instanceOverrides: overrides })\n}\n\n/** Every layer at or below `rootId`. */\nfunction subtreeIds(graph: SceneGraph, rootId: string): string[] {\n const ids: string[] = []\n const visit = (id: string) => {\n ids.push(id)\n for (const childId of graph.nodes.get(id)?.childIds ?? []) visit(childId)\n }\n visit(rootId)\n return ids\n}\n\n/** Forget what the instances above `nodeId` recorded for it and the layers inside it. */\nfunction forgetOverridesOf(graph: SceneGraph, nodeId: string): void {\n const ids = subtreeIds(graph, nodeId)\n const parentId = graph.nodes.get(nodeId)?.parentId\n if (!parentId) return\n graph.closest(parentId, (ancestor) => {\n if (ancestor.type !== 'INSTANCE') return false\n const { descendants } = ancestor.instanceOverrides\n if (ids.some((id) => descendants.delete(id)))\n graph.updateNode(ancestor.id, { instanceOverrides: ancestor.instanceOverrides })\n return false\n })\n}\n\n/** Whether a layer can be replaced in its instance: it sits in the part the component owns. */\nexport function canReplaceInstanceLayer(graph: SceneGraph, nodeId: string): boolean {\n const node = graph.nodes.get(nodeId)\n const owner = node && owningInstance(graph, node)\n if (!node?.parentId || !owner) return false\n // Slot content is the instance's own already, and a generated frame's layers are fixed.\n const scope = slotScope(graph, node.parentId)\n if (scope.kind !== 'locked' || scope.owner.type !== 'INSTANCE') return false\n return (\n replacedLayerIn(owner, node.id) !== undefined ||\n copiedComponentLayerId(owner.instanceOverrides, owner.id, node) !== undefined\n )\n}\n\n/**\n * Put `replacementId` in place of `targetId`, a layer an instance copies from its component, as\n * an override of the nearest instance above it, as pen.dev replaces a layer inside an instance.\n * The replacement takes the target's place among its siblings and its position, the target\n * goes, and syncs keep the replacement in place of the component layer the target copied. A\n * replaced layer can be replaced again. Returns false and changes nothing when the target is no\n * such layer, or the replacement cannot go there.\n */\nexport function replaceInstanceLayer(\n graph: SceneGraph,\n targetId: string,\n replacementId: string\n): boolean {\n const target = graph.nodes.get(targetId)\n const replacement = graph.nodes.get(replacementId)\n const parentId = target?.parentId\n if (!target || !replacement || !parentId || targetId === replacementId) return false\n const owner = owningInstance(graph, target)\n if (!owner || graph.isDescendant(parentId, replacementId)) return false\n if (createsComponentCycle(graph, replacementId, parentId)) return false\n const layerId =\n replacedLayerIn(owner, target.id) ??\n copiedComponentLayerId(owner.instanceOverrides, owner.id, target)\n if (!layerId) return false\n\n // The replacement copies no layer of the component, so its own layers lose such links; an\n // instance among them keeps its own component and layers.\n const unlink = (id: string) => {\n const node = graph.nodes.get(id)\n if (!node) return\n if (node.type !== 'INSTANCE' && node.componentId) graph.updateNode(id, { componentId: null })\n if (node.type !== 'INSTANCE') node.childIds.forEach(unlink)\n }\n unlink(replacementId)\n\n const index = graph.nodes.get(parentId)?.childIds.indexOf(target.id) ?? -1\n forgetOverridesOf(graph, target.id)\n forgetOverridesOf(graph, replacementId)\n graph.insertChildAt(replacementId, parentId, index < 0 ? Number.MAX_SAFE_INTEGER : index)\n graph.updateNode(replacementId, {\n x: target.x,\n y: target.y,\n layoutPositioning: target.layoutPositioning,\n horizontalConstraint: target.horizontalConstraint,\n verticalConstraint: target.verticalConstraint\n })\n graph.deleteNode(target.id)\n setInstanceOverride(\n owner.instanceOverrides,\n owner.id,\n replacementId,\n REPLACED_LAYER_OVERRIDE,\n layerId\n )\n graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides })\n return true\n}\n\n/**\n * Take a replaced layer out and bring back the component layer it stood in for, synced from the\n * outermost instance as a reset syncs. Returns false when the layer is not a replaced one.\n */\nexport function restoreReplacedLayer(graph: SceneGraph, nodeId: string): boolean {\n const node = graph.nodes.get(nodeId)\n const owner = node && owningInstance(graph, node)\n if (!node || !owner || replacedLayerIn(owner, nodeId) === undefined) return false\n let outermost = owner\n for (let above = owningInstance(graph, owner); above; above = owningInstance(graph, above))\n outermost = above\n forgetOverridesOf(graph, nodeId)\n graph.deleteNode(nodeId)\n syncInstance(graph, outermost.id)\n // An enclosing sync stops at a swapped instance, which brings its layers back itself.\n const above = owningInstance(graph, owner)\n if (above && getInstanceOverride(above.instanceOverrides, above.id, owner.id, 'componentId'))\n syncInstance(graph, owner.id)\n return true\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgEA,SAAgB,2BAA2B,WAA0C;CACnF,MAAM,QAA4B,CAAC;CAEnC,KAAK,MAAM,OAAO,CAAC,GAAG,qBAAqB,GAAG,8BAA8B,GAC1E,SAAS,OAAO,WAAW,GAAG;CAChC,OAAO;AACT;;;;;AAMA,SAAS,sBAAsB,OAAmB,WAA8B;CAC9E,MAAM,SAAS,UAAU,WAAW,MAAM,MAAM,IAAI,UAAU,QAAQ,IAAI,KAAA;CAC1E,OAAO,QAAQ,SAAS,kBAA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SAAS,oBAAoB,MAAM,mBAAmB,MAAM,IAAI,MAAM,IAAI,aAAa,GACzF,aAAa,OAAO,MAAM,EAAE;CAC9B,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["hasNodeInstanceOverride"],"sources":["../../src/instances/index.ts"],"sourcesContent":["import type { NodeCloneMode } from '../copy'\nimport type { SceneGraph } from '../graph'\nimport { shapeGeometryChanges } from '../resize'\nimport { slotScope } from '../slots/content'\nimport { detachOwnedSlotContent, restoreOwnedSlotContent } from '../slots/frames'\nimport { changesMoreThanStrokeLines } from '../strokes'\nimport type { SceneNode } from '../types'\nimport { applyBoundPaintColorsIn, keepCopyBoundPaints } from '../variables/paints'\nimport { keepOwnContentSize } from './content-size'\nimport { createInstanceSyncContext, groupCopyRemovals, removeLeftoverCopies } from './copies'\nimport { canCreateInstance, createsComponentCycle } from './cycles'\nimport {\n INSTANCE_FRAME_FOLLOWED_FIELDS,\n INSTANCE_OVERRIDE_FIELDS,\n INSTANCE_SYNC_PROPS\n} from './fields'\nimport { differingVariableModeCollections } from './modes'\nimport {\n assignmentOverrideField,\n cloneInstanceOverrideState,\n copiedComponentLayerId,\n createInstanceOverrideState,\n getInstanceOverride,\n hasInstanceOverride as hasNodeInstanceOverride,\n type InstanceOverrideState,\n overriddenAssignmentId,\n ownInstanceOverrides,\n REPLACED_LAYER_OVERRIDE,\n setInstanceOverride,\n variableModeOverrideField\n} from './overrides'\nimport { owningInstance, replacedLayerIn } from './replacements'\nimport { walkInstanceSources } from './source-walk'\nimport { captureInstanceOverrides, restoreInstanceOverrides } from './swap-overrides'\nimport {\n applySyncedStrokeLines,\n bindingProtection,\n cloneChildrenWithMapping,\n copyProp,\n enclosingInstanceOverrideFields,\n isProtectedSyncField,\n sourceInTargetCoordinates,\n syncBindingFields,\n syncChildren,\n syncVariableModeFields,\n updateSyncedProps\n} from './sync'\n\nexport { canCreateInstance, createsComponentCycle, cycleSafeParent } from './cycles'\nexport { walkInstanceSources } from './source-walk'\nexport { instanceMainComponent } from './main-component'\nexport {\n isInShownReplacedLayer,\n isReplacedLayer,\n owningInstance,\n replacedComponentLayerId,\n showsReplacedLayer\n} from './replacements'\nexport {\n INSTANCE_FOLLOWED_FIELDS,\n INSTANCE_OVERRIDE_FIELDS,\n INSTANCE_SYNC_FIELDS,\n INSTANCE_SYNC_PROPS,\n INSTANCE_SYNC_TEXT_PROPS\n} from './fields'\n\nexport function copyInstanceComponentProps(component: SceneNode): Partial<SceneNode> {\n const props: Partial<SceneNode> = {}\n // A new instance starts with the fields its component frame lends it, as resyncing one does.\n for (const key of [...INSTANCE_SYNC_PROPS, ...INSTANCE_FRAME_FOLLOWED_FIELDS])\n copyProp(props, component, key)\n return props\n}\n\n/**\n * The name Figma gives a new instance of `component`: its component set's name for a variant,\n * whose own name only says which variant it is, and the component's own name otherwise.\n */\nfunction instanceComponentName(graph: SceneGraph, component: SceneNode): string {\n const parent = component.parentId ? graph.nodes.get(component.parentId) : undefined\n return parent?.type === 'COMPONENT_SET' ? parent.name : component.name\n}\n\nexport function createInstance(\n graph: SceneGraph,\n componentId: string,\n parentId: string,\n overrides: Partial<SceneNode> = {}\n): SceneNode | null {\n const component = graph.nodes.get(componentId)\n if (component?.type !== 'COMPONENT' || !canCreateInstance(graph, componentId, parentId))\n return null\n\n const props: Partial<SceneNode> = {\n ...copyInstanceComponentProps(component),\n name: instanceComponentName(graph, component)\n }\n\n // The component checked above is the one the instance shows, whatever `overrides` holds.\n const instance = graph.createNode('INSTANCE', parentId, { ...props, ...overrides, componentId })\n\n cloneChildrenWithMapping(graph, component.id, instance.id)\n // A copy shows its bound paints in its own context, not as its component's paints hold them.\n applyBoundPaintColorsIn(graph, instance.id)\n\n return instance\n}\n\nexport function populateInstanceChildren(\n graph: SceneGraph,\n instanceId: string,\n componentId: string,\n mode: NodeCloneMode = 'deep'\n): void {\n const instance = graph.nodes.get(instanceId)\n const component = graph.nodes.get(componentId)\n if (!instance || !component || instance.type !== 'INSTANCE') return\n cloneChildrenWithMapping(graph, componentId, instanceId, mode)\n}\n\n/**\n * A nested instance's link to the enclosing component's record is its `componentId` when it\n * was populated by cloning. A swap replaces that field, so keep the correspondence as the\n * owner's `sourceComponentId` override and record the swap itself; materialized documents\n * already carry the correspondence and only gain the swap.\n */\nfunction recordNestedSwap(graph: SceneGraph, instance: SceneNode, componentId: string): void {\n const owner = instance.parentId ? findInstanceAncestor(graph, instance.parentId) : undefined\n if (!owner) return\n const existing = getInstanceOverride(\n owner.instanceOverrides,\n owner.id,\n instance.id,\n 'sourceComponentId'\n )\n if (typeof existing !== 'string' && instance.componentId)\n setInstanceOverride(\n ownInstanceOverrides(owner),\n owner.id,\n instance.id,\n 'sourceComponentId',\n instance.componentId\n )\n setInstanceOverride(\n ownInstanceOverrides(owner),\n owner.id,\n instance.id,\n 'componentId',\n componentId\n )\n graph.updateNode(owner.id, { instanceOverrides: ownInstanceOverrides(owner) })\n}\n\nexport interface SwapInstanceOptions {\n /**\n * Keep the instance's name even when it is its old component's. A swap otherwise renames such\n * an instance after the new component, as Figma does; a view that only shows another variant,\n * such as preview, keeps names so layer paths stay the same.\n */\n keepName?: boolean\n /**\n * Keep the overrides the instance's layers record, matched to the layers of the new component\n * that take their places, as Figma keeps them when a variant changes. A swap that only\n * materializes a layer the caller re-applies itself, such as a pen icon's glyph, skips this:\n * what the placeholder recorded is scaffolding, not a user's edit.\n */\n restoreOverrides?: boolean\n}\n\nexport function swapInstanceComponent(\n graph: SceneGraph,\n instanceId: string,\n componentId: string,\n { keepName = false, restoreOverrides = true }: SwapInstanceOptions = {}\n): void {\n const instance = graph.nodes.get(instanceId)\n const component = graph.nodes.get(componentId)\n if (!instance || component?.type !== 'COMPONENT' || instance.type !== 'INSTANCE') return\n if (instance.parentId && !canCreateInstance(graph, componentId, instance.parentId)) return\n\n const previousComponent = instance.componentId ? graph.nodes.get(instance.componentId) : undefined\n recordNestedSwap(graph, instance, componentId)\n const updates: Partial<SceneNode> = { componentId }\n const source = sourceInTargetCoordinates(component, instance.componentScale)\n const overridden = (field: string) =>\n hasNodeInstanceOverride(instance.instanceOverrides, instance.id, instance.id, field)\n for (const key of INSTANCE_SYNC_PROPS) {\n if (key === 'variableModes' || overridden(key)) continue\n copyProp(updates, source, key)\n }\n syncVariableModeFields(instance, source, updates, overridden)\n applySyncedStrokeLines(graph, instance, updates, overridden)\n\n if (\n !keepName &&\n (!previousComponent || instance.name === instanceComponentName(graph, previousComponent))\n )\n updates.name = instanceComponentName(graph, component)\n\n keepCopyBoundPaints(graph, instance, updates)\n const childIds = Array.from(instance.childIds)\n const slotContent = detachOwnedSlotContent(graph, instance)\n swapInstanceLayers(graph, instanceId, componentId, updates, childIds, restoreOverrides)\n restoreOwnedSlotContent(graph, instance, slotContent)\n}\n\n/**\n * Replaces the instance's layers with clones of its new component's and gives the recorded\n * overrides back to the layers that take the old ones' places, matched by name path.\n */\nfunction swapInstanceLayers(\n graph: SceneGraph,\n instanceId: string,\n componentId: string,\n updates: Partial<SceneNode>,\n childIds: string[],\n restoreOverrides: boolean\n): void {\n // The clones take new IDs, so what was recorded for the removed layers only applies again once\n // it is matched to the layers of the new component that take their places.\n const capturedOverrides = restoreOverrides\n ? captureInstanceOverrides(graph, graph.nodes.get(instanceId) as SceneNode)\n : undefined\n for (const childId of childIds) {\n forgetOverridesOf(graph, childId)\n graph.deleteNode(childId)\n }\n graph.updateNode(instanceId, updates)\n cloneChildrenWithMapping(graph, componentId, instanceId)\n applyBoundPaintColorsIn(graph, instanceId)\n const swapped = graph.nodes.get(instanceId)\n if (swapped && capturedOverrides) restoreInstanceOverrides(graph, swapped, capturedOverrides)\n}\n\nconst syncingComponentsByGraph = new WeakMap<SceneGraph, Set<string>>()\n\nexport function syncInstances(graph: SceneGraph, componentId: string): void {\n syncInstancesOf(graph, componentId, getInstances(graph, componentId))\n}\n\n/**\n * Syncs each component's instances, in order, as one edit: the copies they remove stay\n * restorable together for as long as undo keeps that edit.\n */\nexport function syncInstancesTogether(graph: SceneGraph, componentIds: Iterable<string>): void {\n groupCopyRemovals(graph, () => {\n for (const id of componentIds) syncInstances(graph, id)\n })\n}\n\n/** Syncs one instance from its component, as `syncInstances` does for every instance. */\nexport function syncInstance(graph: SceneGraph, instanceId: string): void {\n const instance = graph.nodes.get(instanceId)\n if (instance?.type !== 'INSTANCE' || !instance.componentId) return\n syncInstancesOf(graph, instance.componentId, [instance])\n}\n\nfunction syncInstancesOf(\n graph: SceneGraph,\n componentId: string,\n instances: Iterable<SceneNode>\n): void {\n const component = graph.nodes.get(componentId)\n if (component?.type !== 'COMPONENT') return\n let syncing = syncingComponentsByGraph.get(graph)\n if (!syncing) {\n syncing = new Set()\n syncingComponentsByGraph.set(graph, syncing)\n }\n if (syncing.has(componentId)) return\n syncing.add(componentId)\n try {\n groupCopyRemovals(graph, (removals) => {\n for (const instance of instances) {\n const enclosing = enclosingInstanceOverrideFields(graph, instance)\n enclosing.push(new Set(instance.instanceOverrides.self.keys()))\n const protectedField = bindingProtection(enclosing)\n const source = sourceInTargetCoordinates(component, instance.componentScale)\n const updates: Partial<SceneNode> = {}\n syncBindingFields(instance, source, updates, protectedField)\n syncVariableModeFields(instance, source, updates, protectedField)\n for (const key of INSTANCE_SYNC_PROPS) {\n if (key === 'boundVariables' || key === 'variableModes') continue\n if (isProtectedSyncField(instance, key, protectedField)) continue\n copyProp(updates, source, key)\n }\n // The file keeps one value for the instance frame and its component, so the frame takes\n // those the layers inside an instance may not set.\n for (const key of INSTANCE_FRAME_FOLLOWED_FIELDS) {\n if (!isProtectedSyncField(instance, key, protectedField)) copyProp(updates, source, key)\n }\n // An instance that hugs its layers sizes to what it shows, not to the component.\n keepOwnContentSize(graph, updates, instance, source)\n // A size that follows the component invalidates outlines the file saved on the instance;\n // its live box draws them again.\n if (updates.width !== undefined || updates.height !== undefined) {\n Object.assign(\n updates,\n shapeGeometryChanges(\n instance,\n updates.width ?? instance.width,\n updates.height ?? instance.height\n )\n )\n }\n updateSyncedProps(graph, instance, updates, (key) =>\n isProtectedSyncField(instance, key, protectedField)\n )\n const owned = ownInstanceOverrides(instance)\n const context = createInstanceSyncContext(instance.id, owned)\n syncChildren(graph, component.id, instance.id, owned, context)\n removeLeftoverCopies(graph, context, removals)\n }\n })\n } finally {\n syncing.delete(componentId)\n }\n}\n\n/**\n * Renames the layers that the copied instances among `copies` record overrides for to their\n * copies, as a copied instance records its own layers' overrides. The values keep naming what\n * they name, since a copy shows the same components as its source.\n */\nexport function retargetCopiedOverrides(\n graph: SceneGraph,\n copies: ReadonlyMap<string, string>\n): void {\n for (const id of copies.values()) {\n const node = graph.nodes.get(id)\n if (node?.type !== 'INSTANCE' || node.instanceOverrides.descendants.size === 0) continue\n const descendants = new Map(\n [...node.instanceOverrides.descendants].map(([target, fields]) => [\n copies.get(target) ?? target,\n fields\n ])\n )\n graph.updateNode(id, { instanceOverrides: { ...node.instanceOverrides, descendants } })\n }\n}\n\nexport function detachInstance(graph: SceneGraph, instanceId: string): void {\n const node = graph.nodes.get(instanceId)\n if (node?.type !== 'INSTANCE') return\n for (const nested of outermostNestedInstances(graph, node))\n adoptNestedOverrides(graph, node, nested)\n // Through `updateNode`, so the instance index, change observers, and undo recorders see it.\n graph.updateNode(instanceId, {\n type: 'FRAME',\n componentId: null,\n instanceOverrides: createInstanceOverrideState()\n })\n // Its mirrored layers stand on their own: a component child id would name a layer of another\n // node, which the format never stores and a later sync would read as a link back. A nested\n // instance is not a mirror and keeps its own links, which its overrides are written through.\n const detachLinks = (parentId: string): void => {\n for (const child of graph.getChildren(parentId)) {\n if (child.type === 'INSTANCE') continue\n if (child.componentId) graph.updateNode(child.id, { componentId: null })\n detachLinks(child.id)\n }\n }\n detachLinks(instanceId)\n}\n\n// A swap's bookkeeping belongs to the instance enclosing the swapped one, never to the swapped one.\nconst OWNER_ONLY_FIELDS = new Set(['componentId', 'sourceComponentId'])\n\nfunction outermostNestedInstances(graph: SceneGraph, instance: SceneNode): SceneNode[] {\n return graph\n .getChildren(instance.id)\n .flatMap((child) =>\n child.type === 'INSTANCE' ? [child] : outermostNestedInstances(graph, child)\n )\n}\n\n/**\n * An instance a detached one holds stands on its own once that one is a frame, and so must what\n * makes it differ from its component. Cloned in, it kept the overrides of the instance it copies,\n * under that instance's layers; those, and the ones the detached instance recorded on its layers,\n * now go under its own.\n */\nfunction adoptNestedOverrides(graph: SceneGraph, detached: SceneNode, nested: SceneNode): void {\n const ownLayer = new Map<string, string>()\n walkInstanceSources(graph, nested, (source, target) => {\n ownLayer.set(source.id, target.id)\n return true\n })\n const { self, descendants: kept } = cloneInstanceOverrideState(nested.instanceOverrides)\n const outer = cloneInstanceOverrideState(detached.instanceOverrides).descendants\n const descendants = new Map<string, Map<string, unknown>>()\n const claim = (layerId: string, fields: Map<string, unknown>): void => {\n const merged = descendants.get(layerId)\n if (!merged) descendants.set(layerId, fields)\n else for (const [field, value] of fields) merged.set(field, value)\n }\n // What was recorded on its own layers is more recent than what it copied, so it is laid on top.\n for (const [layerId, fields] of kept)\n if (ownLayer.has(layerId)) claim(ownLayer.get(layerId) ?? layerId, fields)\n for (const [layerId, fields] of kept) if (!ownLayer.has(layerId)) claim(layerId, fields)\n for (const [layerId, fields] of outer) {\n if (layerId === nested.id) {\n for (const [field, value] of fields) if (!OWNER_ONLY_FIELDS.has(field)) self.set(field, value)\n } else if (graph.isDescendant(layerId, nested.id)) claim(layerId, fields)\n }\n graph.updateNode(nested.id, { instanceOverrides: { self, descendants } })\n}\n\nexport function getMainComponent(graph: SceneGraph, instanceId: string): SceneNode | undefined {\n const node = graph.nodes.get(instanceId)\n if (!node?.componentId) return undefined\n return graph.nodes.get(node.componentId)\n}\n\nexport function getInstances(graph: SceneGraph, componentId: string): SceneNode[] {\n const ids = graph.instanceIndex.get(componentId)\n if (!ids) return []\n const instances: SceneNode[] = []\n for (const id of ids) {\n const node = graph.nodes.get(id)\n if (node) instances.push(node)\n }\n return instances\n}\n\n/** Nearest INSTANCE at or above `nodeId` — self, parent, grandparent, etc. */\nexport function findInstanceAncestor(graph: SceneGraph, nodeId: string): SceneNode | undefined {\n let current = graph.nodes.get(nodeId)\n while (current) {\n if (current.type === 'INSTANCE') return current\n current = current.parentId ? graph.nodes.get(current.parentId) : undefined\n }\n return undefined\n}\n\n/**\n * Whether Figma lets this layer take a size of its own: a layer inside an instance shows its\n * component's size and cannot be resized, while an instance nested in another may be.\n */\nexport function takesOwnSize(graph: SceneGraph, node: SceneNode): boolean {\n return node.type === 'INSTANCE' || !node.parentId || !findInstanceAncestor(graph, node.parentId)\n}\n\n/**\n * True when a node field is protected from instance synchronization.\n */\nexport function hasInstanceOverride(graph: SceneGraph, nodeId: string, field: string): boolean {\n const instance = findInstanceAncestor(graph, nodeId)\n if (!instance) return false\n return hasNodeInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)\n}\n\n/**\n * The layer of the component an instance layer copies, which its overrides are measured\n * against: the instance's component for the instance itself.\n */\nfunction copiedLayer(graph: SceneGraph, instance: SceneNode, node: SceneNode) {\n const id =\n node.id === instance.id\n ? instance.componentId\n : copiedComponentLayerId(instance.instanceOverrides, instance.id, node)\n return id ? graph.nodes.get(id) : undefined\n}\n\n/**\n * The override fields an edit of these fields records. A mode edit claims only the collections\n * whose mode now differs from the component layer's, so the component's other modes still\n * reach the layer; with no layer to compare, it claims every mode.\n */\nfunction overrideFieldsOf(\n graph: SceneGraph,\n instance: SceneNode,\n nodeId: string,\n fields: string[]\n): string[] {\n if (!fields.includes('variableModes')) return fields\n const node = graph.nodes.get(nodeId)\n const source = node && copiedLayer(graph, instance, node)\n if (!node || !source) return fields\n return [\n ...fields.filter((field) => field !== 'variableModes'),\n ...differingVariableModeCollections(node, source).map(variableModeOverrideField)\n ]\n}\n\n/**\n * The instance above `instanceId` that records an assignment made through it: an assignment of a\n * nested instance's property is an edit of the instance it sits in, not of the nested instance.\n */\nexport function assignmentOverrideOwner(\n graph: SceneGraph,\n instanceId: string\n): SceneNode | undefined {\n const parentId = graph.nodes.get(instanceId)?.parentId\n return parentId ? findInstanceAncestor(graph, parentId) : undefined\n}\n\n/** The overrides an assignment edit writes on the instance above it, for undo to restore. */\nexport interface AssignmentOverrideState {\n ownerId: string\n overrides: InstanceOverrideState\n}\n\nexport function takeAssignmentOverrideState(\n graph: SceneGraph,\n instanceId: string\n): AssignmentOverrideState | undefined {\n const owner = assignmentOverrideOwner(graph, instanceId)\n return owner\n ? { ownerId: owner.id, overrides: cloneInstanceOverrideState(owner.instanceOverrides) }\n : undefined\n}\n\nexport function restoreAssignmentOverrideState(\n graph: SceneGraph,\n state: AssignmentOverrideState\n): void {\n graph.updateNode(state.ownerId, {\n instanceOverrides: cloneInstanceOverrideState(state.overrides)\n })\n}\n\n/**\n * Records that an instance assigned one of its component properties, as an edit of the instance\n * above it: the assignment is made through the outer instance, so a text override of the same\n * level does not outrank it. A top-level instance has no outer instance to record it on.\n */\nexport function recordAssignmentOverride(\n graph: SceneGraph,\n instanceId: string,\n propertyId: string,\n value: string\n): void {\n const outer = assignmentOverrideOwner(graph, instanceId)\n if (!outer) return\n setInstanceOverride(\n ownInstanceOverrides(outer),\n outer.id,\n instanceId,\n assignmentOverrideField(propertyId),\n value\n )\n graph.updateNode(outer.id, { instanceOverrides: outer.instanceOverrides })\n}\n\n/**\n * The fields `changes` overrides on an instance layer. New strokes that change only what the\n * layer's line fields say override those fields, not the paints (`changesMoreThanStrokeLines`).\n */\nexport function instanceOverrideFields(node: SceneNode, changes: Partial<SceneNode>): string[] {\n const fields = Object.keys(changes)\n if (!changes.strokes || changesMoreThanStrokeLines(node, changes)) return fields\n return fields.filter((field) => field !== 'strokes')\n}\n\nexport function recordInstanceOverride(\n graph: SceneGraph,\n nodeId: string,\n fields: Iterable<string>\n): void {\n const instance = findInstanceAncestor(graph, nodeId)\n if (!instance) return\n\n const relevant = overrideFieldsOf(\n graph,\n instance,\n nodeId,\n [...fields].filter(\n (field) =>\n (INSTANCE_OVERRIDE_FIELDS as readonly string[]).includes(field) ||\n overriddenAssignmentId(field) !== null\n )\n )\n\n const added = relevant.filter(\n (field) => !hasNodeInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)\n )\n if (added.length === 0) return\n\n // A new state rather than an edit of the old one, so a preview that captured the old state\n // puts it back on cancel.\n const overrides = cloneInstanceOverrideState(instance.instanceOverrides)\n for (const field of added) setInstanceOverride(overrides, instance.id, nodeId, field)\n graph.updateNode(instance.id, { instanceOverrides: overrides })\n}\n\n/** Every layer at or below `rootId`. */\nfunction subtreeIds(graph: SceneGraph, rootId: string): string[] {\n const ids: string[] = []\n const visit = (id: string) => {\n ids.push(id)\n for (const childId of graph.nodes.get(id)?.childIds ?? []) visit(childId)\n }\n visit(rootId)\n return ids\n}\n\n/** Forget what the instances above `nodeId` recorded for it and the layers inside it. */\nfunction forgetOverridesOf(graph: SceneGraph, nodeId: string): void {\n const ids = subtreeIds(graph, nodeId)\n const parentId = graph.nodes.get(nodeId)?.parentId\n if (!parentId) return\n graph.closest(parentId, (ancestor) => {\n if (ancestor.type !== 'INSTANCE') return false\n const owned = ownInstanceOverrides(ancestor)\n if (ids.some((id) => owned.descendants.delete(id)))\n graph.updateNode(ancestor.id, { instanceOverrides: owned })\n return false\n })\n}\n\n/** Whether a layer can be replaced in its instance: it sits in the part the component owns. */\nexport function canReplaceInstanceLayer(graph: SceneGraph, nodeId: string): boolean {\n const node = graph.nodes.get(nodeId)\n const owner = node && owningInstance(graph, node)\n if (!node?.parentId || !owner) return false\n // Slot content is the instance's own already, and a generated frame's layers are fixed.\n const scope = slotScope(graph, node.parentId)\n if (scope.kind !== 'locked' || scope.owner.type !== 'INSTANCE') return false\n return (\n replacedLayerIn(owner, node.id) !== undefined ||\n copiedComponentLayerId(owner.instanceOverrides, owner.id, node) !== undefined\n )\n}\n\n/**\n * Put `replacementId` in place of `targetId`, a layer an instance copies from its component, as\n * an override of the nearest instance above it, as pen.dev replaces a layer inside an instance.\n * The replacement takes the target's place among its siblings and its position, the target\n * goes, and syncs keep the replacement in place of the component layer the target copied. A\n * replaced layer can be replaced again. Returns false and changes nothing when the target is no\n * such layer, or the replacement cannot go there.\n */\nexport function replaceInstanceLayer(\n graph: SceneGraph,\n targetId: string,\n replacementId: string\n): boolean {\n const target = graph.nodes.get(targetId)\n const replacement = graph.nodes.get(replacementId)\n const parentId = target?.parentId\n if (!target || !replacement || !parentId || targetId === replacementId) return false\n const owner = owningInstance(graph, target)\n if (!owner || graph.isDescendant(parentId, replacementId)) return false\n if (createsComponentCycle(graph, replacementId, parentId)) return false\n const layerId =\n replacedLayerIn(owner, target.id) ??\n copiedComponentLayerId(owner.instanceOverrides, owner.id, target)\n if (!layerId) return false\n\n // The replacement copies no layer of the component, so its own layers lose such links; an\n // instance among them keeps its own component and layers.\n const unlink = (id: string) => {\n const node = graph.nodes.get(id)\n if (!node) return\n if (node.type !== 'INSTANCE' && node.componentId) graph.updateNode(id, { componentId: null })\n if (node.type !== 'INSTANCE') node.childIds.forEach(unlink)\n }\n unlink(replacementId)\n\n const index = graph.nodes.get(parentId)?.childIds.indexOf(target.id) ?? -1\n forgetOverridesOf(graph, target.id)\n forgetOverridesOf(graph, replacementId)\n graph.insertChildAt(replacementId, parentId, index < 0 ? Number.MAX_SAFE_INTEGER : index)\n graph.updateNode(replacementId, {\n x: target.x,\n y: target.y,\n layoutPositioning: target.layoutPositioning,\n horizontalConstraint: target.horizontalConstraint,\n verticalConstraint: target.verticalConstraint\n })\n graph.deleteNode(target.id)\n setInstanceOverride(\n ownInstanceOverrides(owner),\n owner.id,\n replacementId,\n REPLACED_LAYER_OVERRIDE,\n layerId\n )\n graph.updateNode(owner.id, { instanceOverrides: ownInstanceOverrides(owner) })\n return true\n}\n\n/**\n * Take a replaced layer out and bring back the component layer it stood in for, synced from the\n * outermost instance as a reset syncs. Returns false when the layer is not a replaced one.\n */\nexport function restoreReplacedLayer(graph: SceneGraph, nodeId: string): boolean {\n const node = graph.nodes.get(nodeId)\n const owner = node && owningInstance(graph, node)\n if (!node || !owner || replacedLayerIn(owner, nodeId) === undefined) return false\n let outermost = owner\n for (let above = owningInstance(graph, owner); above; above = owningInstance(graph, above))\n outermost = above\n forgetOverridesOf(graph, nodeId)\n graph.deleteNode(nodeId)\n syncInstance(graph, outermost.id)\n // An enclosing sync stops at a swapped instance, which brings its layers back itself.\n const above = owningInstance(graph, owner)\n if (above && getInstanceOverride(above.instanceOverrides, above.id, owner.id, 'componentId'))\n syncInstance(graph, owner.id)\n return true\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAkEA,SAAgB,2BAA2B,WAA0C;CACnF,MAAM,QAA4B,CAAC;CAEnC,KAAK,MAAM,OAAO,CAAC,GAAG,qBAAqB,GAAG,8BAA8B,GAC1E,SAAS,OAAO,WAAW,GAAG;CAChC,OAAO;AACT;;;;;AAMA,SAAS,sBAAsB,OAAmB,WAA8B;CAC9E,MAAM,SAAS,UAAU,WAAW,MAAM,MAAM,IAAI,UAAU,QAAQ,IAAI,KAAA;CAC1E,OAAO,QAAQ,SAAS,kBAAkB,OAAO,OAAO,UAAU;AACpE;AAEA,SAAgB,eACd,OACA,aACA,UACA,YAAgC,CAAC,GACf;CAClB,MAAM,YAAY,MAAM,MAAM,IAAI,WAAW;CAC7C,IAAI,WAAW,SAAS,eAAe,CAAC,kBAAkB,OAAO,aAAa,QAAQ,GACpF,OAAO;CAET,MAAM,QAA4B;EAChC,GAAG,2BAA2B,SAAS;EACvC,MAAM,sBAAsB,OAAO,SAAS;CAC9C;CAGA,MAAM,WAAW,MAAM,WAAW,YAAY,UAAU;EAAE,GAAG;EAAO,GAAG;EAAW;CAAY,CAAC;CAE/F,yBAAyB,OAAO,UAAU,IAAI,SAAS,EAAE;CAEzD,wBAAwB,OAAO,SAAS,EAAE;CAE1C,OAAO;AACT;AAEA,SAAgB,yBACd,OACA,YACA,aACA,OAAsB,QAChB;CACN,MAAM,WAAW,MAAM,MAAM,IAAI,UAAU;CAC3C,MAAM,YAAY,MAAM,MAAM,IAAI,WAAW;CAC7C,IAAI,CAAC,YAAY,CAAC,aAAa,SAAS,SAAS,YAAY;CAC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AC7B,CAAC;CACD,MAAM,WAAW,OAAO,EAAE;CAC1B,oBACE,qBAAqB,KAAK,GAC1B,MAAM,IACN,eACA,yBACA,OACF;CACA,MAAM,WAAW,MAAM,IAAI,EAAE,mBAAmB,qBAAqB,KAAK,EAAE,CAAC;CAC7E,OAAO;AACT;;;;;AAMA,SAAgB,qBAAqB,OAAmB,QAAyB;CAC/E,MAAM,OAAO,MAAM,MAAM,IAAI,MAAM;CACnC,MAAM,QAAQ,QAAQ,eAAe,OAAO,IAAI;CAChD,IAAI,CAAC,QAAQ,CAAC,SAAS,gBAAgB,OAAO,MAAM,MAAM,KAAA,GAAW,OAAO;CAC5E,IAAI,YAAY;CAChB,KAAK,IAAI,QAAQ,eAAe,OAAO,KAAK,GAAG,OAAO,QAAQ,eAAe,OAAO,KAAK,GACvF,YAAY;CACd,kBAAkB,OAAO,MAAM;CAC/B,MAAM,WAAW,MAAM;CACvB,aAAa,OAAO,UAAU,EAAE;CAEhC,MAAM,QAAQ,eAAe,OAAO,KAAK;CACzC,IAAI,SAAS,oBAAoB,MAAM,mBAAmB,MAAM,IAAI,MAAM,IAAI,aAAa,GACzF,aAAa,OAAO,MAAM,EAAE;CAC9B,OAAO;AACT"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { SceneNode } from "../types.js";
|
|
1
2
|
//#region src/instances/overrides.d.ts
|
|
2
3
|
type InstanceOverrideField = string;
|
|
3
4
|
interface InstanceOverrideState {
|
|
@@ -34,6 +35,19 @@ declare const REPLACED_LAYER_OVERRIDE = "replacedLayer";
|
|
|
34
35
|
/** Override fields whose value names another layer of the document. */
|
|
35
36
|
declare function isLayerReferenceOverride(field: InstanceOverrideField): boolean;
|
|
36
37
|
declare function createInstanceOverrideState(): InstanceOverrideState;
|
|
38
|
+
/**
|
|
39
|
+
* What a layer holds until it records an override of its own. Shared and frozen, so an empty state
|
|
40
|
+
* costs nothing per layer and a write that skipped `ownInstanceOverrides` throws where it happens
|
|
41
|
+
* instead of reaching every layer of every document.
|
|
42
|
+
*/
|
|
43
|
+
declare const EMPTY_INSTANCE_OVERRIDES: InstanceOverrideState;
|
|
44
|
+
declare function isEmptyInstanceOverrideState(state: InstanceOverrideState): boolean;
|
|
45
|
+
/**
|
|
46
|
+
* The layer's own override state, giving it a fresh one when it still holds the shared empty
|
|
47
|
+
* state. Writers record through this and then persist it with `updateNode`, so the change reaches
|
|
48
|
+
* events and undo instead of only the layer.
|
|
49
|
+
*/
|
|
50
|
+
declare function ownInstanceOverrides(node: SceneNode): InstanceOverrideState;
|
|
37
51
|
interface SerializedOverrideValue {
|
|
38
52
|
defined: boolean;
|
|
39
53
|
value?: unknown;
|
|
@@ -68,5 +82,5 @@ declare function deleteInstanceOverride(state: InstanceOverrideState, instanceId
|
|
|
68
82
|
declare function clearInstanceOverrides(state: InstanceOverrideState): void;
|
|
69
83
|
declare function forEachInstanceOverride(state: InstanceOverrideState, callback: (nodeId: string, field: InstanceOverrideField, value: unknown) => void): void;
|
|
70
84
|
//#endregion
|
|
71
|
-
export { InstanceOverrideField, InstanceOverrideReferenceMapper, InstanceOverrideState, REPLACED_LAYER_OVERRIDE, SerializedInstanceOverrideState, SerializedOverrideValue, assignmentOverrideField, bindingOverrideField, clearInstanceOverrides, cloneInstanceOverrideState, copiedComponentLayerId, createInstanceOverrideState, deleteInstanceOverride, deserializeInstanceOverrideState, forEachInstanceOverride, getInstanceOverride, hasInstanceOverride, isLayerReferenceOverride, overriddenAssignmentId, overriddenBindingField, overriddenVariableModeCollection, remapInstanceOverrideState, serializeInstanceOverrideState, setInstanceOverride, variableModeOverrideField };
|
|
85
|
+
export { EMPTY_INSTANCE_OVERRIDES, InstanceOverrideField, InstanceOverrideReferenceMapper, InstanceOverrideState, REPLACED_LAYER_OVERRIDE, SerializedInstanceOverrideState, SerializedOverrideValue, assignmentOverrideField, bindingOverrideField, clearInstanceOverrides, cloneInstanceOverrideState, copiedComponentLayerId, createInstanceOverrideState, deleteInstanceOverride, deserializeInstanceOverrideState, forEachInstanceOverride, getInstanceOverride, hasInstanceOverride, isEmptyInstanceOverrideState, isLayerReferenceOverride, overriddenAssignmentId, overriddenBindingField, overriddenVariableModeCollection, ownInstanceOverrides, remapInstanceOverrideState, serializeInstanceOverrideState, setInstanceOverride, variableModeOverrideField };
|
|
72
86
|
//# sourceMappingURL=overrides.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"overrides.d.ts","names":[],"sources":["../../src/instances/overrides.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"overrides.d.ts","names":[],"sources":["../../src/instances/overrides.ts"],"mappings":";;KAAY;UAIK;EACf,MAAM,IAAI;EACV,aAAa,YAAY,IAAI;;;;;;iBASf,qBAAqB,gBAAgB;;iBAKrC,uBAAuB,OAAO;;;;;iBAY9B,0BAA0B,uBAAuB;;iBAKjD,iCAAiC,OAAO;;;;;iBAYxC,wBAAwB,qBAAqB;;iBAK7C,uBAAuB,OAAO;;;;;;cAWjC;;iBAGG,yBAAyB,OAAO;iBAMhC,+BAA+B;;;;;;cA8BlC,0BAA0B;iBAKvB,6BAA6B,OAAO;;;;;;iBASpC,qBAAqB,MAAM,YAAY;UAOtC;EACf;EACA;;UAGe;EACf,MAAM,OAAO,uBAAuB;EACpC,aAAa,eAAe,OAAO,uBAAuB;;iBAiC5C,+BACd,OAAO,wBACN;iBAUa,iCAAiC,iBAAiB;iBAgBlD,2BAA2B,OAAO,wBAAwB;UAYzD;EACf,OAAO;EACP,WAAW;EACX,cAAc;EACd,YAAY;;;iBAIE,2BACd,OAAO,uBACP,YAAY,kCACX;iBAkCa,oBACd,OAAO,uBACP,oBACA,gBACA,OAAO;;;;;iBASO,uBACd,OAAO,uBACP,oBACA;EAAQ;EAAY;;iBAMN,oBACd,OAAO,uBACP,oBACA,gBACA,OAAO;iBAMO,oBACd,OAAO,uBACP,oBACA,gBACA,OAAO,uBACP;iBAWc,uBACd,OAAO,uBACP,oBACA,gBACA,OAAO;iBAQO,uBAAuB,OAAO;iBAK9B,wBACd,OAAO,uBACP,WAAW,gBAAgB,OAAO,uBAAuB"}
|
|
@@ -51,6 +51,42 @@ function createInstanceOverrideState() {
|
|
|
51
51
|
descendants: /* @__PURE__ */ new Map()
|
|
52
52
|
};
|
|
53
53
|
}
|
|
54
|
+
const SHARED_STATE_WRITE = "the shared empty instance overrides are read-only; call ownInstanceOverrides(node) first";
|
|
55
|
+
/** A map the shared state throws from on every write, which still answers all reads. */
|
|
56
|
+
var SharedOverrideMap = class extends Map {
|
|
57
|
+
set(key, value) {
|
|
58
|
+
throw new Error(SHARED_STATE_WRITE);
|
|
59
|
+
}
|
|
60
|
+
delete(key) {
|
|
61
|
+
throw new Error(SHARED_STATE_WRITE);
|
|
62
|
+
}
|
|
63
|
+
clear() {
|
|
64
|
+
throw new Error(SHARED_STATE_WRITE);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* What a layer holds until it records an override of its own. Shared and frozen, so an empty state
|
|
69
|
+
* costs nothing per layer and a write that skipped `ownInstanceOverrides` throws where it happens
|
|
70
|
+
* instead of reaching every layer of every document.
|
|
71
|
+
*/
|
|
72
|
+
const EMPTY_INSTANCE_OVERRIDES = Object.freeze({
|
|
73
|
+
self: new SharedOverrideMap(),
|
|
74
|
+
descendants: new SharedOverrideMap()
|
|
75
|
+
});
|
|
76
|
+
function isEmptyInstanceOverrideState(state) {
|
|
77
|
+
return state.self.size === 0 && state.descendants.size === 0;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* The layer's own override state, giving it a fresh one when it still holds the shared empty
|
|
81
|
+
* state. Writers record through this and then persist it with `updateNode`, so the change reaches
|
|
82
|
+
* events and undo instead of only the layer.
|
|
83
|
+
*/
|
|
84
|
+
function ownInstanceOverrides(node) {
|
|
85
|
+
if (node.instanceOverrides !== EMPTY_INSTANCE_OVERRIDES) return node.instanceOverrides;
|
|
86
|
+
const owned = createInstanceOverrideState();
|
|
87
|
+
node.instanceOverrides = owned;
|
|
88
|
+
return owned;
|
|
89
|
+
}
|
|
54
90
|
function serializeOverrideValue(value) {
|
|
55
91
|
return value === void 0 ? { defined: false } : {
|
|
56
92
|
defined: true,
|
|
@@ -185,6 +221,6 @@ function forEachInstanceOverride(state, callback) {
|
|
|
185
221
|
for (const [nodeId, fields] of state.descendants) for (const [field, value] of fields) callback(nodeId, field, value);
|
|
186
222
|
}
|
|
187
223
|
//#endregion
|
|
188
|
-
export { REPLACED_LAYER_OVERRIDE, assignmentOverrideField, bindingOverrideField, clearInstanceOverrides, cloneInstanceOverrideState, copiedComponentLayerId, createInstanceOverrideState, deleteInstanceOverride, deserializeInstanceOverrideState, forEachInstanceOverride, getInstanceOverride, hasInstanceOverride, isLayerReferenceOverride, overriddenAssignmentId, overriddenBindingField, overriddenVariableModeCollection, remapInstanceOverrideState, serializeInstanceOverrideState, setInstanceOverride, variableModeOverrideField };
|
|
224
|
+
export { EMPTY_INSTANCE_OVERRIDES, REPLACED_LAYER_OVERRIDE, assignmentOverrideField, bindingOverrideField, clearInstanceOverrides, cloneInstanceOverrideState, copiedComponentLayerId, createInstanceOverrideState, deleteInstanceOverride, deserializeInstanceOverrideState, forEachInstanceOverride, getInstanceOverride, hasInstanceOverride, isEmptyInstanceOverrideState, isLayerReferenceOverride, overriddenAssignmentId, overriddenBindingField, overriddenVariableModeCollection, ownInstanceOverrides, remapInstanceOverrideState, serializeInstanceOverrideState, setInstanceOverride, variableModeOverrideField };
|
|
189
225
|
|
|
190
226
|
//# sourceMappingURL=overrides.js.map
|