@pairdraw/scene-graph 0.16.2 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/checkpoint.d.ts.map +1 -1
- package/dist/checkpoint.js +8 -3
- package/dist/checkpoint.js.map +1 -1
- package/dist/color/index.d.ts.map +1 -1
- package/dist/color/index.js +3 -3
- package/dist/color/index.js.map +1 -1
- package/dist/color/management.d.ts.map +1 -1
- package/dist/color/management.js +4 -2
- package/dist/color/management.js.map +1 -1
- package/dist/coordinate.d.ts.map +1 -1
- package/dist/coordinate.js +3 -1
- package/dist/coordinate.js.map +1 -1
- package/dist/copy.d.ts.map +1 -1
- package/dist/copy.js +7 -3
- package/dist/copy.js.map +1 -1
- package/dist/css/values.d.ts.map +1 -1
- package/dist/css/values.js +2 -2
- package/dist/css/values.js.map +1 -1
- package/dist/effects.d.ts +16 -0
- package/dist/effects.d.ts.map +1 -0
- package/dist/effects.js +78 -0
- package/dist/effects.js.map +1 -0
- package/dist/geometry.d.ts +14 -7
- package/dist/geometry.d.ts.map +1 -1
- package/dist/geometry.js +130 -26
- package/dist/geometry.js.map +1 -1
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +12 -3
- package/dist/graph.js.map +1 -1
- package/dist/hit-test.d.ts.map +1 -1
- package/dist/hit-test.js +100 -8
- package/dist/hit-test.js.map +1 -1
- package/dist/instances/content-size.js +1 -1
- package/dist/instances/index.d.ts.map +1 -1
- package/dist/instances/index.js +4 -1
- package/dist/instances/index.js.map +1 -1
- package/dist/instances/sync.js +4 -3
- package/dist/instances/sync.js.map +1 -1
- package/dist/layout/index.js +1 -1
- package/dist/node-defaults.d.ts.map +1 -1
- package/dist/node-defaults.js +4 -1
- package/dist/node-defaults.js.map +1 -1
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +5 -0
- package/dist/preview.js.map +1 -1
- package/dist/resize.d.ts +4 -1
- package/dist/resize.d.ts.map +1 -1
- package/dist/resize.js +18 -12
- package/dist/resize.js.map +1 -1
- package/dist/scaling/node.d.ts.map +1 -1
- package/dist/scaling/node.js +3 -1
- package/dist/scaling/node.js.map +1 -1
- package/dist/scaling/tree.d.ts.map +1 -1
- package/dist/scaling/tree.js +8 -5
- package/dist/scaling/tree.js.map +1 -1
- package/dist/slots/authoring.js +3 -6
- package/dist/slots/authoring.js.map +1 -1
- package/dist/slots/content.d.ts.map +1 -1
- package/dist/slots/content.js +15 -25
- package/dist/slots/content.js.map +1 -1
- package/dist/slots/frames.js +1 -2
- package/dist/slots/frames.js.map +1 -1
- package/dist/snap.d.ts.map +1 -1
- package/dist/snap.js +12 -4
- package/dist/snap.js.map +1 -1
- package/dist/types.d.ts +5 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/undo.d.ts +2 -1
- package/dist/undo.d.ts.map +1 -1
- package/dist/undo.js +3 -2
- package/dist/undo.js.map +1 -1
- package/dist/variables/bindings.d.ts +2 -1
- package/dist/variables/bindings.d.ts.map +1 -1
- package/dist/variables/bindings.js +6 -2
- package/dist/variables/bindings.js.map +1 -1
- package/dist/variables/index.d.ts +2 -1
- package/dist/variables/index.d.ts.map +1 -1
- package/dist/variables/index.js +37 -7
- package/dist/variables/index.js.map +1 -1
- package/dist/variables/units.d.ts +31 -0
- package/dist/variables/units.d.ts.map +1 -0
- package/dist/variables/units.js +79 -4
- package/dist/variables/units.js.map +1 -1
- package/package.json +6 -1
- package/src/checkpoint.ts +8 -2
- package/src/color/index.ts +4 -6
- package/src/color/management.ts +8 -2
- package/src/coordinate.ts +4 -1
- package/src/copy.ts +8 -3
- package/src/css/values.ts +3 -2
- package/src/effects.ts +76 -0
- package/src/geometry.ts +147 -24
- package/src/graph.ts +13 -3
- package/src/hit-test.ts +138 -16
- package/src/instances/index.ts +5 -1
- package/src/instances/sync.ts +5 -3
- package/src/node-defaults.ts +4 -1
- package/src/preview.ts +4 -0
- package/src/resize.ts +40 -20
- package/src/scaling/node.ts +3 -1
- package/src/scaling/tree.ts +3 -2
- package/src/slots/authoring.ts +7 -7
- package/src/slots/content.ts +13 -19
- package/src/slots/frames.ts +3 -3
- package/src/snap.ts +14 -4
- package/src/types.ts +5 -0
- package/src/undo.ts +3 -2
- package/src/variables/bindings.ts +6 -2
- package/src/variables/index.ts +49 -8
- package/src/variables/units.ts +97 -4
package/dist/checkpoint.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkpoint.d.ts","names":[],"sources":["../src/checkpoint.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"checkpoint.d.ts","names":[],"sources":["../src/checkpoint.ts"],"mappings":";;;;iBAqIgB,uBAAuB,OAAO;;;;;;;;;;;;;;iBAiH9B,sBAAsB,OAAO;yBAAA;EAmBlB,oBAAA,YAAY;EAUJ,4BAAA,YAAY"}
|
package/dist/checkpoint.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { isEqual } from "es-toolkit";
|
|
2
2
|
//#region src/checkpoint.ts
|
|
3
3
|
/**
|
|
4
|
-
* The document state outside its layers, copied: variables, collections, modes, the instance
|
|
5
|
-
*
|
|
4
|
+
* The document state outside its layers, copied: variables, collections, modes, the instance and
|
|
5
|
+
* connector indexes, libraries, images, and document metadata, which a rollback restores in place.
|
|
6
6
|
*/
|
|
7
7
|
function captureTables(graph) {
|
|
8
8
|
const variableRefs = new Map(graph.variables);
|
|
@@ -12,8 +12,10 @@ function captureTables(graph) {
|
|
|
12
12
|
variableCollections: graph.variableCollections,
|
|
13
13
|
activeMode: graph.activeMode,
|
|
14
14
|
instanceIndex: graph.instanceIndex,
|
|
15
|
+
connectorIds: graph.connectorIds,
|
|
15
16
|
enabledLibraries: graph.enabledLibraries,
|
|
16
17
|
rootId: graph.rootId,
|
|
18
|
+
documentKind: graph.documentKind,
|
|
17
19
|
figKiwiVersion: graph.figKiwiVersion,
|
|
18
20
|
figSchemaDeflated: graph.figSchemaDeflated,
|
|
19
21
|
documentColorSpace: graph.documentColorSpace
|
|
@@ -26,16 +28,19 @@ function captureTables(graph) {
|
|
|
26
28
|
}
|
|
27
29
|
}
|
|
28
30
|
function assertDocumentUnchanged() {
|
|
29
|
-
if (!isEqual(snapshot.variableCollections, graph.variableCollections) || !isEqual(snapshot.activeMode, graph.activeMode) || !isEqual(snapshot.instanceIndex, graph.instanceIndex) || !isEqual(snapshot.enabledLibraries, graph.enabledLibraries) || images.size !== graph.images.size || [...images].some(([id, bytes]) => graph.images.get(id) !== bytes) || graph.rootId !== snapshot.rootId || graph.documentColorSpace !== snapshot.documentColorSpace || graph.figKiwiVersion !== snapshot.figKiwiVersion || !isEqual(graph.figSchemaDeflated, snapshot.figSchemaDeflated)) throw new Error("Atomic tools must not change collections, assets or document metadata");
|
|
31
|
+
if (!isEqual(snapshot.variableCollections, graph.variableCollections) || !isEqual(snapshot.activeMode, graph.activeMode) || !isEqual(snapshot.instanceIndex, graph.instanceIndex) || !isEqual(snapshot.enabledLibraries, graph.enabledLibraries) || images.size !== graph.images.size || [...images].some(([id, bytes]) => graph.images.get(id) !== bytes) || graph.rootId !== snapshot.rootId || graph.documentKind !== snapshot.documentKind || graph.documentColorSpace !== snapshot.documentColorSpace || graph.figKiwiVersion !== snapshot.figKiwiVersion || !isEqual(graph.figSchemaDeflated, snapshot.figSchemaDeflated)) throw new Error("Atomic tools must not change collections, assets or document metadata");
|
|
30
32
|
}
|
|
31
33
|
function restore() {
|
|
32
34
|
restoreObjects(graph.variables, snapshot.variables, variableRefs);
|
|
33
35
|
restoreObjects(graph.variableCollections, snapshot.variableCollections, collectionRefs);
|
|
34
36
|
restoreMap(graph.activeMode, structuredClone(snapshot.activeMode));
|
|
35
37
|
restoreMap(graph.instanceIndex, structuredClone(snapshot.instanceIndex));
|
|
38
|
+
graph.connectorIds.clear();
|
|
39
|
+
for (const id of snapshot.connectorIds) graph.connectorIds.add(id);
|
|
36
40
|
restoreMap(graph.enabledLibraries, structuredClone(snapshot.enabledLibraries));
|
|
37
41
|
restoreMap(graph.images, images);
|
|
38
42
|
graph.rootId = snapshot.rootId;
|
|
43
|
+
graph.documentKind = snapshot.documentKind;
|
|
39
44
|
graph.figKiwiVersion = snapshot.figKiwiVersion;
|
|
40
45
|
graph.figSchemaDeflated = structuredClone(snapshot.figSchemaDeflated);
|
|
41
46
|
graph.documentColorSpace = snapshot.documentColorSpace;
|
package/dist/checkpoint.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkpoint.js","names":[],"sources":["../src/checkpoint.ts"],"sourcesContent":["import { isEqual } from 'es-toolkit'\n\nimport type { SceneGraph } from './graph'\nimport type { InstanceOverrideState } from './instances/overrides'\nimport type { SceneNode } from './types'\n\n/**\n * The document state outside its layers, copied: variables, collections, modes, the instance\n * index, libraries, images, and document metadata, which a rollback restores in place.\n */\nfunction captureTables(graph: SceneGraph) {\n const variableRefs = new Map(graph.variables)\n const collectionRefs = new Map(graph.variableCollections)\n const snapshot = structuredClone({\n variables: graph.variables,\n variableCollections: graph.variableCollections,\n activeMode: graph.activeMode,\n instanceIndex: graph.instanceIndex,\n enabledLibraries: graph.enabledLibraries,\n rootId: graph.rootId,\n figKiwiVersion: graph.figKiwiVersion,\n figSchemaDeflated: graph.figSchemaDeflated,\n documentColorSpace: graph.documentColorSpace\n })\n // Atomic property tools cannot edit assets. Retain existing buffers, not copies of every bitmap.\n const images = new Map(graph.images)\n\n function assertVariablesKept() {\n for (const [id, before] of snapshot.variables) {\n const after = graph.variables.get(id)\n if (\n !after ||\n after !== variableRefs.get(id) ||\n before.id !== after.id ||\n before.collectionId !== after.collectionId ||\n before.type !== after.type\n )\n throw new Error('Atomic tools must not change variable identity')\n }\n }\n\n function assertDocumentUnchanged() {\n if (\n !isEqual(snapshot.variableCollections, graph.variableCollections) ||\n !isEqual(snapshot.activeMode, graph.activeMode) ||\n !isEqual(snapshot.instanceIndex, graph.instanceIndex) ||\n !isEqual(snapshot.enabledLibraries, graph.enabledLibraries) ||\n images.size !== graph.images.size ||\n [...images].some(([id, bytes]) => graph.images.get(id) !== bytes) ||\n graph.rootId !== snapshot.rootId ||\n graph.documentColorSpace !== snapshot.documentColorSpace ||\n graph.figKiwiVersion !== snapshot.figKiwiVersion ||\n !isEqual(graph.figSchemaDeflated, snapshot.figSchemaDeflated)\n ) {\n throw new Error('Atomic tools must not change collections, assets or document metadata')\n }\n }\n\n function restore() {\n restoreObjects(graph.variables, snapshot.variables, variableRefs)\n restoreObjects(graph.variableCollections, snapshot.variableCollections, collectionRefs)\n restoreMap(graph.activeMode, structuredClone(snapshot.activeMode))\n restoreMap(graph.instanceIndex, structuredClone(snapshot.instanceIndex))\n restoreMap(graph.enabledLibraries, structuredClone(snapshot.enabledLibraries))\n restoreMap(graph.images, images)\n graph.rootId = snapshot.rootId\n graph.figKiwiVersion = snapshot.figKiwiVersion\n graph.figSchemaDeflated = structuredClone(snapshot.figSchemaDeflated)\n graph.documentColorSpace = snapshot.documentColorSpace\n }\n\n return {\n variables: snapshot.variables,\n variableCount: snapshot.variables.size,\n assertVariablesKept,\n assertDocumentUnchanged,\n restore\n }\n}\n\nfunction assertSameNodes(graph: SceneGraph, refs: Map<string, SceneNode>, variableCount: number) {\n if (refs.size !== graph.nodes.size || variableCount !== graph.variables.size)\n throw new Error('Atomic tools must not create or remove nodes or variables')\n}\n\nfunction assertHierarchyKept(\n graph: SceneGraph,\n refs: Map<string, SceneNode>,\n before: SceneNode,\n id: string\n) {\n const after = graph.nodes.get(id)\n if (\n !after ||\n after !== refs.get(id) ||\n before.id !== after.id ||\n before.type !== after.type ||\n before.parentId !== after.parentId ||\n before.componentId !== after.componentId ||\n !isEqual(before.childIds, after.childIds)\n ) {\n throw new Error('Atomic tools must not change node hierarchy or identity')\n }\n}\n\n/**\n * Lets consumers know the restored hierarchy and indexes, once all of it is in place: removed\n * layers first, then the layers put back, then `changed` ones.\n */\nfunction announceRestore(\n graph: SceneGraph,\n failedNodes: Map<string, SceneNode>,\n changed: Iterable<string>\n) {\n for (const [id, node] of failedNodes) {\n if (!graph.nodes.has(id)) graph.emitter.emit('node:deleted', id, node.parentId)\n }\n for (const id of changed) {\n const node = graph.nodes.get(id)\n if (node && failedNodes.has(id)) graph.emitter.emit('node:updated', id, node)\n }\n for (const node of graph.nodes.values()) {\n if (!failedNodes.has(node.id)) graph.emitter.emit('node:created', node)\n }\n}\n\n/** Capture rollback state without changing graph or surviving object identities. */\nexport function captureGraphCheckpoint(graph: SceneGraph) {\n const nodeRefs = new Map(graph.nodes)\n const nodes = structuredClone(graph.nodes)\n const tables = captureTables(graph)\n\n function assertPropertiesOnly() {\n assertSameNodes(graph, nodeRefs, tables.variableCount)\n for (const [id, before] of nodes) assertHierarchyKept(graph, nodeRefs, before, id)\n tables.assertVariablesKept()\n tables.assertDocumentUnchanged()\n }\n\n function restore() {\n const failedNodes = new Map(graph.nodes)\n restoreObjects(graph.nodes, nodes, nodeRefs)\n tables.restore()\n graph.clearAbsPosCache()\n announceRestore(graph, failedNodes, graph.nodes.keys())\n }\n\n return { nodes, variables: tables.variables, assertPropertiesOnly, restore }\n}\n\nfunction copyOverrides(state: InstanceOverrideState): InstanceOverrideState {\n return {\n self: new Map(state.self),\n descendants: new Map([...state.descendants].map(([id, fields]) => [id, new Map(fields)]))\n }\n}\n\n/**\n * A layer's fields as they are, sharing their values, with the parts the graph edits in place\n * (child list, source metadata, override maps) copied, as undo recording copies a page.\n */\nfunction referenceCopy(node: SceneNode): SceneNode {\n const { source } = node\n return {\n ...node,\n childIds: [...node.childIds],\n source: { ...source, fig: { ...source.fig, rawNodeFields: { ...source.fig.rawNodeFields } } },\n instanceOverrides: copyOverrides(node.instanceOverrides)\n }\n}\n\nfunction keyCount(value: object): number {\n let count = 0\n for (const key in value) if (Object.hasOwn(value, key)) count++\n return count\n}\n\n/**\n * Whether `current` holds the same keys as `saved`, each with the same value, except `skip`;\n * `savedKeys` is how many keys `saved` has, when already counted.\n */\nfunction sameFields<T extends object>(\n current: T,\n saved: T,\n skip?: ReadonlySet<string>,\n savedKeys = keyCount(saved)\n): boolean {\n let currentKeys = 0\n for (const key in current) {\n if (!Object.hasOwn(current, key)) continue\n currentKeys++\n if (skip?.has(key)) continue\n if (current[key] !== saved[key]) return false\n }\n return currentKeys === savedKeys\n}\n\nfunction sameMap<K, V>(current: Map<K, V>, saved: Map<K, V>): boolean {\n if (current.size !== saved.size) return false\n for (const [key, value] of current) if (saved.get(key) !== value) return false\n return true\n}\n\nconst COPIED_FIELDS: ReadonlySet<string> = new Set(['childIds', 'source', 'instanceOverrides'])\nconst SOURCE_FIG: ReadonlySet<string> = new Set(['fig'])\nconst FIG_RAW_FIELDS: ReadonlySet<string> = new Set(['rawNodeFields'])\n\n/** A layer's reference copy, and how many fields it has. */\ninterface Reference {\n node: SceneNode\n fields: number\n}\n\n/** Whether anything of `node` differs from its reference copy, even written in place. */\nfunction differs(node: SceneNode, { node: saved, fields }: Reference): boolean {\n const { source, instanceOverrides: overrides } = node\n const savedOverrides = saved.instanceOverrides\n return !(\n sameFields(node, saved, COPIED_FIELDS, fields) &&\n isEqual(node.childIds, saved.childIds) &&\n sameFields(source, saved.source, SOURCE_FIG) &&\n sameFields(source.fig, saved.source.fig, FIG_RAW_FIELDS) &&\n sameFields(source.fig.rawNodeFields, saved.source.fig.rawNodeFields) &&\n sameMap(overrides.self, savedOverrides.self) &&\n overrides.descendants.size === savedOverrides.descendants.size &&\n [...overrides.descendants].every(([id, fields]) => {\n const savedFields = savedOverrides.descendants.get(id)\n return savedFields !== undefined && sameMap(fields, savedFields)\n })\n )\n}\n\n/**\n * Rollback state for an edit that may only change properties, costing what the edit touches:\n * every layer is kept by reference (its values shared, the parts the graph edits in place\n * copied), and a layer the graph announces with `willChangeNode` is deep-copied before it\n * changes. A layer written without that announcement is still caught and restored as long as\n * its values were replaced rather than written into, as the graph's contract asks. The other\n * tables are copied whole, as `captureGraphCheckpoint` does. Call `release` when done.\n */\nexport function captureEditCheckpoint(graph: SceneGraph) {\n const nodeRefs = new Map(graph.nodes)\n const references = new Map<string, Reference>()\n for (const [id, node] of nodeRefs) {\n const copy = referenceCopy(node)\n references.set(id, { node: copy, fields: keyCount(copy) })\n }\n // Deep copies of announced layers, taken before they change.\n const announced = new Map<string, SceneNode>()\n const release = graph.observeNodeChanges({\n created: () => undefined,\n before: (node) => {\n const saved = references.get(node.id)\n if (saved && !announced.has(node.id)) announced.set(node.id, structuredClone(saved.node))\n }\n })\n const tables = captureTables(graph)\n\n /** Each layer the edit changed so far, as it was before: announced ones and any other. */\n function changedNodes(): Map<string, SceneNode> {\n const changed = new Map(announced)\n for (const [id, node] of graph.nodes) {\n const saved = references.get(id)\n if (saved && !changed.has(id) && differs(node, saved)) changed.set(id, saved.node)\n }\n return changed\n }\n\n /** Throws unless the edit only changed properties; returns what it changed, as `changedNodes`. */\n function assertPropertiesOnly(): Map<string, SceneNode> {\n assertSameNodes(graph, nodeRefs, tables.variableCount)\n for (const [id, ref] of nodeRefs) {\n if (graph.nodes.get(id) !== ref)\n throw new Error('Atomic tools must not change node hierarchy or identity')\n }\n const changed = changedNodes()\n for (const [id, before] of changed) assertHierarchyKept(graph, nodeRefs, before, id)\n tables.assertVariablesKept()\n tables.assertDocumentUnchanged()\n return changed\n }\n\n function restore() {\n const changed = changedNodes()\n const failedNodes = new Map(graph.nodes)\n graph.nodes.clear()\n for (const [id, node] of nodeRefs) graph.nodes.set(id, node)\n for (const [id, saved] of changed) {\n const node = nodeRefs.get(id)\n if (!node) continue\n for (const key of Object.keys(node) as (keyof SceneNode)[]) {\n if (!(key in saved)) Reflect.deleteProperty(node, key)\n }\n // A deep copy is the checkpoint's own; a reference copy holds the values the layer had.\n Object.assign(node, announced.has(id) ? structuredClone(saved) : saved)\n }\n tables.restore()\n graph.clearAbsPosCache()\n announceRestore(graph, failedNodes, changed.keys())\n }\n\n return { variables: tables.variables, changedNodes, assertPropertiesOnly, restore, release }\n}\n\nfunction restoreObjects<T extends object>(\n target: Map<string, T>,\n snapshot: Map<string, T>,\n refs: Map<string, T>\n) {\n target.clear()\n for (const [id, saved] of snapshot) {\n const original = refs.get(id)\n if (!original) throw new Error(`Missing checkpoint reference: ${id}`)\n for (const key of Object.keys(original) as (keyof T)[]) {\n if (!(key in saved)) Reflect.deleteProperty(original, key)\n }\n Object.assign(original, structuredClone(saved))\n target.set(id, original)\n }\n}\n\nfunction restoreMap<K, V>(target: Map<K, V>, saved: Map<K, V>) {\n target.clear()\n for (const [key, value] of saved) target.set(key, value)\n}\n"],"mappings":";;;;;;AAUA,SAAS,cAAc,OAAmB;CACxC,MAAM,eAAe,IAAI,IAAI,MAAM,SAAS;CAC5C,MAAM,iBAAiB,IAAI,IAAI,MAAM,mBAAmB;CACxD,MAAM,WAAW,gBAAgB;EAC/B,WAAW,MAAM;EACjB,qBAAqB,MAAM;EAC3B,YAAY,MAAM;EAClB,eAAe,MAAM;EACrB,kBAAkB,MAAM;EACxB,QAAQ,MAAM;EACd,gBAAgB,MAAM;EACtB,mBAAmB,MAAM;EACzB,oBAAoB,MAAM;CAC5B,CAAC;CAED,MAAM,SAAS,IAAI,IAAI,MAAM,MAAM;CAEnC,SAAS,sBAAsB;EAC7B,KAAK,MAAM,CAAC,IAAI,WAAW,SAAS,WAAW;GAC7C,MAAM,QAAQ,MAAM,UAAU,IAAI,EAAE;GACpC,IACE,CAAC,SACD,UAAU,aAAa,IAAI,EAAE,KAC7B,OAAO,OAAO,MAAM,MACpB,OAAO,iBAAiB,MAAM,gBAC9B,OAAO,SAAS,MAAM,MAEtB,MAAM,IAAI,MAAM,gDAAgD;EACpE;CACF;CAEA,SAAS,0BAA0B;EACjC,IACE,CAAC,QAAQ,SAAS,qBAAqB,MAAM,mBAAmB,KAChE,CAAC,QAAQ,SAAS,YAAY,MAAM,UAAU,KAC9C,CAAC,QAAQ,SAAS,eAAe,MAAM,aAAa,KACpD,CAAC,QAAQ,SAAS,kBAAkB,MAAM,gBAAgB,KAC1D,OAAO,SAAS,MAAM,OAAO,QAC7B,CAAC,GA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e,UAAU,GAAG;EAE3D,OAAO,OAAO,UAAU,gBAAgB,KAAK,CAAC;EAC9C,OAAO,IAAI,IAAI,QAAQ;CACzB;AACF;AAEA,SAAS,WAAiB,QAAmB,OAAkB;CAC7D,OAAO,MAAM;CACb,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,OAAO,IAAI,KAAK,KAAK;AACzD"}
|
|
1
|
+
{"version":3,"file":"checkpoint.js","names":[],"sources":["../src/checkpoint.ts"],"sourcesContent":["import { isEqual } from 'es-toolkit'\n\nimport type { SceneGraph } from './graph'\nimport type { InstanceOverrideState } from './instances/overrides'\nimport type { SceneNode } from './types'\n\n/**\n * The document state outside its layers, copied: variables, collections, modes, the instance and\n * connector indexes, libraries, images, and document metadata, which a rollback restores in place.\n */\nfunction captureTables(graph: SceneGraph) {\n const variableRefs = new Map(graph.variables)\n const collectionRefs = new Map(graph.variableCollections)\n const snapshot = structuredClone({\n variables: graph.variables,\n variableCollections: graph.variableCollections,\n activeMode: graph.activeMode,\n instanceIndex: graph.instanceIndex,\n connectorIds: graph.connectorIds,\n enabledLibraries: graph.enabledLibraries,\n rootId: graph.rootId,\n documentKind: graph.documentKind,\n figKiwiVersion: graph.figKiwiVersion,\n figSchemaDeflated: graph.figSchemaDeflated,\n documentColorSpace: graph.documentColorSpace\n })\n // Atomic property tools cannot edit assets. Retain existing buffers, not copies of every bitmap.\n const images = new Map(graph.images)\n\n function assertVariablesKept() {\n for (const [id, before] of snapshot.variables) {\n const after = graph.variables.get(id)\n if (\n !after ||\n after !== variableRefs.get(id) ||\n before.id !== after.id ||\n before.collectionId !== after.collectionId ||\n before.type !== after.type\n )\n throw new Error('Atomic tools must not change variable identity')\n }\n }\n\n function assertDocumentUnchanged() {\n if (\n !isEqual(snapshot.variableCollections, graph.variableCollections) ||\n !isEqual(snapshot.activeMode, graph.activeMode) ||\n !isEqual(snapshot.instanceIndex, graph.instanceIndex) ||\n !isEqual(snapshot.enabledLibraries, graph.enabledLibraries) ||\n images.size !== graph.images.size ||\n [...images].some(([id, bytes]) => graph.images.get(id) !== bytes) ||\n graph.rootId !== snapshot.rootId ||\n graph.documentKind !== snapshot.documentKind ||\n graph.documentColorSpace !== snapshot.documentColorSpace ||\n graph.figKiwiVersion !== snapshot.figKiwiVersion ||\n !isEqual(graph.figSchemaDeflated, snapshot.figSchemaDeflated)\n ) {\n throw new Error('Atomic tools must not change collections, assets or document metadata')\n }\n }\n\n function restore() {\n restoreObjects(graph.variables, snapshot.variables, variableRefs)\n restoreObjects(graph.variableCollections, snapshot.variableCollections, collectionRefs)\n restoreMap(graph.activeMode, structuredClone(snapshot.activeMode))\n restoreMap(graph.instanceIndex, structuredClone(snapshot.instanceIndex))\n graph.connectorIds.clear()\n for (const id of snapshot.connectorIds) graph.connectorIds.add(id)\n restoreMap(graph.enabledLibraries, structuredClone(snapshot.enabledLibraries))\n restoreMap(graph.images, images)\n graph.rootId = snapshot.rootId\n graph.documentKind = snapshot.documentKind\n graph.figKiwiVersion = snapshot.figKiwiVersion\n graph.figSchemaDeflated = structuredClone(snapshot.figSchemaDeflated)\n graph.documentColorSpace = snapshot.documentColorSpace\n }\n\n return {\n variables: snapshot.variables,\n variableCount: snapshot.variables.size,\n assertVariablesKept,\n assertDocumentUnchanged,\n restore\n }\n}\n\nfunction assertSameNodes(graph: SceneGraph, refs: Map<string, SceneNode>, variableCount: number) {\n if (refs.size !== graph.nodes.size || variableCount !== graph.variables.size)\n throw new Error('Atomic tools must not create or remove nodes or variables')\n}\n\nfunction assertHierarchyKept(\n graph: SceneGraph,\n refs: Map<string, SceneNode>,\n before: SceneNode,\n id: string\n) {\n const after = graph.nodes.get(id)\n if (\n !after ||\n after !== refs.get(id) ||\n before.id !== after.id ||\n before.type !== after.type ||\n before.parentId !== after.parentId ||\n before.componentId !== after.componentId ||\n !isEqual(before.childIds, after.childIds)\n ) {\n throw new Error('Atomic tools must not change node hierarchy or identity')\n }\n}\n\n/**\n * Lets consumers know the restored hierarchy and indexes, once all of it is in place: removed\n * layers first, then the layers put back, then `changed` ones.\n */\nfunction announceRestore(\n graph: SceneGraph,\n failedNodes: Map<string, SceneNode>,\n changed: Iterable<string>\n) {\n for (const [id, node] of failedNodes) {\n if (!graph.nodes.has(id)) graph.emitter.emit('node:deleted', id, node.parentId)\n }\n for (const id of changed) {\n const node = graph.nodes.get(id)\n if (node && failedNodes.has(id)) graph.emitter.emit('node:updated', id, node)\n }\n for (const node of graph.nodes.values()) {\n if (!failedNodes.has(node.id)) graph.emitter.emit('node:created', node)\n }\n}\n\n/** Capture rollback state without changing graph or surviving object identities. */\nexport function captureGraphCheckpoint(graph: SceneGraph) {\n const nodeRefs = new Map(graph.nodes)\n const nodes = structuredClone(graph.nodes)\n const tables = captureTables(graph)\n\n function assertPropertiesOnly() {\n assertSameNodes(graph, nodeRefs, tables.variableCount)\n for (const [id, before] of nodes) assertHierarchyKept(graph, nodeRefs, before, id)\n tables.assertVariablesKept()\n tables.assertDocumentUnchanged()\n }\n\n function restore() {\n const failedNodes = new Map(graph.nodes)\n restoreObjects(graph.nodes, nodes, nodeRefs)\n tables.restore()\n graph.clearAbsPosCache()\n announceRestore(graph, failedNodes, graph.nodes.keys())\n }\n\n return { nodes, variables: tables.variables, assertPropertiesOnly, restore }\n}\n\nfunction copyOverrides(state: InstanceOverrideState): InstanceOverrideState {\n return {\n self: new Map(state.self),\n descendants: new Map([...state.descendants].map(([id, fields]) => [id, new Map(fields)]))\n }\n}\n\n/**\n * A layer's fields as they are, sharing their values, with the parts the graph edits in place\n * (child list, source metadata, override maps) copied, as undo recording copies a page.\n */\nfunction referenceCopy(node: SceneNode): SceneNode {\n const { source } = node\n return {\n ...node,\n childIds: [...node.childIds],\n source: { ...source, fig: { ...source.fig, rawNodeFields: { ...source.fig.rawNodeFields } } },\n instanceOverrides: copyOverrides(node.instanceOverrides)\n }\n}\n\nfunction keyCount(value: object): number {\n let count = 0\n for (const key in value) if (Object.hasOwn(value, key)) count++\n return count\n}\n\n/**\n * Whether `current` holds the same keys as `saved`, each with the same value, except `skip`;\n * `savedKeys` is how many keys `saved` has, when already counted.\n */\nfunction sameFields<T extends object>(\n current: T,\n saved: T,\n skip?: ReadonlySet<string>,\n savedKeys = keyCount(saved)\n): boolean {\n let currentKeys = 0\n for (const key in current) {\n if (!Object.hasOwn(current, key)) continue\n currentKeys++\n if (skip?.has(key)) continue\n if (current[key] !== saved[key]) return false\n }\n return currentKeys === savedKeys\n}\n\nfunction sameMap<K, V>(current: Map<K, V>, saved: Map<K, V>): boolean {\n if (current.size !== saved.size) return false\n for (const [key, value] of current) if (saved.get(key) !== value) return false\n return true\n}\n\nconst COPIED_FIELDS: ReadonlySet<string> = new Set(['childIds', 'source', 'instanceOverrides'])\nconst SOURCE_FIG: ReadonlySet<string> = new Set(['fig'])\nconst FIG_RAW_FIELDS: ReadonlySet<string> = new Set(['rawNodeFields'])\n\n/** A layer's reference copy, and how many fields it has. */\ninterface Reference {\n node: SceneNode\n fields: number\n}\n\n/** Whether anything of `node` differs from its reference copy, even written in place. */\nfunction differs(node: SceneNode, { node: saved, fields }: Reference): boolean {\n const { source, instanceOverrides: overrides } = node\n const savedOverrides = saved.instanceOverrides\n return !(\n sameFields(node, saved, COPIED_FIELDS, fields) &&\n isEqual(node.childIds, saved.childIds) &&\n sameFields(source, saved.source, SOURCE_FIG) &&\n sameFields(source.fig, saved.source.fig, FIG_RAW_FIELDS) &&\n sameFields(source.fig.rawNodeFields, saved.source.fig.rawNodeFields) &&\n sameMap(overrides.self, savedOverrides.self) &&\n overrides.descendants.size === savedOverrides.descendants.size &&\n [...overrides.descendants].every(([id, fields]) => {\n const savedFields = savedOverrides.descendants.get(id)\n return savedFields !== undefined && sameMap(fields, savedFields)\n })\n )\n}\n\n/**\n * Rollback state for an edit that may only change properties, costing what the edit touches:\n * every layer is kept by reference (its values shared, the parts the graph edits in place\n * copied), and a layer the graph announces with `willChangeNode` is deep-copied before it\n * changes. A layer written without that announcement is still caught and restored as long as\n * its values were replaced rather than written into, as the graph's contract asks. The other\n * tables are copied whole, as `captureGraphCheckpoint` does. Call `release` when done.\n */\nexport function captureEditCheckpoint(graph: SceneGraph) {\n const nodeRefs = new Map(graph.nodes)\n const references = new Map<string, Reference>()\n for (const [id, node] of nodeRefs) {\n const copy = referenceCopy(node)\n references.set(id, { node: copy, fields: keyCount(copy) })\n }\n // Deep copies of announced layers, taken before they change.\n const announced = new Map<string, SceneNode>()\n const release = graph.observeNodeChanges({\n created: () => undefined,\n before: (node) => {\n const saved = references.get(node.id)\n if (saved && !announced.has(node.id)) announced.set(node.id, structuredClone(saved.node))\n }\n })\n const tables = captureTables(graph)\n\n /** Each layer the edit changed so far, as it was before: announced ones and any other. */\n function changedNodes(): Map<string, SceneNode> {\n const changed = new Map(announced)\n for (const [id, node] of graph.nodes) {\n const saved = references.get(id)\n if (saved && !changed.has(id) && differs(node, saved)) changed.set(id, saved.node)\n }\n return changed\n }\n\n /** Throws unless the edit only changed properties; returns what it changed, as `changedNodes`. */\n function assertPropertiesOnly(): Map<string, SceneNode> {\n assertSameNodes(graph, nodeRefs, tables.variableCount)\n for (const [id, ref] of nodeRefs) {\n if (graph.nodes.get(id) !== ref)\n throw new Error('Atomic tools must not change node hierarchy or identity')\n }\n const changed = changedNodes()\n for (const [id, before] of changed) assertHierarchyKept(graph, nodeRefs, before, id)\n tables.assertVariablesKept()\n tables.assertDocumentUnchanged()\n return changed\n }\n\n function restore() {\n const changed = changedNodes()\n const failedNodes = new Map(graph.nodes)\n graph.nodes.clear()\n for (const [id, node] of nodeRefs) graph.nodes.set(id, node)\n for (const [id, saved] of changed) {\n const node = nodeRefs.get(id)\n if (!node) continue\n for (const key of Object.keys(node) as (keyof SceneNode)[]) {\n if (!(key in saved)) Reflect.deleteProperty(node, key)\n }\n // A deep copy is the checkpoint's own; a reference copy holds the values the layer had.\n Object.assign(node, announced.has(id) ? structuredClone(saved) : saved)\n }\n tables.restore()\n graph.clearAbsPosCache()\n announceRestore(graph, failedNodes, changed.keys())\n }\n\n return { variables: tables.variables, changedNodes, assertPropertiesOnly, restore, release }\n}\n\nfunction restoreObjects<T extends object>(\n target: Map<string, T>,\n snapshot: Map<string, T>,\n refs: Map<string, T>\n) {\n target.clear()\n for (const [id, saved] of snapshot) {\n const original = refs.get(id)\n if (!original) throw new Error(`Missing checkpoint reference: ${id}`)\n for (const key of Object.keys(original) as (keyof T)[]) {\n if (!(key in saved)) Reflect.deleteProperty(original, key)\n }\n Object.assign(original, structuredClone(saved))\n target.set(id, original)\n }\n}\n\nfunction restoreMap<K, V>(target: Map<K, V>, saved: Map<K, V>) {\n target.clear()\n for (const [key, value] of saved) target.set(key, value)\n}\n"],"mappings":";;;;;;AAUA,SAAS,cAAc,OAAmB;CACxC,MAAM,eAAe,IAAI,IAAI,MAAM,SAAS;CAC5C,MAAM,iBAAiB,IAAI,IAAI,MAAM,mBAAmB;CACxD,MAAM,WAAW,gBAAgB;EAC/B,WAAW,MAAM;EACjB,qBAAqB,MAAM;EAC3B,YAAY,MAAM;EAClB,eAAe,MAAM;EACrB,cAAc,MAAM;EACpB,kBAAkB,MAAM;EACxB,QAAQ,MAAM;EACd,cAAc,MAAM;EACpB,gBAAgB,MAAM;EACtB,mBAAmB,MAAM;EACzB,oBAAoB,MAAM;CAC5B,CAAC;CAED,MAAM,SAAS,IAAI,IAAI,MAAM,MAAM;CAEnC,SAAS,sBAAsB;EAC7B,KAAK,MAAM,CAAC,IAAI,WAAW,SAAS,WAAW;GAC7C,MAAM,QAAQ,MAAM,UAAU,IAAI,EAAE;GACpC,IACE,CAAC,SACD,UAAU,aAAa,IAAI,EAAE,KAC7B,OAAO,OAAO,MAAM,MACpB,OAAO,iBAAiB,MAAM,gBAC9B,OAAO,SAAS,MAAM,MAEtB,MAAM,IAAI,MAAM,gDAAgD;EACpE;CACF;CAEA,SAAS,0BAA0B;EACjC,IACE,CAAC,QAAQ,SAAS,qBAAqB,MAAM,mBAAmB,KAChE,CAAC,QAAQ,SAAS,YAAY,MAAM,UAAU,KAC9C,CAA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EA,SAAS,eACP,QACA,UACA,MACA;CACA,OAAO,MAAM;CACb,KAAK,MAAM,CAAC,IAAI,UAAU,UAAU;EAClC,MAAM,WAAW,KAAK,IAAI,EAAE;EAC5B,IAAI,CAAC,UAAU,MAAM,IAAI,MAAM,iCAAiC,IAAI;EACpE,KAAK,MAAM,OAAO,OAAO,KAAK,QAAQ,GACpC,IAAI,EAAE,OAAO,QAAQ,QAAQ,eAAe,UAAU,GAAG;EAE3D,OAAO,OAAO,UAAU,gBAAgB,KAAK,CAAC;EAC9C,OAAO,IAAI,IAAI,QAAQ;CACzB;AACF;AAEA,SAAS,WAAiB,QAAmB,OAAkB;CAC7D,OAAO,MAAM;CACb,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,OAAO,IAAI,KAAK,KAAK;AACzD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/color/index.ts"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/color/index.ts"],"mappings":";;;;;;;;iBAegB,cAAc,gBAAgB;;iBAS9B,WAAW,gBAAgB;iBAI3B,WAAW,OAAO;iBAIlB,YAAY,OAAO,OAAO;iBAM1B,cAAc,OAAO;iBAIrB,eAAe,OAAO;;;;;;iBAStB,WAAW,OAAO;iBAIlB,kBAAkB,OAAO;iBAOzB,eAAe,WAAW,WAAW,WAAW,aAAQ;iBAIxD,YAAY,gBAAgB;;;;;;;;;;;iBAY5B,cAAc,IAAI,OAAO,IAAI"}
|
package/dist/color/index.js
CHANGED
|
@@ -12,12 +12,12 @@ function tryParseColor(input) {
|
|
|
12
12
|
const parsed = parse(input);
|
|
13
13
|
if (!parsed) return null;
|
|
14
14
|
const rgb = toRGB(parsed);
|
|
15
|
-
return {
|
|
15
|
+
return normalizeColor({
|
|
16
16
|
r: rgb.r,
|
|
17
17
|
g: rgb.g,
|
|
18
18
|
b: rgb.b,
|
|
19
|
-
a: parsed.alpha
|
|
20
|
-
};
|
|
19
|
+
a: parsed.alpha
|
|
20
|
+
});
|
|
21
21
|
}
|
|
22
22
|
/** A CSS color, or black when `input` is not one. */
|
|
23
23
|
function parseColor(input) {
|
package/dist/color/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/color/index.ts"],"sourcesContent":["export * from './contrast'\nexport * from './management'\nexport { normalizeColor } from './normalize'\nexport * from './okhcl'\n\nimport { parse, formatHex, formatHex8, formatRgb, converter, differenceEuclidean } from 'culori'\n\nimport { BLACK } from '../constants'\nimport type { Color } from '../primitives'\n\nconst toRGB = converter('rgb')\n\n/** A CSS color, or null when `input` is not one. */\nexport function tryParseColor(input: string): Color | null {\n const parsed = parse(input)\n if (!parsed) return null\n const rgb = toRGB(parsed)\n return {
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/color/index.ts"],"sourcesContent":["export * from './contrast'\nexport * from './management'\nexport { normalizeColor } from './normalize'\nexport * from './okhcl'\nexport { colorSchema } from './schema'\n\nimport { parse, formatHex, formatHex8, formatRgb, converter, differenceEuclidean } from 'culori'\n\nimport { BLACK } from '../constants'\nimport type { Color } from '../primitives'\nimport { normalizeColor } from './normalize'\n\nconst toRGB = converter('rgb')\n\n/** A CSS color, or null when `input` is not one. */\nexport function tryParseColor(input: string): Color | null {\n const parsed = parse(input)\n if (!parsed) return null\n const rgb = toRGB(parsed)\n // culori leaves a `none` channel out, which normalizing reads as zero.\n return normalizeColor({ r: rgb.r, g: rgb.g, b: rgb.b, a: parsed.alpha })\n}\n\n/** A CSS color, or black when `input` is not one. */\nexport function parseColor(input: string): Color {\n return tryParseColor(input) ?? { ...BLACK }\n}\n\nexport function colorToHex(color: Color): string {\n return formatHex({ mode: 'rgb', r: color.r, g: color.g, b: color.b }).toUpperCase()\n}\n\nexport function colorToHex8(color: Color, alpha?: number): string {\n const a = alpha ?? color.a\n if (a >= 1) return colorToHex(color)\n return formatHex8({ mode: 'rgb', r: color.r, g: color.g, b: color.b, alpha: a }).toUpperCase()\n}\n\nexport function colorToHexRaw(color: Color): string {\n return colorToHex(color).slice(1)\n}\n\nexport function colorToRgba255(color: Color) {\n return {\n r: Math.round(color.r * 255),\n g: Math.round(color.g * 255),\n b: Math.round(color.b * 255),\n a: color.a\n }\n}\n\nexport function colorToCSS(color: Color): string {\n return formatRgb({ mode: 'rgb', r: color.r, g: color.g, b: color.b, alpha: color.a })\n}\n\nexport function colorToCSSCompact(color: Color): string {\n const { r, g, b } = colorToRgba255(color)\n const a = Number(color.a.toFixed(3))\n if (a >= 1) return `rgb(${r},${g},${b})`\n return `rgba(${r},${g},${b},${a})`\n}\n\nexport function rgba255ToColor(r: number, g: number, b: number, a = 1): Color {\n return { r: r / 255, g: g / 255, b: b / 255, a }\n}\n\nexport function colorToFill(color: string | Color) {\n const rgba = typeof color === 'string' ? parseColor(color) : color\n return {\n type: 'SOLID' as const,\n color: { r: rgba.r, g: rgba.g, b: rgba.b, a: rgba.a },\n opacity: rgba.a,\n visible: true\n }\n}\n\nconst euclideanRGB255 = differenceEuclidean('rgb')\n\nexport function colorDistance(c1: Color, c2: Color): number {\n return (\n euclideanRGB255(\n { mode: 'rgb', r: c1.r, g: c1.g, b: c1.b },\n { mode: 'rgb', r: c2.r, g: c2.g, b: c2.b }\n ) * 255\n )\n}\nexport * from './schema'\n"],"mappings":";;;;;;;;AAYA,MAAM,QAAQ,UAAU,KAAK;;AAG7B,SAAgB,cAAc,OAA6B;CACzD,MAAM,SAAS,MAAM,KAAK;CAC1B,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,MAAM,MAAM,MAAM;CAExB,OAAO,eAAe;EAAE,GAAG,IAAI;EAAG,GAAG,IAAI;EAAG,GAAG,IAAI;EAAG,GAAG,OAAO;CAAM,CAAC;AACzE;;AAGA,SAAgB,WAAW,OAAsB;CAC/C,OAAO,cAAc,KAAK,KAAK,EAAE,GAAG,MAAM;AAC5C;AAEA,SAAgB,WAAW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AAO,OAAO,UAAU,WAAW,WAAW,KAAK,IAAI;CAC7D,OAAO;EACL,MAAM;EACN,OAAO;GAAE,GAAG,KAAK;GAAG,GAAG,KAAK;GAAG,GAAG,KAAK;GAAG,GAAG,KAAK;EAAE;EACpD,SAAS,KAAK;EACd,SAAS;CACX;AACF;AAEA,MAAM,kBAAkB,oBAAoB,KAAK;AAEjD,SAAgB,cAAc,IAAW,IAAmB;CAC1D,OACE,gBACE;EAAE,MAAM;EAAO,GAAG,GAAG;EAAG,GAAG,GAAG;EAAG,GAAG,GAAG;CAAE,GACzC;EAAE,MAAM;EAAO,GAAG,GAAG;EAAG,GAAG,GAAG;EAAG,GAAG,GAAG;CAAE,CAC3C,IAAI;AAER"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"management.d.ts","names":[],"sources":["../../src/color/management.ts"],"mappings":";;;;KAOY;KACA;UAEK;EACf,aAAa;EACb,qBAAqB;;UAGN;EACf,OAAO;EACP;EACA,aAAa;EACb,aAAa;EACb;;
|
|
1
|
+
{"version":3,"file":"management.d.ts","names":[],"sources":["../../src/color/management.ts"],"mappings":";;;;KAOY;KACA;UAEK;EACf,aAAa;EACb,qBAAqB;;UAGN;EACf,OAAO;EACP;EACA,aAAa;EACb,aAAa;EACb;;iBA2Ec,uBACd,OAAO,YACP,UAAU,sBACT;;;;;;iBA2Da,sBAAsB,gBAAgB;iBActC,sBACd,OAAO,OACP,UAAU,sBACT;iBAaa,qBACd,MAAM,MACN,mBACA,MAAM,WACN,UAAU,sBACT;iBAMa,uBACd,QAAQ,QACR,qBACA,MAAM,WACN,UAAU,sBACT;iBAMa,kBAAkB,OAAO,OAAO,UAAU;iBAI1C,8BAA8B"}
|
package/dist/color/management.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { normalizeColor } from "./normalize.js";
|
|
2
2
|
import { getFillOkHCL, getStrokeOkHCL } from "./okhcl.js";
|
|
3
|
-
import { converter, formatCss, formatRgb, inGamut, parse, toGamut } from "culori";
|
|
3
|
+
import { clampGamut, converter, formatCss, formatRgb, inGamut, parse, toGamut } from "culori";
|
|
4
4
|
//#region src/color/management.ts
|
|
5
5
|
const DEFAULT_COLOR_SPACE = "srgb";
|
|
6
6
|
const toRGB = converter("rgb");
|
|
@@ -8,6 +8,7 @@ const toP3 = converter("p3");
|
|
|
8
8
|
const toDisplayableRGB = toGamut("rgb", "oklch");
|
|
9
9
|
const toDisplayableP3 = toGamut("p3", "oklch");
|
|
10
10
|
const isDisplayableRGB = inGamut("rgb");
|
|
11
|
+
const clampToRGB = clampGamut("rgb");
|
|
11
12
|
const isDisplayableP3 = inGamut("p3");
|
|
12
13
|
function normalizeOkLCH(color) {
|
|
13
14
|
const hue = color.h % 360;
|
|
@@ -145,7 +146,8 @@ function resolveOkHCLForPreview(color, options) {
|
|
|
145
146
|
function parseDisplayableColor(input) {
|
|
146
147
|
const parsed = parse(input);
|
|
147
148
|
if (!parsed) return null;
|
|
148
|
-
const rgb = isDisplayableRGB(parsed) ? toRGB(parsed) : toDisplayableRGB(parsed);
|
|
149
|
+
const rgb = isDisplayableRGB(parsed) ? toRGB(parsed) : clampToRGB(parsed.mode === "rgb" ? parsed : toDisplayableRGB(parsed));
|
|
150
|
+
if (!rgb) return null;
|
|
149
151
|
return normalizeColor({
|
|
150
152
|
r: rgb.r,
|
|
151
153
|
g: rgb.g,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"management.js","names":[],"sources":["../../src/color/management.ts"],"sourcesContent":["import { converter, formatCss, formatRgb, inGamut, parse, toGamut } from 'culori'\n\nimport type { Color } from '../primitives'\nimport type { DocumentColorSpace, Fill, SceneNode, Stroke } from '../types'\nimport { normalizeColor } from './normalize'\nimport { getFillOkHCL, getStrokeOkHCL, type OkHCLColor } from './okhcl'\n\nexport type RenderColorSpace = 'srgb' | 'display-p3'\nexport type ColorIntentSpace = 'oklch' | 'srgb'\n\nexport interface ColorPreviewOptions {\n colorSpace?: RenderColorSpace\n documentColorSpace?: DocumentColorSpace\n}\n\nexport interface ResolvedRenderColor {\n color: Color\n cssColor: string\n sourceSpace: ColorIntentSpace\n targetSpace: RenderColorSpace\n clipped: boolean\n}\n\nconst DEFAULT_COLOR_SPACE: RenderColorSpace = 'srgb'\n\nconst toRGB = converter('rgb')\nconst toP3 = converter('p3')\nconst toDisplayableRGB = toGamut('rgb', 'oklch')\nconst toDisplayableP3 = toGamut('p3', 'oklch')\nconst isDisplayableRGB = inGamut('rgb')\nconst isDisplayableP3 = inGamut('p3')\n\nfunction normalizeOkLCH(color: OkHCLColor) {\n const hue = color.h % 360\n return {\n mode: 'oklch' as const,\n l: Math.max(0, Math.min(1, color.l)),\n c: Math.max(0, color.c),\n h: hue < 0 ? hue + 360 : hue,\n alpha: Math.max(0, Math.min(1, color.a ?? 1))\n }\n}\n\n/**\n * Numbers are stored in the document's profile, so painting into a surface with a different\n * profile has to convert them. Same profile means no work, which is the common case.\n */\nfunction convertComponents(color: Color, from: RenderColorSpace, to: RenderColorSpace): Color {\n if (from === to) return color\n const source =\n from === 'display-p3'\n ? { mode: 'p3' as const, r: color.r, g: color.g, b: color.b, alpha: color.a }\n : { mode: 'rgb' as const, r: color.r, g: color.g, b: color.b, alpha: color.a }\n const converted = to === 'display-p3' ? toP3(source) : toRGB(source)\n return normalizeColor({\n r: converted.r,\n g: converted.g,\n b: converted.b,\n a: converted.alpha ?? color.a\n })\n}\n\nfunction isOutsideGamut(color: Color, space: RenderColorSpace): boolean {\n if (space === 'display-p3') {\n return !isDisplayableP3({ mode: 'p3', r: color.r, g: color.g, b: color.b, alpha: color.a })\n }\n return !isDisplayableRGB({ mode: 'rgb', r: color.r, g: color.g, b: color.b, alpha: color.a })\n}\n\nfunction resolveTargetSpace(options?: ColorPreviewOptions): RenderColorSpace {\n return options?.colorSpace ?? options?.documentColorSpace ?? DEFAULT_COLOR_SPACE\n}\n\nfunction formatCSSForTarget(color: Color, targetSpace: RenderColorSpace): string {\n if (targetSpace === 'display-p3') {\n const p3 = toP3({ mode: 'rgb', r: color.r, g: color.g, b: color.b, alpha: color.a })\n return formatCss({\n mode: 'p3',\n r: p3.r,\n g: p3.g,\n b: p3.b,\n alpha: p3.alpha ?? color.a\n })\n }\n\n return formatRgb({\n mode: 'rgb',\n r: color.r,\n g: color.g,\n b: color.b,\n alpha: color.a\n })\n}\n\nexport function resolveOkHCLForPreview(\n color: OkHCLColor,\n options?: ColorPreviewOptions\n): ResolvedRenderColor {\n const oklch = normalizeOkLCH(color)\n const targetSpace = resolveTargetSpace(options)\n\n if (targetSpace === 'display-p3') {\n const clipped = !isDisplayableP3(oklch)\n const p3 = toP3(toDisplayableP3(oklch))\n // P3 coordinates, because the caller asked for a P3 target.\n const resolved = normalizeColor({\n r: p3.r,\n g: p3.g,\n b: p3.b,\n a: p3.alpha ?? oklch.alpha\n })\n\n return {\n color: resolved,\n cssColor: formatCss({\n mode: 'p3',\n r: p3.r,\n g: p3.g,\n b: p3.b,\n alpha: p3.alpha ?? oklch.alpha\n }),\n sourceSpace: 'oklch',\n targetSpace,\n clipped\n }\n }\n\n const clipped = !isDisplayableRGB(oklch)\n const rgb = toRGB(toDisplayableRGB(oklch))\n const resolved = normalizeColor({\n r: rgb.r,\n g: rgb.g,\n b: rgb.b,\n a: rgb.alpha ?? oklch.alpha\n })\n\n return {\n color: resolved,\n cssColor: formatRgb({\n mode: 'rgb',\n r: resolved.r,\n g: resolved.g,\n b: resolved.b,\n alpha: resolved.a\n }),\n sourceSpace: 'oklch',\n targetSpace,\n clipped\n }\n}\n\n/**\n * A CSS color in any space, mapped into sRGB the way CSS maps out-of-gamut colors: by reducing\n * chroma in OKLCH, so a Display P3 red becomes the nearest sRGB red, not a clipped one. A missing\n * (`none`) component reads as zero. Null when `input` is not a color.\n */\nexport function parseDisplayableColor(input: string): Color | null {\n const parsed = parse(input)\n if (!parsed) return null\n // Mapping through OKLCH shifts colors already in sRGB by float noise, so only map the rest.\n const rgb = isDisplayableRGB(parsed) ? toRGB(parsed) : toDisplayableRGB(parsed)\n // culori leaves a `none` channel out, which normalizing reads as zero.\n return normalizeColor({ r: rgb.r, g: rgb.g, b: rgb.b, a: parsed.alpha })\n}\n\nexport function resolveRGBAForPreview(\n color: Color,\n options?: ColorPreviewOptions\n): ResolvedRenderColor {\n const documentColorSpace = options?.documentColorSpace ?? DEFAULT_COLOR_SPACE\n const targetSpace = options?.colorSpace ?? documentColorSpace\n const resolved = convertComponents(normalizeColor(color), documentColorSpace, targetSpace)\n return {\n color: resolved,\n cssColor: formatCSSForTarget(resolved, targetSpace),\n sourceSpace: 'srgb',\n targetSpace,\n clipped: targetSpace !== documentColorSpace && isOutsideGamut(resolved, targetSpace)\n }\n}\n\nexport function resolveNodeFillColor(\n fill: Fill,\n fillIndex: number,\n node: SceneNode,\n options?: ColorPreviewOptions\n): ResolvedRenderColor {\n const okhcl = getFillOkHCL(node, fillIndex)?.color\n if (okhcl) return resolveOkHCLForPreview(okhcl, options)\n return resolveRGBAForPreview(fill.color, options)\n}\n\nexport function resolveNodeStrokeColor(\n stroke: Stroke,\n strokeIndex: number,\n node: SceneNode,\n options?: ColorPreviewOptions\n): ResolvedRenderColor {\n const okhcl = getStrokeOkHCL(node, strokeIndex)?.color\n if (okhcl) return resolveOkHCLForPreview(okhcl, options)\n return resolveRGBAForPreview(stroke.color, options)\n}\n\nexport function colorToDisplayCSS(color: Color, options?: ColorPreviewOptions): string {\n return resolveRGBAForPreview(color, options).cssColor\n}\n\nexport function getDefaultRenderColorSpace(): RenderColorSpace {\n return DEFAULT_COLOR_SPACE\n}\n"],"mappings":";;;;AAuBA,MAAM,sBAAwC;AAE9C,MAAM,QAAQ,UAAU,KAAK;AAC7B,MAAM,OAAO,UAAU,IAAI;AAC3B,MAAM,mBAAmB,QAAQ,OAAO,OAAO;AAC/C,MAAM,kBAAkB,QAAQ,MAAM,OAAO;AAC7C,MAAM,mBAAmB,QAAQ,KAAK;AACtC,MAAM,kBAAkB,QAAQ,IAAI;AAEpC,SAAS,e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KAAK;CAC1B,IAAI,CAAC,QAAQ,OAAO;CAEpB,MAAM,MAAM,iBAAiB,MAAM,IAAI,MAAM,MAAM,IAAI,iBAAiB,MAAM;CAE9E,OAAO,eAAe;EAAE,GAAG,IAAI;EAAG,GAAG,IAAI;EAAG,GAAG,IAAI;EAAG,GAAG,OAAO;CAAM,CAAC;AACzE;AAEA,SAAgB,sBACd,OACA,SACqB;CACrB,MAAM,qBAAqB,SAAS,sBAAsB;CAC1D,MAAM,cAAc,SAAS,cAAc;CAC3C,MAAM,WAAW,kBAAkB,eAAe,KAAK,GAAG,oBAAoB,WAAW;CACzF,OAAO;EACL,OAAO;EACP,UAAU,mBAAmB,UAAU,WAAW;EAClD,aAAa;EACb;EACA,SAAS,gBAAgB,sBAAsB,eAAe,UAAU,WAAW;CACrF;AACF;AAEA,SAAgB,qBACd,MACA,WACA,MACA,SACqB;CACrB,MAAM,QAAQ,aAAa,MAAM,SAAS,CAAC,EAAE;CAC7C,IAAI,OAAO,OAAO,uBAAuB,OAAO,OAAO;CACvD,OAAO,sBAAsB,KAAK,OAAO,OAAO;AAClD;AAEA,SAAgB,uBACd,QACA,aACA,MACA,SACqB;CACrB,MAAM,QAAQ,eAAe,MAAM,WAAW,CAAC,EAAE;CACjD,IAAI,OAAO,OAAO,uBAAuB,OAAO,OAAO;CACvD,OAAO,sBAAsB,OAAO,OAAO,OAAO;AACpD;AAEA,SAAgB,kBAAkB,OAAc,SAAuC;CACrF,OAAO,sBAAsB,OAAO,OAAO,CAAC,CAAC;AAC/C;AAEA,SAAgB,6BAA+C;CAC7D,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"management.js","names":[],"sources":["../../src/color/management.ts"],"sourcesContent":["import { clampGamut, converter, formatCss, formatRgb, inGamut, parse, toGamut } from 'culori'\n\nimport type { Color } from '../primitives'\nimport type { DocumentColorSpace, Fill, SceneNode, Stroke } from '../types'\nimport { normalizeColor } from './normalize'\nimport { getFillOkHCL, getStrokeOkHCL, type OkHCLColor } from './okhcl'\n\nexport type RenderColorSpace = 'srgb' | 'display-p3'\nexport type ColorIntentSpace = 'oklch' | 'srgb'\n\nexport interface ColorPreviewOptions {\n colorSpace?: RenderColorSpace\n documentColorSpace?: DocumentColorSpace\n}\n\nexport interface ResolvedRenderColor {\n color: Color\n cssColor: string\n sourceSpace: ColorIntentSpace\n targetSpace: RenderColorSpace\n clipped: boolean\n}\n\nconst DEFAULT_COLOR_SPACE: RenderColorSpace = 'srgb'\n\nconst toRGB = converter('rgb')\nconst toP3 = converter('p3')\nconst toDisplayableRGB = toGamut('rgb', 'oklch')\nconst toDisplayableP3 = toGamut('p3', 'oklch')\nconst isDisplayableRGB = inGamut('rgb')\nconst clampToRGB = clampGamut('rgb')\nconst isDisplayableP3 = inGamut('p3')\n\nfunction normalizeOkLCH(color: OkHCLColor) {\n const hue = color.h % 360\n return {\n mode: 'oklch' as const,\n l: Math.max(0, Math.min(1, color.l)),\n c: Math.max(0, color.c),\n h: hue < 0 ? hue + 360 : hue,\n alpha: Math.max(0, Math.min(1, color.a ?? 1))\n }\n}\n\n/**\n * Numbers are stored in the document's profile, so painting into a surface with a different\n * profile has to convert them. Same profile means no work, which is the common case.\n */\nfunction convertComponents(color: Color, from: RenderColorSpace, to: RenderColorSpace): Color {\n if (from === to) return color\n const source =\n from === 'display-p3'\n ? { mode: 'p3' as const, r: color.r, g: color.g, b: color.b, alpha: color.a }\n : { mode: 'rgb' as const, r: color.r, g: color.g, b: color.b, alpha: color.a }\n const converted = to === 'display-p3' ? toP3(source) : toRGB(source)\n return normalizeColor({\n r: converted.r,\n g: converted.g,\n b: converted.b,\n a: converted.alpha ?? color.a\n })\n}\n\nfunction isOutsideGamut(color: Color, space: RenderColorSpace): boolean {\n if (space === 'display-p3') {\n return !isDisplayableP3({ mode: 'p3', r: color.r, g: color.g, b: color.b, alpha: color.a })\n }\n return !isDisplayableRGB({ mode: 'rgb', r: color.r, g: color.g, b: color.b, alpha: color.a })\n}\n\nfunction resolveTargetSpace(options?: ColorPreviewOptions): RenderColorSpace {\n return options?.colorSpace ?? options?.documentColorSpace ?? DEFAULT_COLOR_SPACE\n}\n\nfunction formatCSSForTarget(color: Color, targetSpace: RenderColorSpace): string {\n if (targetSpace === 'display-p3') {\n const p3 = toP3({ mode: 'rgb', r: color.r, g: color.g, b: color.b, alpha: color.a })\n return formatCss({\n mode: 'p3',\n r: p3.r,\n g: p3.g,\n b: p3.b,\n alpha: p3.alpha ?? color.a\n })\n }\n\n return formatRgb({\n mode: 'rgb',\n r: color.r,\n g: color.g,\n b: color.b,\n alpha: color.a\n })\n}\n\nexport function resolveOkHCLForPreview(\n color: OkHCLColor,\n options?: ColorPreviewOptions\n): ResolvedRenderColor {\n const oklch = normalizeOkLCH(color)\n const targetSpace = resolveTargetSpace(options)\n\n if (targetSpace === 'display-p3') {\n const clipped = !isDisplayableP3(oklch)\n const p3 = toP3(toDisplayableP3(oklch))\n // P3 coordinates, because the caller asked for a P3 target.\n const resolved = normalizeColor({\n r: p3.r,\n g: p3.g,\n b: p3.b,\n a: p3.alpha ?? oklch.alpha\n })\n\n return {\n color: resolved,\n cssColor: formatCss({\n mode: 'p3',\n r: p3.r,\n g: p3.g,\n b: p3.b,\n alpha: p3.alpha ?? oklch.alpha\n }),\n sourceSpace: 'oklch',\n targetSpace,\n clipped\n }\n }\n\n const clipped = !isDisplayableRGB(oklch)\n const rgb = toRGB(toDisplayableRGB(oklch))\n const resolved = normalizeColor({\n r: rgb.r,\n g: rgb.g,\n b: rgb.b,\n a: rgb.alpha ?? oklch.alpha\n })\n\n return {\n color: resolved,\n cssColor: formatRgb({\n mode: 'rgb',\n r: resolved.r,\n g: resolved.g,\n b: resolved.b,\n alpha: resolved.a\n }),\n sourceSpace: 'oklch',\n targetSpace,\n clipped\n }\n}\n\n/**\n * A CSS color in any space, mapped into sRGB the way CSS maps out-of-gamut colors: by reducing\n * chroma in OKLCH, so a Display P3 red becomes the nearest sRGB red, not a clipped one. A missing\n * (`none`) component reads as zero. Null when `input` is not a color.\n */\nexport function parseDisplayableColor(input: string): Color | null {\n const parsed = parse(input)\n if (!parsed) return null\n // Mapping through OKLCH shifts colors already in sRGB by float noise, so only map the rest.\n // CSS clamps out-of-range sRGB channels and gamut-maps wider colors; clamping also removes the\n // float noise gamut mapping can leave just outside 0..1.\n const rgb = isDisplayableRGB(parsed)\n ? toRGB(parsed)\n : clampToRGB(parsed.mode === 'rgb' ? parsed : toDisplayableRGB(parsed))\n if (!rgb) return null\n // culori leaves a `none` channel out, which normalizing reads as zero.\n return normalizeColor({ r: rgb.r, g: rgb.g, b: rgb.b, a: parsed.alpha })\n}\n\nexport function resolveRGBAForPreview(\n color: Color,\n options?: ColorPreviewOptions\n): ResolvedRenderColor {\n const documentColorSpace = options?.documentColorSpace ?? DEFAULT_COLOR_SPACE\n const targetSpace = options?.colorSpace ?? documentColorSpace\n const resolved = convertComponents(normalizeColor(color), documentColorSpace, targetSpace)\n return {\n color: resolved,\n cssColor: formatCSSForTarget(resolved, targetSpace),\n sourceSpace: 'srgb',\n targetSpace,\n clipped: targetSpace !== documentColorSpace && isOutsideGamut(resolved, targetSpace)\n }\n}\n\nexport function resolveNodeFillColor(\n fill: Fill,\n fillIndex: number,\n node: SceneNode,\n options?: ColorPreviewOptions\n): ResolvedRenderColor {\n const okhcl = getFillOkHCL(node, fillIndex)?.color\n if (okhcl) return resolveOkHCLForPreview(okhcl, options)\n return resolveRGBAForPreview(fill.color, options)\n}\n\nexport function resolveNodeStrokeColor(\n stroke: Stroke,\n strokeIndex: number,\n node: SceneNode,\n options?: ColorPreviewOptions\n): ResolvedRenderColor {\n const okhcl = getStrokeOkHCL(node, strokeIndex)?.color\n if (okhcl) return resolveOkHCLForPreview(okhcl, options)\n return resolveRGBAForPreview(stroke.color, options)\n}\n\nexport function colorToDisplayCSS(color: Color, options?: ColorPreviewOptions): string {\n return resolveRGBAForPreview(color, options).cssColor\n}\n\nexport function getDefaultRenderColorSpace(): RenderColorSpace {\n return DEFAULT_COLOR_SP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AAEA,SAAgB,kBAAkB,OAAc,SAAuC;CACrF,OAAO,sBAAsB,OAAO,OAAO,CAAC,CAAC;AAC/C;AAEA,SAAgB,6BAA+C;CAC7D,OAAO;AACT"}
|
package/dist/coordinate.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"coordinate.d.ts","names":[],"sources":["../src/coordinate.ts"],"mappings":";;;;;iBAMgB,eAAe,MAAM,WAAW,OAAO,KAAK,yBAAyB;
|
|
1
|
+
{"version":3,"file":"coordinate.d.ts","names":[],"sources":["../src/coordinate.ts"],"mappings":";;;;;iBAMgB,eAAe,MAAM,WAAW,OAAO,KAAK,yBAAyB;iBA2CrE,0BAA0B,MAAM,WAAW,OAAO,KAAK,yBAAsB;;;;;iBAQ7E,uBAAuB,MAAM,KAAK,gCAAgC,OAAO,OAAI;;iBAK7E,qBACd,QAAQ,uBACR,OAAO,KAAK,oCACX;;;;;;;iBAWa,6BACd,gBAAgB,aAChB,kBACA,OAAO,KAAK,oCACX;iBASa,oBAAoB,MAAM,WAAW,OAAO,aAAa;iBASzD,oBAAoB,MAAM,WAAW,OAAO;iBAW5C,wBAAwB,MAAM,WAAW,OAAO;;;;;;;;;;;;iBA2DhD,sBAAsB,MAAM,KAAK,0CAA0C;;KAK/E,gBAAgB,KAC1B;;iBAKc,mBAAmB,GAAG,eAAe,WAAU,SAAU;iBAczD,mBAAmB,MAAM,YAAS;;;;;;;;iBAWlC,gBACd,MAAM,WACN,OAAO,KAAK,wBACZ,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA8CT,iBAAiB,KAAK;;;;;iBAMX,wBACd,MAAM,WACN,OAAO,MACP,aAAa,OACZ;iBAca,kBAAkB,QAAQ;;;;;;;iBAU1B,2BACd,MAAM,WACN,OAAO,KAAK,yBACX"}
|
package/dist/coordinate.js
CHANGED
|
@@ -3,8 +3,10 @@ import { FITTED_CONTAINER_TYPES } from "./node-defaults.js";
|
|
|
3
3
|
//#region src/coordinate.ts
|
|
4
4
|
function getWorldMatrix(node, graph) {
|
|
5
5
|
const chain = [];
|
|
6
|
+
const visited = /* @__PURE__ */ new Set();
|
|
6
7
|
let current = node;
|
|
7
|
-
while (current) {
|
|
8
|
+
while (current && !visited.has(current.id)) {
|
|
9
|
+
visited.add(current.id);
|
|
8
10
|
chain.unshift(current);
|
|
9
11
|
if (!current.parentId) break;
|
|
10
12
|
current = graph.getNode(current.parentId);
|
package/dist/coordinate.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"coordinate.js","names":[],"sources":["../src/coordinate.ts"],"sourcesContent":["import type { SceneGraph } from './graph'\nimport Matrix, { type Mat3 } from './matrix'\nimport { FITTED_CONTAINER_TYPES } from './node-defaults'\nimport type { Rect, Vector } from './primitives'\nimport type { SceneNode } from './types'\n\nexport function getWorldMatrix(node: SceneNode, graph: Pick<SceneGraph, 'getNode'>): Mat3 {\n const chain: SceneNode[] = []\n let current: SceneNode | undefined = node\n\n while (current) {\n chain.unshift(current)\n if (!current.parentId) break\n current = graph.getNode(current.parentId)\n }\n\n let matrix = Matrix.identity()\n\n for (const n of chain) {\n const local = getNodeLocalMatrix(n)\n matrix = Matrix.multiply(matrix, local)\n }\n\n return matrix\n}\n\n/** Axis-aligned box around interleaved `x, y` points; empty input gives an empty box at the origin. */\nfunction boundsOfPoints(points: readonly number[]): Rect {\n if (points.length === 0) return { x: 0, y: 0, width: 0, height: 0 }\n let minX = Infinity\n let minY = Infinity\n let maxX = -Infinity\n let maxY = -Infinity\n for (let i = 0; i < points.length; i += 2) {\n minX = Math.min(minX, points[i])\n minY = Math.min(minY, points[i + 1])\n maxX = Math.max(maxX, points[i])\n maxY = Math.max(maxY, points[i + 1])\n }\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }\n}\n\nfunction cornersOf(node: Pick<SceneNode, 'width' | 'height'>): number[] {\n return [0, 0, node.width, 0, node.width, node.height, 0, node.height]\n}\n\nexport function getAxisAlignedWorldBounds(node: SceneNode, graph: Pick<SceneGraph, 'getNode'>) {\n return getAxisAlignedBoundsAt(node, getWorldMatrix(node, graph))\n}\n\n/**\n * Axis-aligned canvas box of a node drawn with the world matrix `world`, for walks down the tree\n * that compose each child's matrix from its parent's instead of climbing the ancestors again.\n */\nexport function getAxisAlignedBoundsAt(node: Pick<SceneNode, 'width' | 'height'>, world: Mat3) {\n return boundsOfPoints(Matrix.mapPoints(world, cornersOf(node)))\n}\n\n/** World matrix of a parent; the document root and a missing parent are the identity. */\nexport function getParentWorldMatrix(\n parent: SceneNode | undefined,\n graph: Pick<SceneGraph, 'getNode' | 'rootId'>\n): Mat3 {\n if (!parent || parent.id === graph.rootId) return Matrix.identity()\n return getWorldMatrix(parent, graph)\n}\n\n/**\n * Axis-aligned box of `nodes` in `parentId`'s own axes: where a group, frame, or boolean operation\n * made from them sits. Each node's corners are mapped through the parent's inverse world matrix,\n * so a rotated or flipped parent gets a box in its own axes and the nodes keep their drawn places\n * once they move into the container.\n */\nexport function getAxisAlignedBoundsInParent(\n nodes: readonly SceneNode[],\n parentId: string,\n graph: Pick<SceneGraph, 'getNode' | 'rootId'>\n): Rect {\n const toParent =\n Matrix.invert(getParentWorldMatrix(graph.getNode(parentId), graph)) ?? Matrix.identity()\n const points = nodes.flatMap((node) =>\n Matrix.mapPoints(Matrix.multiply(toParent, getWorldMatrix(node, graph)), cornersOf(node))\n )\n return boundsOfPoints(points)\n}\n\nexport function getAbsolutePosition(node: SceneNode, graph: SceneGraph): Vector {\n const matrix = getWorldMatrix(node, graph)\n const p = Matrix.mapPoints(matrix, [0, 0])\n\n return {\n x: p[0],\n y: p[1]\n }\n}\nexport function getAbsoluteRotation(node: SceneNode, graph: SceneGraph): number {\n const matrix = getWorldMatrix(node, graph)\n const a = matrix[0]\n const b = matrix[1]\n const angle = Math.atan2(b, a)\n let deg = (angle * 180) / Math.PI\n deg = (deg + 360) % 360\n\n return deg\n}\n\nexport function getAbsolutePositionFull(node: SceneNode, graph: SceneGraph) {\n const matrix = getWorldMatrix(node, graph)\n\n const origin = Matrix.mapPoints(matrix, [0, 0])\n const x = origin[0]\n const y = origin[1]\n\n const pts = Matrix.mapPoints(matrix, [\n 0,\n 0,\n node.width,\n 0,\n node.width,\n node.height,\n 0,\n node.height\n ])\n\n const [x1, y1, x2, y2, x3, y3, x4, y4] = pts\n\n const minX = Math.min(x1, x2, x3, x4)\n const maxX = Math.max(x1, x2, x3, x4)\n const minY = Math.min(y1, y2, y3, y4)\n const maxY = Math.max(y1, y2, y3, y4)\n\n const width = maxX - minX\n const height = maxY - minY\n\n let angle = Math.atan2(matrix[3], matrix[0])\n\n const det = matrix[0] * matrix[4] - matrix[1] * matrix[3]\n if (det < 0) {\n angle = -angle\n }\n\n const rotation = angle * (180 / Math.PI)\n\n const center = Matrix.mapPoints(matrix, [node.width / 2, node.height / 2])\n\n const centerX = center[0]\n const centerY = center[1]\n\n return {\n x,\n y,\n\n // AABB\n boundX: minX,\n boundY: minY,\n width,\n height,\n\n rotation,\n\n centerX,\n centerY\n }\n}\n/** Lines retain their origin pivot; other shapes rotate around their center. */\nexport function getNodeRotationOrigin(node: Pick<SceneNode, 'type' | 'width' | 'height'>): Vector {\n return node.type === 'LINE' ? { x: 0, y: 0 } : { x: node.width / 2, y: node.height / 2 }\n}\n\n/** What places a layer in its parent: its position, size, reflection, turn, and pivot. */\nexport type NodePlacement = Pick<\n SceneNode,\n 'type' | 'x' | 'y' | 'width' | 'height' | 'rotation' | 'flipX' | 'flipY'\n>\n\n/** Position can be applied separately by renderers before setting up local opacity layers. */\nexport function getNodeLocalMatrix(n: NodePlacement, position: Vector = n) {\n let matrix = Matrix.translated(position.x, position.y)\n if (n.flipX || n.flipY) {\n matrix = Matrix.multiply(\n matrix,\n Matrix.scaled(n.flipX ? -1 : 1, n.flipY ? -1 : 1, n.width / 2, n.height / 2)\n )\n }\n if (n.rotation) {\n const pivot = getNodeRotationOrigin(n)\n matrix = Matrix.multiply(matrix, Matrix.rotated((n.rotation * Math.PI) / 180, pivot.x, pivot.y))\n }\n return matrix\n}\nexport function getNodeWorldBounds(node: SceneNode) {\n return boundsOfPoints(Matrix.mapPoints(getNodeLocalMatrix(node), cornersOf(node)))\n}\n\n/**\n * World-space positions of the 8 selection handles. `localRect` overrides the\n * node-local box the handles sit on — text-on-path draws its handles on the\n * glyph-fitted path box, not node bounds, so its hit-test must pass that box\n * or the visible handles are ~25px off and unclickable. Defaults to full node\n * bounds.\n */\nexport function getWorldHandles(\n node: SceneNode,\n graph: Pick<SceneGraph, 'getNode'>,\n localRect?: Rect\n) {\n const matrix = getWorldMatrix(node, graph)\n\n const x0 = localRect?.x ?? 0\n const y0 = localRect?.y ?? 0\n const w = localRect?.width ?? node.width\n const h = localRect?.height ?? node.height\n const mx = x0 + w / 2\n const my = y0 + h / 2\n const x1 = x0 + w\n const y1 = y0 + h\n\n const localPts = [\n x0,\n y0, // nw\n mx,\n y0, // n\n x1,\n y0, // ne\n x1,\n my, // e\n x1,\n y1, // se\n mx,\n y1, // s\n x0,\n y1, // sw\n x0,\n my // w\n ]\n\n const pts = Matrix.mapPoints(matrix, localPts)\n\n return {\n nw: { x: pts[0], y: pts[1] },\n n: { x: pts[2], y: pts[3] },\n ne: { x: pts[4], y: pts[5] },\n e: { x: pts[6], y: pts[7] },\n se: { x: pts[8], y: pts[9] },\n s: { x: pts[10], y: pts[11] },\n sw: { x: pts[12], y: pts[13] },\n w: { x: pts[14], y: pts[15] }\n }\n}\n\ntype LocalTransform = Pick<SceneNode, 'x' | 'y' | 'rotation' | 'flipX' | 'flipY'>\n\n/**\n * Local transform that draws `node` with the given world matrix once it sits under a parent\n * whose world matrix is `parentWorld`. Keeps the node's own `flipX` when the matrix allows it.\n */\nexport function localTransformFromWorld(\n node: SceneNode,\n world: Mat3,\n parentWorld: Mat3\n): LocalTransform | null {\n const parentInverse = Matrix.invert(parentWorld)\n if (!parentInverse) return null\n const local = Matrix.multiply(parentInverse, world)\n const [a, b, , c, d] = local\n const sx = node.flipX ? -1 : 1\n const sy = a * d - b * c < 0 ? -sx : sx\n let rotation = (Math.atan2(sy * c, sx * a) * 180) / Math.PI\n if (Math.abs(rotation) < 1e-9) rotation = 0\n const transform = { rotation, flipX: sx < 0, flipY: sy < 0 }\n const origin = getNodeLocalMatrix({ ...node, ...transform }, { x: 0, y: 0 })\n return { ...transform, x: local[2] - origin[2], y: local[5] - origin[5] }\n}\n\nexport function isTranslationOnly(matrix: Mat3): boolean {\n return matrix[0] === 1 && matrix[1] === 0 && matrix[3] === 0 && matrix[4] === 1\n}\n\n/**\n * Maps a node's parent space into its container's: through the groups and booleans around it,\n * which set no coordinate space of their own. Figma's plugin API reports `x`, `y`, and\n * `relativeTransform` of their children in the container's space. The identity when the parent is\n * not a group.\n */\nexport function getParentToContainerMatrix(\n node: SceneNode,\n graph: Pick<SceneGraph, 'getNode'>\n): Mat3 {\n let matrix = Matrix.identity()\n for (\n let parent = node.parentId ? graph.getNode(node.parentId) : undefined;\n parent && FITTED_CONTAINER_TYPES.has(parent.type);\n parent = parent.parentId ? graph.getNode(parent.parentId) : undefined\n ) {\n matrix = Matrix.multiply(getNodeLocalMatrix(parent), matrix)\n }\n return matrix\n}\n"],"mappings":";;;AAMA,SAAgB,eAAe,MAAiB,OAA0C;CACxF,MAAM,QAAqB,CAAC;CAC5B,IAAI,UAAiC;CAErC,OAAO,SAAS;EACd,MAAM,QAAQ,OAAO;EACrB,IAAI,CAAC,QAAQ,UAAU;EACvB,UAAU,MAAM,QAAQ,QAAQ,QAAQ;CAC1C;CAEA,IAAI,SAAS,OAAO,SAAS;CAE7B,KAAK,MAAM,KAAK,OAAO;EACrB,MAAM,QAAQ,mBAAmB,CAAC;EAClC,SAAS,OAAO,SAAS,QAAQ,KAAK;CACxC;CAEA,OAAO;AACT;;AAGA,SAAS,eAAe,QAAiC;CACvD,IAAI,OAAO,WAAW,GAAG,OAAO;EAAE,GAAG;EAAG,GAAG;EAAG,OAAO;EAAG,QAAQ;CAAE;CAClE,IAA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O,OAAO,KAAK,OAAO,OAAO;AAChF;;;;;;;AAQA,SAAgB,2BACd,MACA,OACM;CACN,IAAI,SAAS,OAAO,SAAS;CAC7B,KACE,IAAI,SAAS,KAAK,WAAW,MAAM,QAAQ,KAAK,QAAQ,IAAI,KAAA,GAC5D,UAAU,uBAAuB,IAAI,OAAO,IAAI,GAChD,SAAS,OAAO,WAAW,MAAM,QAAQ,OAAO,QAAQ,IAAI,KAAA,GAE5D,SAAS,OAAO,SAAS,mBAAmB,MAAM,GAAG,MAAM;CAE7D,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"coordinate.js","names":[],"sources":["../src/coordinate.ts"],"sourcesContent":["import type { SceneGraph } from './graph'\nimport Matrix, { type Mat3 } from './matrix'\nimport { FITTED_CONTAINER_TYPES } from './node-defaults'\nimport type { Rect, Vector } from './primitives'\nimport type { SceneNode } from './types'\n\nexport function getWorldMatrix(node: SceneNode, graph: Pick<SceneGraph, 'getNode'>): Mat3 {\n const chain: SceneNode[] = []\n const visited = new Set<string>()\n let current: SceneNode | undefined = node\n\n // A parent cycle in bad data must end the walk instead of hanging it.\n while (current && !visited.has(current.id)) {\n visited.add(current.id)\n chain.unshift(current)\n if (!current.parentId) break\n current = graph.getNode(current.parentId)\n }\n\n let matrix = Matrix.identity()\n\n for (const n of chain) {\n const local = getNodeLocalMatrix(n)\n matrix = Matrix.multiply(matrix, local)\n }\n\n return matrix\n}\n\n/** Axis-aligned box around interleaved `x, y` points; empty input gives an empty box at the origin. */\nfunction boundsOfPoints(points: readonly number[]): Rect {\n if (points.length === 0) return { x: 0, y: 0, width: 0, height: 0 }\n let minX = Infinity\n let minY = Infinity\n let maxX = -Infinity\n let maxY = -Infinity\n for (let i = 0; i < points.length; i += 2) {\n minX = Math.min(minX, points[i])\n minY = Math.min(minY, points[i + 1])\n maxX = Math.max(maxX, points[i])\n maxY = Math.max(maxY, points[i + 1])\n }\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }\n}\n\nfunction cornersOf(node: Pick<SceneNode, 'width' | 'height'>): number[] {\n return [0, 0, node.width, 0, node.width, node.height, 0, node.height]\n}\n\nexport function getAxisAlignedWorldBounds(node: SceneNode, graph: Pick<SceneGraph, 'getNode'>) {\n return getAxisAlignedBoundsAt(node, getWorldMatrix(node, graph))\n}\n\n/**\n * Axis-aligned canvas box of a node drawn with the world matrix `world`, for walks down the tree\n * that compose each child's matrix from its parent's instead of climbing the ancestors again.\n */\nexport function getAxisAlignedBoundsAt(node: Pick<SceneNode, 'width' | 'height'>, world: Mat3) {\n return boundsOfPoints(Matrix.mapPoints(world, cornersOf(node)))\n}\n\n/** World matrix of a parent; the document root and a missing parent are the identity. */\nexport function getParentWorldMatrix(\n parent: SceneNode | undefined,\n graph: Pick<SceneGraph, 'getNode' | 'rootId'>\n): Mat3 {\n if (!parent || parent.id === graph.rootId) return Matrix.identity()\n return getWorldMatrix(parent, graph)\n}\n\n/**\n * Axis-aligned box of `nodes` in `parentId`'s own axes: where a group, frame, or boolean operation\n * made from them sits. Each node's corners are mapped through the parent's inverse world matrix,\n * so a rotated or flipped parent gets a box in its own axes and the nodes keep their drawn places\n * once they move into the container.\n */\nexport function getAxisAlignedBoundsInParent(\n nodes: readonly SceneNode[],\n parentId: string,\n graph: Pick<SceneGraph, 'getNode' | 'rootId'>\n): Rect {\n const toParent =\n Matrix.invert(getParentWorldMatrix(graph.getNode(parentId), graph)) ?? Matrix.identity()\n const points = nodes.flatMap((node) =>\n Matrix.mapPoints(Matrix.multiply(toParent, getWorldMatrix(node, graph)), cornersOf(node))\n )\n return boundsOfPoints(points)\n}\n\nexport function getAbsolutePosition(node: SceneNode, graph: SceneGraph): Vector {\n const matrix = getWorldMatrix(node, graph)\n const p = Matrix.mapPoints(matrix, [0, 0])\n\n return {\n x: p[0],\n y: p[1]\n }\n}\nexport function getAbsoluteRotation(node: SceneNode, graph: SceneGraph): number {\n const matrix = getWorldMatrix(node, graph)\n const a = matrix[0]\n const b = matrix[1]\n const angle = Math.atan2(b, a)\n let deg = (angle * 180) / Math.PI\n deg = (deg + 360) % 360\n\n return deg\n}\n\nexport function getAbsolutePositionFull(node: SceneNode, graph: SceneGraph) {\n const matrix = getWorldMatrix(node, graph)\n\n const origin = Matrix.mapPoints(matrix, [0, 0])\n const x = origin[0]\n const y = origin[1]\n\n const pts = Matrix.mapPoints(matrix, [\n 0,\n 0,\n node.width,\n 0,\n node.width,\n node.height,\n 0,\n node.height\n ])\n\n const [x1, y1, x2, y2, x3, y3, x4, y4] = pts\n\n const minX = Math.min(x1, x2, x3, x4)\n const maxX = Math.max(x1, x2, x3, x4)\n const minY = Math.min(y1, y2, y3, y4)\n const maxY = Math.max(y1, y2, y3, y4)\n\n const width = maxX - minX\n const height = maxY - minY\n\n let angle = Math.atan2(matrix[3], matrix[0])\n\n const det = matrix[0] * matrix[4] - matrix[1] * matrix[3]\n if (det < 0) {\n angle = -angle\n }\n\n const rotation = angle * (180 / Math.PI)\n\n const center = Matrix.mapPoints(matrix, [node.width / 2, node.height / 2])\n\n const centerX = center[0]\n const centerY = center[1]\n\n return {\n x,\n y,\n\n // AABB\n boundX: minX,\n boundY: minY,\n width,\n height,\n\n rotation,\n\n centerX,\n centerY\n }\n}\n/** Lines retain their origin pivot; other shapes rotate around their center. */\nexport function getNodeRotationOrigin(node: Pick<SceneNode, 'type' | 'width' | 'height'>): Vector {\n return node.type === 'LINE' ? { x: 0, y: 0 } : { x: node.width / 2, y: node.height / 2 }\n}\n\n/** What places a layer in its parent: its position, size, reflection, turn, and pivot. */\nexport type NodePlacement = Pick<\n SceneNode,\n 'type' | 'x' | 'y' | 'width' | 'height' | 'rotation' | 'flipX' | 'flipY'\n>\n\n/** Position can be applied separately by renderers before setting up local opacity layers. */\nexport function getNodeLocalMatrix(n: NodePlacement, position: Vector = n) {\n let matrix = Matrix.translated(position.x, position.y)\n if (n.flipX || n.flipY) {\n matrix = Matrix.multiply(\n matrix,\n Matrix.scaled(n.flipX ? -1 : 1, n.flipY ? -1 : 1, n.width / 2, n.height / 2)\n )\n }\n if (n.rotation) {\n const pivot = getNodeRotationOrigin(n)\n matrix = Matrix.multiply(matrix, Matrix.rotated((n.rotation * Math.PI) / 180, pivot.x, pivot.y))\n }\n return matrix\n}\nexport function getNodeWorldBounds(node: SceneNode) {\n return boundsOfPoints(Matrix.mapPoints(getNodeLocalMatrix(node), cornersOf(node)))\n}\n\n/**\n * World-space positions of the 8 selection handles. `localRect` overrides the\n * node-local box the handles sit on — text-on-path draws its handles on the\n * glyph-fitted path box, not node bounds, so its hit-test must pass that box\n * or the visible handles are ~25px off and unclickable. Defaults to full node\n * bounds.\n */\nexport function getWorldHandles(\n node: SceneNode,\n graph: Pick<SceneGraph, 'getNode'>,\n localRect?: Rect\n) {\n const matrix = getWorldMatrix(node, graph)\n\n const x0 = localRect?.x ?? 0\n const y0 = localRect?.y ?? 0\n const w = localRect?.width ?? node.width\n const h = localRect?.height ?? node.height\n const mx = x0 + w / 2\n const my = y0 + h / 2\n const x1 = x0 + w\n const y1 = y0 + h\n\n const localPts = [\n x0,\n y0, // nw\n mx,\n y0, // n\n x1,\n y0, // ne\n x1,\n my, // e\n x1,\n y1, // se\n mx,\n y1, // s\n x0,\n y1, // sw\n x0,\n my // w\n ]\n\n const pts = Matrix.mapPoints(matrix, localPts)\n\n return {\n nw: { x: pts[0], y: pts[1] },\n n: { x: pts[2], y: pts[3] },\n ne: { x: pts[4], y: pts[5] },\n e: { x: pts[6], y: pts[7] },\n se: { x: pts[8], y: pts[9] },\n s: { x: pts[10], y: pts[11] },\n sw: { x: pts[12], y: pts[13] },\n w: { x: pts[14], y: pts[15] }\n }\n}\n\ntype LocalTransform = Pick<SceneNode, 'x' | 'y' | 'rotation' | 'flipX' | 'flipY'>\n\n/**\n * Local transform that draws `node` with the given world matrix once it sits under a parent\n * whose world matrix is `parentWorld`. Keeps the node's own `flipX` when the matrix allows it.\n */\nexport function localTransformFromWorld(\n node: SceneNode,\n world: Mat3,\n parentWorld: Mat3\n): LocalTransform | null {\n const parentInverse = Matrix.invert(parentWorld)\n if (!parentInverse) return null\n const local = Matrix.multiply(parentInverse, world)\n const [a, b, , c, d] = local\n const sx = node.flipX ? -1 : 1\n const sy = a * d - b * c < 0 ? -sx : sx\n let rotation = (Math.atan2(sy * c, sx * a) * 180) / Math.PI\n if (Math.abs(rotation) < 1e-9) rotation = 0\n const transform = { rotation, flipX: sx < 0, flipY: sy < 0 }\n const origin = getNodeLocalMatrix({ ...node, ...transform }, { x: 0, y: 0 })\n return { ...transform, x: local[2] - origin[2], y: local[5] - origin[5] }\n}\n\nexport function isTranslationOnly(matrix: Mat3): boolean {\n return matrix[0] === 1 && matrix[1] === 0 && matrix[3] === 0 && matrix[4] === 1\n}\n\n/**\n * Maps a node's parent space into its container's: through the groups and booleans around it,\n * which set no coordinate space of their own. Figma's plugin API reports `x`, `y`, and\n * `relativeTransform` of their children in the container's space. The identity when the parent is\n * not a group.\n */\nexport function getParentToContainerMatrix(\n node: SceneNode,\n graph: Pick<SceneGraph, 'getNode'>\n): Mat3 {\n let matrix = Matrix.identity()\n for (\n let parent = node.parentId ? graph.getNode(node.parentId) : undefined;\n parent && FITTED_CONTAINER_TYPES.has(parent.type);\n parent = parent.parentId ? graph.getNode(parent.parentId) : undefined\n ) {\n matrix = Matrix.multiply(getNodeLocalMatrix(parent), matrix)\n }\n return matrix\n}\n"],"mappings":";;;AAMA,SAAgB,eAAe,MAAiB,OAA0C;CACxF,MAAM,QAAqB,CAAC;CAC5B,MAAM,0BAAU,IAAI,IAAY;CAChC,IAAI,UAAiC;CAGrC,OAAO,WAAW,CAAC,QAAQ,IAAI,QAAQ,EAAE,GAAG;EAC1C,QAAQ,IAAI,QAAQ,EAAE;EACtB,MAAM,QAAQ,OAAO;EACrB,IAAI,CAAC,QAAQ,UAAU;EACvB,UAAU,MAAM,QAAQ,QAAQ,QAAQ;CAC1C;CAEA,IAAI,SAAS,OAAO,SAAS;CAE7B,KAAK,MAAM,KAAK,OAAO;EACrB,MAAM,QAAQ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EAAG,GAAG;CAAE,CAAC;CAC3E,OAAO;EAAE,GAAG;EAAW,GAAG,MAAM,KAAK,OAAO;EAAI,GAAG,MAAM,KAAK,OAAO;CAAG;AAC1E;AAEA,SAAgB,kBAAkB,QAAuB;CACvD,OAAO,OAAO,OAAO,KAAK,OAAO,OAAO,KAAK,OAAO,OAAO,KAAK,OAAO,OAAO;AAChF;;;;;;;AAQA,SAAgB,2BACd,MACA,OACM;CACN,IAAI,SAAS,OAAO,SAAS;CAC7B,KACE,IAAI,SAAS,KAAK,WAAW,MAAM,QAAQ,KAAK,QAAQ,IAAI,KAAA,GAC5D,UAAU,uBAAuB,IAAI,OAAO,IAAI,GAChD,SAAS,OAAO,WAAW,MAAM,QAAQ,OAAO,QAAQ,IAAI,KAAA,GAE5D,SAAS,OAAO,SAAS,mBAAmB,MAAM,GAAG,MAAM;CAE7D,OAAO;AACT"}
|
package/dist/copy.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"copy.d.ts","names":[],"sources":["../src/copy.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"copy.d.ts","names":[],"sources":["../src/copy.ts"],"mappings":";;;iBAiCgB,SAAS,UAAU,MAAM,GAAG,IAAI;iBAehC,WAAW,GAAG,SAAS;iBAQvB,WAAW,GAAG,SAAS;iBAWvB,aAAa,GAAG,WAAW;;iBA6B3B,eAAe,kBAAkB,QAAQ,GAAG,MAAM,IAAI;;iBAMtD,kBAAkB,cAAc;iBAKhC,UAAU,OAAO,SAAS;iBAI1B,YAAY,SAAS,WAAW;iBAIhC,YAAY,SAAS,WAAW;iBAIhC,gBAAgB,OAAO,eAAe;iBAItC,cAAc,MAAM,aAAa;iBAajC,kBAAkB,OAAO,iBAAiB;;;;;;;iBAU1C,sBACd,MAAM,YACN,aACA,aACA,aACA,aACA,aACA,cACC;iBAoBa,uBACd,OAAO,gBACP,aACA,aACA,aACA,aACA,aACA,cACC;;;;;iBAUa,mBAAmB,OAAO,gBAAgB,YAAY,aAAa;;iBAmCnE,kBAAkB,QAAQ,4BAA4B;iBAatD,sBAAsB,UAAU,oBAAoB;;;;;;;;KAiBxD;iBAUI,eACd,KAAK,WACL,4BACA,OAAM,gBACL,QAAQ"}
|
package/dist/copy.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { normalizeEffects } from "./effects.js";
|
|
1
2
|
import { cloneInstanceOverrideState } from "./instances/overrides.js";
|
|
2
3
|
import { createDefaultSourceMetadata } from "./node-defaults.js";
|
|
3
4
|
import { geometryCommandCoordCount } from "./geometry.js";
|
|
@@ -35,10 +36,12 @@ function copyStroke(s) {
|
|
|
35
36
|
}
|
|
36
37
|
function copyEffect(e) {
|
|
37
38
|
if (e.type === "SHADER") return structuredClone(e);
|
|
39
|
+
const normalized = normalizeEffects([e])[0] ?? e;
|
|
40
|
+
if (normalized.type === "SHADER") return structuredClone(normalized);
|
|
38
41
|
return {
|
|
39
|
-
...
|
|
40
|
-
color: { ...
|
|
41
|
-
offset: { ...
|
|
42
|
+
...normalized,
|
|
43
|
+
color: { ...normalized.color },
|
|
44
|
+
offset: { ...normalized.offset }
|
|
42
45
|
};
|
|
43
46
|
}
|
|
44
47
|
function copyStyleRun(r) {
|
|
@@ -56,6 +59,7 @@ function copyStyleRun(r) {
|
|
|
56
59
|
if (r.style.lineHeight) copy.style.lineHeight = { ...r.style.lineHeight };
|
|
57
60
|
if (r.style.letterSpacing) copy.style.letterSpacing = { ...r.style.letterSpacing };
|
|
58
61
|
if (r.style.boundVariables) copy.style.boundVariables = { ...r.style.boundVariables };
|
|
62
|
+
if (r.style.variableBindingScales) copy.style.variableBindingScales = { ...r.style.variableBindingScales };
|
|
59
63
|
return copy;
|
|
60
64
|
}
|
|
61
65
|
const internalCopySources = /* @__PURE__ */ new WeakMap();
|
package/dist/copy.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"copy.js","names":[],"sources":["../src/copy.ts"],"sourcesContent":["/**\n * Typed shallow-copy helpers for Fill, Stroke, Effect, and StyleRun.\n *\n * These replace `structuredClone` for known scene-graph array types,\n * avoiding the ~24× overhead of the generic deep-clone algorithm.\n * Each helper spreads the top-level object and any nested objects\n * (color, offset, gradientStops, dashPattern, style) to ensure\n * no shared references between source and copy.\n */\n\nimport { geometryCommandCoordCount } from './geometry'\nimport { cloneInstanceOverrideState } from './instances/overrides'\nimport { createDefaultSourceMetadata } from './node-defaults'\nimport type {\n ArcData,\n ComponentPropertyDefinition,\n ConnectorEndpoint,\n Effect,\n DerivedTextGlyph,\n Fill,\n GeometryPath,\n GradientStop,\n LayoutGrid,\n SceneNode,\n Stroke,\n StyleRun\n} from './types'\nimport { cloneVectorNetwork } from './vector-network'\n\n// --- Individual copy functions ---\n\n/** Generic over the paint shape so a stroke keeps its own fields while the paint deep-copies. */\nexport function copyFill<T extends Fill>(f: T): T {\n const copy: T = { ...f, color: { ...f.color } }\n if (f.gradientStops) copy.gradientStops = f.gradientStops.map(copyGradientStop)\n if (f.gradientTransform) copy.gradientTransform = { ...f.gradientTransform }\n if (f.meshPoints) {\n copy.meshPoints = f.meshPoints.map((point) => ({\n position: { ...point.position },\n color: { ...point.color }\n }))\n }\n if (f.patternSpacing) copy.patternSpacing = { ...f.patternSpacing }\n if (f.noiseSize) copy.noiseSize = { ...f.noiseSize }\n return copy\n}\n\nexport function copyStroke(s: Stroke): Stroke {\n const copy = copyFill(s)\n if (s.dashPattern) {\n copy.dashPattern = [...s.dashPattern]\n }\n return copy\n}\n\nexport function copyEffect(e: Effect): Effect {\n if (e.type === 'SHADER') return structuredClone(e)\n return {\n ...e,\n color: { ...e.color },\n offset: { ...e.offset }\n }\n}\n\nexport function copyStyleRun(r: StyleRun): StyleRun {\n const copy: StyleRun = {\n ...r,\n style: {\n ...r.style,\n fills: r.style.fills ? r.style.fills.map(copyFill) : undefined,\n textDecorationFills: r.style.textDecorationFills\n ? r.style.textDecorationFills.map(copyFill)\n : undefined,\n fontVariations: r.style.fontVariations\n ? r.style.fontVariations.map((v) => ({ ...v }))\n : undefined,\n fontFeatures: r.style.fontFeatures ? r.style.fontFeatures.map((v) => ({ ...v })) : undefined\n }\n }\n if (r.style.hyperlink) copy.style.hyperlink = { ...r.style.hyperlink }\n if (r.style.lineHeight) copy.style.lineHeight = { ...r.style.lineHeight }\n if (r.style.letterSpacing) copy.style.letterSpacing = { ...r.style.letterSpacing }\n if (r.style.boundVariables) copy.style.boundVariables = { ...r.style.boundVariables }\n return copy\n}\n\n// --- Array copy functions ---\n\nconst internalCopySources = new WeakMap<object, object>()\n\n/** Record immutable lineage for an internal deep copy without sharing mutable values. */\nexport function markCopySource<T extends object>(source: T, copy: T): T {\n internalCopySources.set(copy, internalCopySources.get(source) ?? source)\n return copy\n}\n\n/** Compare internal deep copies in O(1) without traversing large paint or text payloads. */\nexport function hasSameCopySource(left: object, right: object): boolean {\n if (left === right) return true\n return (internalCopySources.get(left) ?? left) === (internalCopySources.get(right) ?? right)\n}\n\nexport function copyFills(fills: Fill[]): Fill[] {\n return fills.map(copyFill)\n}\n\nexport function copyStrokes(strokes: Stroke[]): Stroke[] {\n return strokes.map(copyStroke)\n}\n\nexport function copyEffects(effects: Effect[]): Effect[] {\n return effects.map(copyEffect)\n}\n\nexport function copyLayoutGrids(grids: LayoutGrid[]): LayoutGrid[] {\n return grids.map((grid) => ({ ...grid, color: grid.color ? { ...grid.color } : undefined }))\n}\n\nexport function copyStyleRuns(runs: StyleRun[]): StyleRun[] {\n return runs.map(copyStyleRun)\n}\n\n/** Keep path-level fills across copy/scale/transform (resize snapshots). */\nfunction withPathPaintMeta(path: GeometryPath, commandsBlob: Uint8Array): GeometryPath {\n return {\n windingRule: path.windingRule,\n commandsBlob,\n ...(path.fills ? { fills: copyFills(path.fills) } : {})\n }\n}\n\nexport function copyGeometryPaths(paths: GeometryPath[]): GeometryPath[] {\n return paths.map((p) => withPathPaintMeta(p, p.commandsBlob.slice()))\n}\n\n/**\n * Affine-transform every coordinate pair in a path command blob (returns a\n * copy): (x, y) → (m00·x + m01·y + tx, m10·x + m11·y + ty).\n * Command layout: 1=move/2=line (1 pair), 3=quad (2 pairs), 4=cubic (3 pairs)\n * — font-glyph blobs are quad-heavy, so skipping command 3 desyncs the walk.\n */\nexport function transformGeometryBlob(\n blob: Uint8Array,\n m00: number,\n m01: number,\n m10: number,\n m11: number,\n tx = 0,\n ty = 0\n): Uint8Array {\n const out = blob.slice()\n const dv = new DataView(out.buffer, out.byteOffset, out.byteLength)\n let offset = 0\n while (offset < out.length) {\n const command = out[offset++]\n const coords = geometryCommandCoordCount(command)\n if (coords == null) break\n for (let i = 0; i < coords; i++) {\n if (offset + 8 > out.length) break\n const x = dv.getFloat32(offset, true)\n const y = dv.getFloat32(offset + 4, true)\n dv.setFloat32(offset, m00 * x + m01 * y + tx, true)\n dv.setFloat32(offset + 4, m10 * x + m11 * y + ty, true)\n offset += 8\n }\n }\n return out\n}\n\nexport function transformGeometryPaths(\n paths: GeometryPath[],\n m00: number,\n m01: number,\n m10: number,\n m11: number,\n tx = 0,\n ty = 0\n): GeometryPath[] {\n return paths.map((g) =>\n withPathPaintMeta(g, transformGeometryBlob(g.commandsBlob, m00, m01, m10, m11, tx, ty))\n )\n}\n\n/**\n * Scale path command blob coordinates by (sx, sy).\n * Identity scale returns a deep copy (same as copyGeometryPaths).\n */\nexport function scaleGeometryPaths(paths: GeometryPath[], sx: number, sy: number): GeometryPath[] {\n if (sx === 1 && sy === 1) return copyGeometryPaths(paths)\n return transformGeometryPaths(paths, sx, 0, 0, sy)\n}\n\n// --- Internal helpers ---\n\n/** Copy an optional array: non-empty → mapped, empty → [], undefined → undefined. */\nfunction copyOpt<T, U>(arr: T[] | undefined, fn: (arr: T[]) => U[]): U[] | undefined {\n if (arr === undefined) return undefined\n return arr.length > 0 ? fn(arr) : []\n}\n\nfunction copyGradientStop(gs: GradientStop): GradientStop {\n return { color: { ...gs.color }, position: gs.position }\n}\n\nfunction copySpread<T extends object>(arr: T[] | undefined): T[] {\n return arr?.map((item) => ({ ...item })) ?? []\n}\n\nfunction copyPropertyDefs(\n defs: ComponentPropertyDefinition[] | undefined\n): ComponentPropertyDefinition[] {\n return (\n defs?.map((d) => ({\n ...d,\n variantOptions: d.variantOptions ? [...d.variantOptions] : undefined,\n preferredValues: d.preferredValues ? [...d.preferredValues] : undefined,\n slotSettings: d.slotSettings ? { ...d.slotSettings } : undefined\n })) ?? []\n )\n}\n\n/** Deep-copy path-text glyphs (fresh commandsBlob buffers). */\nexport function copyDerivedGlyphs(glyphs: DerivedTextGlyph[] | null): DerivedTextGlyph[] | null {\n return glyphs\n ? glyphs.map((g) => ({\n ...g,\n commandsBlob: new Uint8Array(g.commandsBlob),\n ...(g.emojiCodePoints ? { emojiCodePoints: [...g.emojiCodePoints] } : {})\n }))\n : null\n}\n\n// --- Complex structure copy functions ---\n// These replace structuredClone for known types, avoiding its ~24× overhead.\n\nexport function copyConnectorEndpoint(endpoint: ConnectorEndpoint): ConnectorEndpoint {\n return { ...endpoint, position: { ...endpoint.position } }\n}\n\nfunction copyArcData(a: ArcData): ArcData {\n return { startingAngle: a.startingAngle, endingAngle: a.endingAngle, innerRadius: a.innerRadius }\n}\n\n// --- Deep-copy clone props ---\n\n/**\n * Build the init props for a deep-copy clone of `src`.\n * Shares logic between SceneGraph.cloneTree and instance child cloning.\n * Explicitly deep-copies all mutable object/array fields that `...rest`\n * would otherwise share by reference. When adding a mutable SceneNode field,\n * add its copy behavior here or document why sharing is intentional.\n */\nexport type NodeCloneMode = 'deep' | 'fig-import'\n\n/** A text's line height and letter spacing, copied so a clone never shares them. */\nfunction copyTextLengths(src: SceneNode): Pick<SceneNode, 'lineHeight' | 'letterSpacing'> {\n return {\n lineHeight: src.lineHeight && { ...src.lineHeight },\n letterSpacing: { ...src.letterSpacing }\n }\n}\n\nexport function cloneNodeProps(\n src: SceneNode,\n componentId: string | null,\n mode: NodeCloneMode = 'deep'\n): Partial<SceneNode> {\n const { id: _, parentId: _p, childIds: _c, ...rest } = src\n if (mode === 'fig-import') {\n return {\n ...rest,\n ...(componentId !== null ? { componentId } : {}),\n source: createDefaultSourceMetadata(),\n boundVariables: { ...src.boundVariables },\n variableBindingScales: { ...src.variableBindingScales },\n variableAssignmentScales: { ...src.variableAssignmentScales },\n variableModes: { ...src.variableModes },\n instanceOverrides: cloneInstanceOverrideState(src.instanceOverrides),\n componentPropertyAssignments: { ...src.componentPropertyAssignments },\n\n componentPropertyValues: { ...src.componentPropertyValues }\n }\n }\n return {\n ...rest,\n ...(componentId !== null ? { componentId } : {}),\n boundVariables: { ...src.boundVariables },\n variableBindingScales: { ...src.variableBindingScales },\n variableAssignmentScales: { ...src.variableAssignmentScales },\n variableModes: { ...src.variableModes },\n instanceOverrides: cloneInstanceOverrideState(src.instanceOverrides),\n fills: copyOpt(src.fills, (value) => markCopySource(value, copyFills(value))),\n\n strokes: copyOpt(src.strokes, (value) => markCopySource(value, copyStrokes(value))),\n effects: copyOpt(src.effects, (value) => markCopySource(value, copyEffects(value))),\n layoutGrids: copyOpt(src.layoutGrids, copyLayoutGrids),\n guides: copyOpt(src.guides, (guides) => guides.map((guide) => ({ ...guide }))),\n styleRuns: copyOpt(src.styleRuns, (value) => markCopySource(value, copyStyleRuns(value))),\n // Generated instance descendants have no independent Figma provenance. Retaining the source\n // component's opaque raw payload here duplicates megabytes of metadata per instance.\n source: componentId === null ? structuredClone(src.source) : createDefaultSourceMetadata(),\n dashPattern: copyOpt(src.dashPattern, (a) => [...a]),\n fontVariations: copyOpt(src.fontVariations, (a) => a.map((v) => ({ ...v }))),\n ...copyTextLengths(src),\n fontFeatures: copyOpt(src.fontFeatures, (a) => a.map((v) => ({ ...v }))),\n textParagraphs: copyOpt(src.textParagraphs, (a) => a.map((v) => ({ ...v }))),\n textDecorationFills: copyOpt(src.textDecorationFills, copyFills),\n fillGeometry: copyOpt(src.fillGeometry, copyGeometryPaths),\n strokeGeometry: copyOpt(src.strokeGeometry, copyGeometryPaths),\n gridTemplateColumns: copySpread(src.gridTemplateColumns),\n gridTemplateRows: copySpread(src.gridTemplateRows),\n componentPropertyDefinitions: copyPropertyDefs(src.componentPropertyDefinitions),\n componentPropertyReferences: copySpread(src.componentPropertyReferences),\n componentPropertyAssignments: { ...src.componentPropertyAssignments },\n symbolLinks: copySpread(src.symbolLinks),\n variantPropSpecs: copySpread(src.variantPropSpecs),\n pluginData: copySpread(src.pluginData),\n pluginRelaunchData: copySpread(src.pluginRelaunchData),\n prototypeReactions: src.prototypeReactions.map((reaction) => structuredClone(reaction)),\n exportSettings: copySpread(src.exportSettings),\n // Generated instance descendants have no status of their own.\n status: componentId === null ? src.status : null,\n componentPropertyValues: { ...src.componentPropertyValues },\n derivedLayout: src.derivedLayout ? { ...src.derivedLayout } : null,\n arcData: src.arcData ? copyArcData(src.arcData) : null,\n vectorNetwork: src.vectorNetwork ? cloneVectorNetwork(src.vectorNetwork) : null,\n textPicture: src.textPicture ? new Uint8Array(src.textPicture) : null,\n derivedTextGlyphs: src.derivedTextGlyphs\n ? markCopySource(src.derivedTextGlyphs, copyDerivedGlyphs(src.derivedTextGlyphs) ?? [])\n : null,\n textPathData: src.textPathData ? structuredClone(src.textPathData) : null,\n textPathBox: src.textPathBox ? { ...src.textPathBox } : null,\n gridPosition: src.gridPosition ? { ...src.gridPosition } : null,\n targetAspectRatio: src.targetAspectRatio ? { ...src.targetAspectRatio } : null,\n connectorStart: src.connectorStart ? copyConnectorEndpoint(src.connectorStart) : null,\n connectorEnd: src.connectorEnd ? copyConnectorEndpoint(src.connectorEnd) : null,\n connectorControlPoints: structuredClone(src.connectorControlPoints),\n connectorCurveHandles: structuredClone(src.connectorCurveHandles),\n connectorLabelPosition: src.connectorLabelPosition ? { ...src.connectorLabelPosition } : null\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgCA,SAAgB,SAAyB,GAAS;CAChD,MAAM,OAAU;EAAE,GAAG;EAAG,OAAO,EAAE,GAAG,EAAE,MAAM;CAAE;CAC9C,IAAI,EAAE,eAAe,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GAAG,IAAI,kBAAkB,IAAI;EAC1E,gBAAgB,IAAI,iBAAiB,sBAAsB,IAAI,cAAc,IAAI;EACjF,cAAc,IAAI,eAAe,sBAAsB,IAAI,YAAY,IAAI;EAC3E,wBAAwB,gBAAgB,IAAI,sBAAsB;EAClE,uBAAuB,gBAAgB,IAAI,qBAAqB;EAChE,wBAAwB,IAAI,yBAAyB,EAAE,GAAG,IAAI,uBAAuB,IAAI;CAC3F;AACF"}
|
|
1
|
+
{"version":3,"file":"copy.js","names":[],"sources":["../src/copy.ts"],"sourcesContent":["/**\n * Typed shallow-copy helpers for Fill, Stroke, Effect, and StyleRun.\n *\n * These replace `structuredClone` for known scene-graph array types,\n * avoiding the ~24× overhead of the generic deep-clone algorithm.\n * Each helper spreads the top-level object and any nested objects\n * (color, offset, gradientStops, dashPattern, style) to ensure\n * no shared references between source and copy.\n */\n\nimport { normalizeEffects } from './effects'\nimport { geometryCommandCoordCount } from './geometry'\nimport { cloneInstanceOverrideState } from './instances/overrides'\nimport { createDefaultSourceMetadata } from './node-defaults'\nimport type {\n ArcData,\n ComponentPropertyDefinition,\n ConnectorEndpoint,\n Effect,\n DerivedTextGlyph,\n Fill,\n GeometryPath,\n GradientStop,\n LayoutGrid,\n SceneNode,\n Stroke,\n StyleRun\n} from './types'\nimport { cloneVectorNetwork } from './vector-network'\n\n// --- Individual copy functions ---\n\n/** Generic over the paint shape so a stroke keeps its own fields while the paint deep-copies. */\nexport function copyFill<T extends Fill>(f: T): T {\n const copy: T = { ...f, color: { ...f.color } }\n if (f.gradientStops) copy.gradientStops = f.gradientStops.map(copyGradientStop)\n if (f.gradientTransform) copy.gradientTransform = { ...f.gradientTransform }\n if (f.meshPoints) {\n copy.meshPoints = f.meshPoints.map((point) => ({\n position: { ...point.position },\n color: { ...point.color }\n }))\n }\n if (f.patternSpacing) copy.patternSpacing = { ...f.patternSpacing }\n if (f.noiseSize) copy.noiseSize = { ...f.noiseSize }\n return copy\n}\n\nexport function copyStroke(s: Stroke): Stroke {\n const copy = copyFill(s)\n if (s.dashPattern) {\n copy.dashPattern = [...s.dashPattern]\n }\n return copy\n}\n\nexport function copyEffect(e: Effect): Effect {\n if (e.type === 'SHADER') return structuredClone(e)\n const normalized = normalizeEffects([e])[0] ?? e\n if (normalized.type === 'SHADER') return structuredClone(normalized)\n return {\n ...normalized,\n color: { ...normalized.color },\n offset: { ...normalized.offset }\n }\n}\n\nexport function copyStyleRun(r: StyleRun): StyleRun {\n const copy: StyleRun = {\n ...r,\n style: {\n ...r.style,\n fills: r.style.fills ? r.style.fills.map(copyFill) : undefined,\n textDecorationFills: r.style.textDecorationFills\n ? r.style.textDecorationFills.map(copyFill)\n : undefined,\n fontVariations: r.style.fontVariations\n ? r.style.fontVariations.map((v) => ({ ...v }))\n : undefined,\n fontFeatures: r.style.fontFeatures ? r.style.fontFeatures.map((v) => ({ ...v })) : undefined\n }\n }\n if (r.style.hyperlink) copy.style.hyperlink = { ...r.style.hyperlink }\n if (r.style.lineHeight) copy.style.lineHeight = { ...r.style.lineHeight }\n if (r.style.letterSpacing) copy.style.letterSpacing = { ...r.style.letterSpacing }\n if (r.style.boundVariables) copy.style.boundVariables = { ...r.style.boundVariables }\n if (r.style.variableBindingScales)\n copy.style.variableBindingScales = { ...r.style.variableBindingScales }\n return copy\n}\n\n// --- Array copy functions ---\n\nconst internalCopySources = new WeakMap<object, object>()\n\n/** Record immutable lineage for an internal deep copy without sharing mutable values. */\nexport function markCopySource<T extends object>(source: T, copy: T): T {\n internalCopySources.set(copy, internalCopySources.get(source) ?? source)\n return copy\n}\n\n/** Compare internal deep copies in O(1) without traversing large paint or text payloads. */\nexport function hasSameCopySource(left: object, right: object): boolean {\n if (left === right) return true\n return (internalCopySources.get(left) ?? left) === (internalCopySources.get(right) ?? right)\n}\n\nexport function copyFills(fills: Fill[]): Fill[] {\n return fills.map(copyFill)\n}\n\nexport function copyStrokes(strokes: Stroke[]): Stroke[] {\n return strokes.map(copyStroke)\n}\n\nexport function copyEffects(effects: Effect[]): Effect[] {\n return effects.map(copyEffect)\n}\n\nexport function copyLayoutGrids(grids: LayoutGrid[]): LayoutGrid[] {\n return grids.map((grid) => ({ ...grid, color: grid.color ? { ...grid.color } : undefined }))\n}\n\nexport function copyStyleRuns(runs: StyleRun[]): StyleRun[] {\n return runs.map(copyStyleRun)\n}\n\n/** Keep path-level fills across copy/scale/transform (resize snapshots). */\nfunction withPathPaintMeta(path: GeometryPath, commandsBlob: Uint8Array): GeometryPath {\n return {\n windingRule: path.windingRule,\n commandsBlob,\n ...(path.fills ? { fills: copyFills(path.fills) } : {})\n }\n}\n\nexport function copyGeometryPaths(paths: GeometryPath[]): GeometryPath[] {\n return paths.map((p) => withPathPaintMeta(p, p.commandsBlob.slice()))\n}\n\n/**\n * Affine-transform every coordinate pair in a path command blob (returns a\n * copy): (x, y) → (m00·x + m01·y + tx, m10·x + m11·y + ty).\n * Command layout: 1=move/2=line (1 pair), 3=quad (2 pairs), 4=cubic (3 pairs)\n * — font-glyph blobs are quad-heavy, so skipping command 3 desyncs the walk.\n */\nexport function transformGeometryBlob(\n blob: Uint8Array,\n m00: number,\n m01: number,\n m10: number,\n m11: number,\n tx = 0,\n ty = 0\n): Uint8Array {\n const out = blob.slice()\n const dv = new DataView(out.buffer, out.byteOffset, out.byteLength)\n let offset = 0\n while (offset < out.length) {\n const command = out[offset++]\n const coords = geometryCommandCoordCount(command)\n if (coords == null) break\n for (let i = 0; i < coords; i++) {\n if (offset + 8 > out.length) break\n const x = dv.getFloat32(offset, true)\n const y = dv.getFloat32(offset + 4, true)\n dv.setFloat32(offset, m00 * x + m01 * y + tx, true)\n dv.setFloat32(offset + 4, m10 * x + m11 * y + ty, true)\n offset += 8\n }\n }\n return out\n}\n\nexport function transformGeometryPaths(\n paths: GeometryPath[],\n m00: number,\n m01: number,\n m10: number,\n m11: number,\n tx = 0,\n ty = 0\n): GeometryPath[] {\n return paths.map((g) =>\n withPathPaintMeta(g, transformGeometryBlob(g.commandsBlob, m00, m01, m10, m11, tx, ty))\n )\n}\n\n/**\n * Scale path command blob coordinates by (sx, sy).\n * Identity scale returns a deep copy (same as copyGeometryPaths).\n */\nexport function scaleGeometryPaths(paths: GeometryPath[], sx: number, sy: number): GeometryPath[] {\n if (sx === 1 && sy === 1) return copyGeometryPaths(paths)\n return transformGeometryPaths(paths, sx, 0, 0, sy)\n}\n\n// --- Internal helpers ---\n\n/** Copy an optional array: non-empty → mapped, empty → [], undefined → undefined. */\nfunction copyOpt<T, U>(arr: T[] | undefined, fn: (arr: T[]) => U[]): U[] | undefined {\n if (arr === undefined) return undefined\n return arr.length > 0 ? fn(arr) : []\n}\n\nfunction copyGradientStop(gs: GradientStop): GradientStop {\n return { color: { ...gs.color }, position: gs.position }\n}\n\nfunction copySpread<T extends object>(arr: T[] | undefined): T[] {\n return arr?.map((item) => ({ ...item })) ?? []\n}\n\nfunction copyPropertyDefs(\n defs: ComponentPropertyDefinition[] | undefined\n): ComponentPropertyDefinition[] {\n return (\n defs?.map((d) => ({\n ...d,\n variantOptions: d.variantOptions ? [...d.variantOptions] : undefined,\n preferredValues: d.preferredValues ? [...d.preferredValues] : undefined,\n slotSettings: d.slotSettings ? { ...d.slotSettings } : undefined\n })) ?? []\n )\n}\n\n/** Deep-copy path-text glyphs (fresh commandsBlob buffers). */\nexport function copyDerivedGlyphs(glyphs: DerivedTextGlyph[] | null): DerivedTextGlyph[] | null {\n return glyphs\n ? glyphs.map((g) => ({\n ...g,\n commandsBlob: new Uint8Array(g.commandsBlob),\n ...(g.emojiCodePoints ? { emojiCodePoints: [...g.emojiCodePoints] } : {})\n }))\n : null\n}\n\n// --- Complex structure copy functions ---\n// These replace structuredClone for known types, avoiding its ~24× overhead.\n\nexport function copyConnectorEndpoint(endpoint: ConnectorEndpoint): ConnectorEndpoint {\n return { ...endpoint, position: { ...endpoint.position } }\n}\n\nfunction copyArcData(a: ArcData): ArcData {\n return { startingAngle: a.startingAngle, endingAngle: a.endingAngle, innerRadius: a.innerRadius }\n}\n\n// --- Deep-copy clone props ---\n\n/**\n * Build the init props for a deep-copy clone of `src`.\n * Shares logic between SceneGraph.cloneTree and instance child cloning.\n * Explicitly deep-copies all mutable object/array fields that `...rest`\n * would otherwise share by reference. When adding a mutable SceneNode field,\n * add its copy behavior here or document why sharing is intentional.\n */\nexport type NodeCloneMode = 'deep' | 'fig-import'\n\n/** A text's line height and letter spacing, copied so a clone never shares them. */\nfunction copyTextLengths(src: SceneNode): Pick<SceneNode, 'lineHeight' | 'letterSpacing'> {\n return {\n lineHeight: src.lineHeight && { ...src.lineHeight },\n letterSpacing: { ...src.letterSpacing }\n }\n}\n\nexport function cloneNodeProps(\n src: SceneNode,\n componentId: string | null,\n mode: NodeCloneMode = 'deep'\n): Partial<SceneNode> {\n const { id: _, parentId: _p, childIds: _c, ...rest } = src\n if (mode === 'fig-import') {\n return {\n ...rest,\n ...(componentId !== null ? { componentId } : {}),\n source: createDefaultSourceMetadata(),\n boundVariables: { ...src.boundVariables },\n variableBindingScales: { ...src.variableBindingScales },\n variableAssignmentScales: { ...src.variableAssignmentScales },\n variableModes: { ...src.variableModes },\n instanceOverrides: cloneInstanceOverrideState(src.instanceOverrides),\n componentPropertyAssignments: { ...src.componentPropertyAssignments },\n\n componentPropertyValues: { ...src.componentPropertyValues }\n }\n }\n return {\n ...rest,\n ...(componentId !== null ? { componentId } : {}),\n boundVariables: { ...src.boundVariables },\n variableBindingScales: { ...src.variableBindingScales },\n variableAssignmentScales: { ...src.variableAssignmentScales },\n variableModes: { ...src.variableModes },\n instanceOverrides: cloneInstanceOverrideState(src.instanceOverrides),\n fills: copyOpt(src.fills, (value) => markCopySource(value, copyFills(value))),\n\n strokes: copyOpt(src.strokes, (value) => markCopySource(value, copyStrokes(value))),\n effects: copyOpt(src.effects, (value) => markCopySource(value, copyEffects(value))),\n layoutGrids: copyOpt(src.layoutGrids, copyLayoutGrids),\n guides: copyOpt(src.guides, (guides) => guides.map((guide) => ({ ...guide }))),\n styleRuns: copyOpt(src.styleRuns, (value) => markCopySource(value, copyStyleRuns(value))),\n // Generated instance descendants have no independent Figma provenance. Retaining the source\n // component's opaque raw payload here duplicates megabytes of metadata per instance.\n source: componentId === null ? structuredClone(src.source) : createDefaultSourceMetadata(),\n dashPattern: copyOpt(src.dashPattern, (a) => [...a]),\n fontVariations: copyOpt(src.fontVariations, (a) => a.map((v) => ({ ...v }))),\n ...copyTextLengths(src),\n fontFeatures: copyOpt(src.fontFeatures, (a) => a.map((v) => ({ ...v }))),\n textParagraphs: copyOpt(src.textParagraphs, (a) => a.map((v) => ({ ...v }))),\n textDecorationFills: copyOpt(src.textDecorationFills, copyFills),\n fillGeometry: copyOpt(src.fillGeometry, copyGeometryPaths),\n strokeGeometry: copyOpt(src.strokeGeometry, copyGeometryPaths),\n gridTemplateColumns: copySpread(src.gridTemplateColumns),\n gridTemplateRows: copySpread(src.gridTemplateRows),\n componentPropertyDefinitions: copyPropertyDefs(src.componentPropertyDefinitions),\n componentPropertyReferences: copySpread(src.componentPropertyReferences),\n componentPropertyAssignments: { ...src.componentPropertyAssignments },\n symbolLinks: copySpread(src.symbolLinks),\n variantPropSpecs: copySpread(src.variantPropSpecs),\n pluginData: copySpread(src.pluginData),\n pluginRelaunchData: copySpread(src.pluginRelaunchData),\n prototypeReactions: src.prototypeReactions.map((reaction) => structuredClone(reaction)),\n exportSettings: copySpread(src.exportSettings),\n // Generated instance descendants have no status of their own.\n status: componentId === null ? src.status : null,\n componentPropertyValues: { ...src.componentPropertyValues },\n derivedLayout: src.derivedLayout ? { ...src.derivedLayout } : null,\n arcData: src.arcData ? copyArcData(src.arcData) : null,\n vectorNetwork: src.vectorNetwork ? cloneVectorNetwork(src.vectorNetwork) : null,\n textPicture: src.textPicture ? new Uint8Array(src.textPicture) : null,\n derivedTextGlyphs: src.derivedTextGlyphs\n ? markCopySource(src.derivedTextGlyphs, copyDerivedGlyphs(src.derivedTextGlyphs) ?? [])\n : null,\n textPathData: src.textPathData ? structuredClone(src.textPathData) : null,\n textPathBox: src.textPathBox ? { ...src.textPathBox } : null,\n gridPosition: src.gridPosition ? { ...src.gridPosition } : null,\n targetAspectRatio: src.targetAspectRatio ? { ...src.targetAspectRatio } : null,\n connectorStart: src.connectorStart ? copyConnectorEndpoint(src.connectorStart) : null,\n connectorEnd: src.connectorEnd ? copyConnectorEndpoint(src.connectorEnd) : null,\n connectorControlPoints: structuredClone(src.connectorControlPoints),\n connectorCurveHandles: structuredClone(src.connectorCurveHandles),\n connectorLabelPosition: src.connectorLabelPosition ? { ...src.connectorLabelPosition } : null\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiCA,SAAgB,SAAyB,GAAS;CAChD,MAAM,OAAU;EAAE,GAAG;EAAG,OAAO,EAAE,GAAG,EAAE,MAAM;CAAE;CAC9C,IAAI,EAAE,eAAe,KAAK,gBAAgB,EAAE,cAAc,IAAI,gBAAgB;CAC9E,IAAI,EAAE,mBAAmB,KAAK,oBAAoB,EAAE,GAAG,EAAE,kBAAkB;CAC3E,IAAI,EAAE,YACJ,KAAK,aAAa,EAAE,WAAW,KAAK,WAAW;EAC7C,UAAU,EAAE,GAAG,MAAM,SAAS;EAC9B,OAAO,EAAE,GAAG,MAAM,MAAM;CAC1B,EAAE;CAEJ,IAAI,EAAE,gBAAgB,KAAK,iBAAiB,EAAE,GAAG,EAAE,eAAe;CAClE,IAAI,EAAE,WAAW,KAAK,YAAY,EAAE,GAAG,EAAE,UAAU;CACnD,OAAO;AACT;AAEA,SAAgB,WAAW,GAAmB;CAC5C,MAAM,OAAO,SAAS,CAAC;CACvB,IAAI,EAAE,aACJ,KAAK,cAAc,CAAC,GAAG,EAAE,WAAW;CAEtC,OAAO;AACT;AAEA,SAAgB,WAAW,GAAmB;CAC5C,IAAI,EAAE,SAAS,UAAU,OAAO,gBAAgB,CAAC;CACjD,MAAM,aAAa,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM;CAC/C,IAAI,WAAW,SAAS,UAAU,OAAO,gBAAgB,UAAU;C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,IAAI,kBAAkB;EACrD,oBAAoB,IAAI,mBAAmB,KAAK,aAAa,gBAAgB,QAAQ,CAAC;EACtF,gBAAgB,WAAW,IAAI,cAAc;EAE7C,QAAQ,gBAAgB,OAAO,IAAI,SAAS;EAC5C,yBAAyB,EAAE,GAAG,IAAI,wBAAwB;EAC1D,eAAe,IAAI,gBAAgB,EAAE,GAAG,IAAI,cAAc,IAAI;EAC9D,SAAS,IAAI,UAAU,YAAY,IAAI,OAAO,IAAI;EAClD,eAAe,IAAI,gBAAgB,mBAAmB,IAAI,aAAa,IAAI;EAC3E,aAAa,IAAI,cAAc,IAAI,WAAW,IAAI,WAAW,IAAI;EACjE,mBAAmB,IAAI,oBACnB,eAAe,IAAI,mBAAmB,kBAAkB,IAAI,iBAAiB,KAAK,CAAC,CAAC,IACpF;EACJ,cAAc,IAAI,eAAe,gBAAgB,IAAI,YAAY,IAAI;EACrE,aAAa,IAAI,cAAc,EAAE,GAAG,IAAI,YAAY,IAAI;EACxD,cAAc,IAAI,eAAe,EAAE,GAAG,IAAI,aAAa,IAAI;EAC3D,mBAAmB,IAAI,oBAAoB,EAAE,GAAG,IAAI,kBAAkB,IAAI;EAC1E,gBAAgB,IAAI,iBAAiB,sBAAsB,IAAI,cAAc,IAAI;EACjF,cAAc,IAAI,eAAe,sBAAsB,IAAI,YAAY,IAAI;EAC3E,wBAAwB,gBAAgB,IAAI,sBAAsB;EAClE,uBAAuB,gBAAgB,IAAI,qBAAqB;EAChE,wBAAwB,IAAI,yBAAyB,EAAE,GAAG,IAAI,uBAAuB,IAAI;CAC3F;AACF"}
|
package/dist/css/values.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"values.d.ts","names":[],"sources":["../../src/css/values.ts"],"mappings":";;;;;;iBAYgB,eAAe;;iBAkBf,cAAc,4BAA4B;;
|
|
1
|
+
{"version":3,"file":"values.d.ts","names":[],"sources":["../../src/css/values.ts"],"mappings":";;;;;;iBAYgB,eAAe;;iBAkBf,cAAc,4BAA4B;;iBAQ1C,cAAc"}
|
package/dist/css/values.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { parseDisplayableColor } from "../color/management.js";
|
|
2
2
|
import valueParser from "postcss-value-parser";
|
|
3
3
|
//#region src/css/values.ts
|
|
4
4
|
/** Pixels in a rem, as browsers use by default. */
|
|
@@ -23,7 +23,7 @@ function parseCSSNumber(value) {
|
|
|
23
23
|
/** A CSS color that paints something; null for an invalid or fully transparent one. */
|
|
24
24
|
function parseCSSColor(value) {
|
|
25
25
|
if (!value) return null;
|
|
26
|
-
const color =
|
|
26
|
+
const color = parseDisplayableColor(value.trim());
|
|
27
27
|
return color && color.a > 0 ? color : null;
|
|
28
28
|
}
|
|
29
29
|
/** The space-separated parts of a CSS value, keeping functions such as `rgb(0, 0, 0)` whole. */
|
package/dist/css/values.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"values.js","names":[],"sources":["../../src/css/values.ts"],"sourcesContent":["import valueParser from 'postcss-value-parser'\n\nimport {
|
|
1
|
+
{"version":3,"file":"values.js","names":[],"sources":["../../src/css/values.ts"],"sourcesContent":["import valueParser from 'postcss-value-parser'\n\nimport { parseDisplayableColor } from '../color'\nimport type { Color } from '../primitives'\n\n/** Pixels in a rem, as browsers use by default. */\nconst ROOT_FONT_SIZE = 16\n\n/**\n * A CSS number in pixels: unitless, `px`, or `rem`. Null for `auto`, for units that depend on\n * what the value applies to (`%`, `em`, `vh`), and for anything that is not a number.\n */\nexport function parseCSSNumber(value: string | undefined): number | null {\n if (!value) return null\n const dimension = valueParser.unit(value.trim())\n if (!dimension) return null\n const number = Number(dimension.number)\n if (!Number.isFinite(number)) return null\n switch (dimension.unit.toLowerCase()) {\n case '':\n case 'px':\n return number\n case 'rem':\n return number * ROOT_FONT_SIZE\n default:\n return null\n }\n}\n\n/** A CSS color that paints something; null for an invalid or fully transparent one. */\nexport function parseCSSColor(value: string | undefined): Color | null {\n if (!value) return null\n // CSS clamps `rgb()` channels and maps wide-gamut colors into sRGB, as a stored color must be.\n const color = parseDisplayableColor(value.trim())\n return color && color.a > 0 ? color : null\n}\n\n/** The space-separated parts of a CSS value, keeping functions such as `rgb(0, 0, 0)` whole. */\nexport function splitCSSValue(value: string): string[] {\n return valueParser(value)\n .nodes.filter((node) => node.type !== 'space' && node.type !== 'comment')\n .map((node) => valueParser.stringify(node))\n}\n"],"mappings":";;;;AAMA,MAAM,iBAAiB;;;;;AAMvB,SAAgB,eAAe,OAA0C;CACvE,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,YAAY,YAAY,KAAK,MAAM,KAAK,CAAC;CAC/C,IAAI,CAAC,WAAW,OAAO;CACvB,MAAM,SAAS,OAAO,UAAU,MAAM;CACtC,IAAI,CAAC,OAAO,SAAS,MAAM,GAAG,OAAO;CACrC,QAAQ,UAAU,KAAK,YAAY,GAAnC;EACE,KAAK;EACL,KAAK,MACH,OAAO;EACT,KAAK,OACH,OAAO,SAAS;EAClB,SACE,OAAO;CACX;AACF;;AAGA,SAAgB,cAAc,OAAyC;CACrE,IAAI,CAAC,OAAO,OAAO;CAEnB,MAAM,QAAQ,sBAAsB,MAAM,KAAK,CAAC;CAChD,OAAO,SAAS,MAAM,IAAI,IAAI,QAAQ;AACxC;;AAGA,SAAgB,cAAc,OAAyB;CACrD,OAAO,YAAY,KAAK,CAAC,CACtB,MAAM,QAAQ,SAAS,KAAK,SAAS,WAAW,KAAK,SAAS,SAAS,CAAC,CACxE,KAAK,SAAS,YAAY,UAAU,IAAI,CAAC;AAC9C"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Vector } from "./primitives/index.js";
|
|
2
|
+
import { Effect, ShaderEffect, ShadowEffect } from "./types.js";
|
|
3
|
+
//#region src/effects.d.ts
|
|
4
|
+
/** A shadow or blur whose offset may still be missing or only partly present. */
|
|
5
|
+
type ShadowInput = Omit<ShadowEffect, 'offset'> & {
|
|
6
|
+
offset?: Partial<Vector> | null;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Shadows and blurs keep a finite offset. A drop or inner shadow missing one uses `{x: 0, y: 4}`,
|
|
10
|
+
* the same default as `dropShadow()` and `set_effects`; a blur uses `{x: 0, y: 0}`. Shader effects
|
|
11
|
+
* are left alone. An array that is already valid is returned as itself.
|
|
12
|
+
*/
|
|
13
|
+
declare function normalizeEffects(effects: (ShaderEffect | ShadowInput)[]): Effect[];
|
|
14
|
+
//#endregion
|
|
15
|
+
export { normalizeEffects };
|
|
16
|
+
//# sourceMappingURL=effects.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"effects.d.ts","names":[],"sources":["../src/effects.ts"],"mappings":";;;;KAOK,cAAc,KAAK;EACtB,SAAS,QAAQ;;;;;;;iBAqDH,iBAAiB,UAAU,eAAe,iBAAiB"}
|