@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/variables/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { BLACK } from "../constants.js";
|
|
2
2
|
import { bindingOverrideField, setInstanceOverride } from "../instances/overrides.js";
|
|
3
|
-
import { BOOLEAN_BINDING_FIELDS, ICON_BINDING_FIELDS, STRING_BINDING_FIELDS, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, isNumericVariableBindingField, paintBindingTarget, uniformBindingTarget } from "./fields.js";
|
|
3
|
+
import { BOOLEAN_BINDING_FIELDS, ICON_BINDING_FIELDS, NUMERIC_FIELDS, STRING_BINDING_FIELDS, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, isNumericVariableBindingField, paintBindingTarget, uniformBindingTarget } from "./fields.js";
|
|
4
|
+
import { SCALED_RUN_BINDING_FIELDS, pinnedRunBindingScales, runBindingScale, scaleVariableBindingUnits, withBoundBindingScales } from "./units.js";
|
|
4
5
|
import { findInstanceAncestor } from "../instances/index.js";
|
|
5
6
|
import { isShaderSourcePaint, shaderOfPaint, withShaderPaints } from "../shaders/model.js";
|
|
6
7
|
import { variableFontFamily, variableText, variableTruthy } from "./text.js";
|
|
@@ -21,6 +22,16 @@ import { ROOT_FONT_SIZE_PX, tokenExpressionForValue, tokenNumberFromUnit, tokenN
|
|
|
21
22
|
import { omit, omitBy } from "es-toolkit/object";
|
|
22
23
|
import { partition } from "es-toolkit/array";
|
|
23
24
|
//#region src/variables/index.ts
|
|
25
|
+
/**
|
|
26
|
+
* Gives the runs that bind `fields` the scale they resolve with as their own, before the layer's
|
|
27
|
+
* scale for those fields changes or goes, and the change to announce.
|
|
28
|
+
*/
|
|
29
|
+
function pinRunBindingScales(node, fields) {
|
|
30
|
+
const styleRuns = pinnedRunBindingScales(node, fields);
|
|
31
|
+
if (!styleRuns) return {};
|
|
32
|
+
node.styleRuns = styleRuns;
|
|
33
|
+
return { styleRuns };
|
|
34
|
+
}
|
|
24
35
|
function addVariable(graph, variable) {
|
|
25
36
|
graph.variables.set(variable.id, variable);
|
|
26
37
|
const collection = graph.variableCollections.get(variable.collectionId);
|
|
@@ -36,10 +47,13 @@ function removeVariable(graph, id) {
|
|
|
36
47
|
if (!Object.values(node.boundVariables).includes(id)) continue;
|
|
37
48
|
graph.willChangeNode(node);
|
|
38
49
|
node.boundVariables = omitBy(node.boundVariables, (varId) => varId === id);
|
|
39
|
-
|
|
50
|
+
const pruned = Object.keys(node.variableBindingScales).filter((field) => !(field in node.boundVariables));
|
|
51
|
+
const runs = pinRunBindingScales(node, pruned);
|
|
52
|
+
node.variableBindingScales = omit(node.variableBindingScales, pruned);
|
|
40
53
|
graph.emitter.emit("node:updated", node.id, {
|
|
41
54
|
boundVariables: { ...node.boundVariables },
|
|
42
|
-
variableBindingScales: { ...node.variableBindingScales }
|
|
55
|
+
variableBindingScales: { ...node.variableBindingScales },
|
|
56
|
+
...runs
|
|
43
57
|
});
|
|
44
58
|
markBoundVariablesOverrideOnInstance(graph, node.id);
|
|
45
59
|
}
|
|
@@ -157,6 +171,18 @@ function getVariablesForCollection(graph, collectionId) {
|
|
|
157
171
|
function getVariablesByType(graph, type) {
|
|
158
172
|
return [...graph.variables.values()].filter((v) => v.type === type);
|
|
159
173
|
}
|
|
174
|
+
const PAINT_BINDING_LISTS = ["fills", "strokes"];
|
|
175
|
+
/**
|
|
176
|
+
* Every field a binding takes, from the same sets `checkBindingFieldType` reads, so a refusal for
|
|
177
|
+
* an unknown one names what the caller can send instead of leaving them to guess.
|
|
178
|
+
*/
|
|
179
|
+
const ACCEPTED_BINDING_FIELDS = [
|
|
180
|
+
...NUMERIC_FIELDS,
|
|
181
|
+
...STRING_BINDING_FIELDS,
|
|
182
|
+
...BOOLEAN_BINDING_FIELDS,
|
|
183
|
+
...ICON_BINDING_FIELDS,
|
|
184
|
+
...PAINT_BINDING_LISTS.flatMap((list) => [`${list}/<n>/color`, `${list}/<n>/uniforms/<name>`])
|
|
185
|
+
];
|
|
160
186
|
/**
|
|
161
187
|
* Throws when a variable of `type` cannot bind to `field`, or for a field no binding takes. A
|
|
162
188
|
* paint target is checked by its caller, which also validates its index.
|
|
@@ -169,7 +195,7 @@ function checkBindingFieldType(field, type) {
|
|
|
169
195
|
if (ICON_BINDING_FIELDS.has(field) && type !== "STRING") throw new Error(`Cannot bind ${type} variable to icon field "${field}"`);
|
|
170
196
|
const uniform = uniformBindingTarget(field);
|
|
171
197
|
if (uniform && type !== "FLOAT" && type !== "COLOR" && type !== "BOOLEAN") throw new Error(`Cannot bind ${type} variable to shader input "${field}"`);
|
|
172
|
-
if (!(isNumericVariableBindingField(field) || STRING_BINDING_FIELDS.has(field) || BOOLEAN_BINDING_FIELDS.has(field) || ICON_BINDING_FIELDS.has(field) || paintBindingTarget(field) !== null || uniform !== null)) throw new Error(`Unknown binding field "${field}"`);
|
|
198
|
+
if (!(isNumericVariableBindingField(field) || STRING_BINDING_FIELDS.has(field) || BOOLEAN_BINDING_FIELDS.has(field) || ICON_BINDING_FIELDS.has(field) || paintBindingTarget(field) !== null || uniform !== null)) throw new Error(`Unknown binding field "${field}". Accepted: ${ACCEPTED_BINDING_FIELDS.join(", ")}`);
|
|
173
199
|
}
|
|
174
200
|
function bindVariable(graph, nodeId, field, variableId) {
|
|
175
201
|
const node = graph.nodes.get(nodeId);
|
|
@@ -210,11 +236,13 @@ function bindVariable(graph, nodeId, field, variableId) {
|
|
|
210
236
|
...node.boundVariables,
|
|
211
237
|
[field]: variableId
|
|
212
238
|
};
|
|
239
|
+
const runs = pinRunBindingScales(node, [field]);
|
|
213
240
|
assignVariableBindingUnits(graph, node, field);
|
|
214
241
|
markBoundVariablesOverrideOnInstance(graph, nodeId, field);
|
|
215
242
|
graph.emitter.emit("node:updated", nodeId, {
|
|
216
243
|
boundVariables: { ...node.boundVariables },
|
|
217
|
-
variableBindingScales: { ...node.variableBindingScales }
|
|
244
|
+
variableBindingScales: { ...node.variableBindingScales },
|
|
245
|
+
...runs
|
|
218
246
|
});
|
|
219
247
|
}
|
|
220
248
|
function unbindVariable(graph, nodeId, field) {
|
|
@@ -223,11 +251,13 @@ function unbindVariable(graph, nodeId, field) {
|
|
|
223
251
|
if (!(field in node.boundVariables)) return;
|
|
224
252
|
graph.willChangeNode(node);
|
|
225
253
|
node.boundVariables = omit(node.boundVariables, [field]);
|
|
254
|
+
const runs = pinRunBindingScales(node, [field]);
|
|
226
255
|
node.variableBindingScales = omit(node.variableBindingScales, [field]);
|
|
227
256
|
markBoundVariablesOverrideOnInstance(graph, nodeId, field);
|
|
228
257
|
graph.emitter.emit("node:updated", nodeId, {
|
|
229
258
|
boundVariables: { ...node.boundVariables },
|
|
230
|
-
variableBindingScales: { ...node.variableBindingScales }
|
|
259
|
+
variableBindingScales: { ...node.variableBindingScales },
|
|
260
|
+
...runs
|
|
231
261
|
});
|
|
232
262
|
}
|
|
233
263
|
function markBoundVariablesOverrideOnInstance(graph, nodeId, field) {
|
|
@@ -241,6 +271,6 @@ function markBoundVariablesOverrideOnInstance(graph, nodeId, field) {
|
|
|
241
271
|
if (field) setInstanceOverride(owner.instanceOverrides, owner.id, nodeId, bindingOverrideField(field), node.boundVariables[field] ?? null);
|
|
242
272
|
}
|
|
243
273
|
//#endregion
|
|
244
|
-
export { ICON_BINDING_FIELDS, MAX_FORMULA_DEPTH, ROOT_FONT_SIZE_PX, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, VariableFormulaError, VariableResolutionError, addCollection, addMode, addVariable, assignVariableBindingUnits, bindVariable, boundNumberValue, collectionsBoundIn, createBatchVariableResolver, createCollection, createMode, createVariable, evaluateVariableFormula, foldFormula, formatVariableFormula, formulaArity, formulaSymbol, formulaTokenName, formulaTokens, formulaValueType, getActiveModeId, getNodeVariableModeId, getVariablesByType, getVariablesForCollection, independentCornerChanges, inferFormulaType, isFormulaOperation, isFormulaReference, isNumericVariableBindingField, isUnsupportedVariableValue, layersUsingVariables, mapVariableValueReferences, modesDefaultFirst, paintBindingTarget, parseVariableFormula, printFormula, readFormulaToken, reconcileVariableBindings, removeCollection, removeMode, removeVariable, renameMode, resolveColorVariable, resolveColorVariableForNode, resolveNumberVariable, resolveNumberVariableForNode, resolveStringVariableForNode, resolveVariable, resolveVariableForNode, resolveVariableInModes, resolveVariableValue, resolvedIconBinding, resolvedNumericBindings, resolvedPaintBindings, resolvedRunBindings, resolvedValueBindings, setActiveMode, setDefaultMode, tokenExpressionForValue, tokenNumberFromUnit, tokenNumberInUnit, unbindVariable, updateTokenExpression, variableAliasSchema, variableBindingOwner, variableCollectionSchema, variableColorExpressionSchema, variableFontFamily, variableFormulaReference, variableFormulaSchema, variableSchema, variableText, variableTruthy, variableValueInMode, variableValueReferences, variablesResolvingThrough };
|
|
274
|
+
export { ICON_BINDING_FIELDS, MAX_FORMULA_DEPTH, ROOT_FONT_SIZE_PX, SCALED_RUN_BINDING_FIELDS, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, VariableFormulaError, VariableResolutionError, addCollection, addMode, addVariable, assignVariableBindingUnits, bindVariable, boundNumberValue, collectionsBoundIn, createBatchVariableResolver, createCollection, createMode, createVariable, evaluateVariableFormula, foldFormula, formatVariableFormula, formulaArity, formulaSymbol, formulaTokenName, formulaTokens, formulaValueType, getActiveModeId, getNodeVariableModeId, getVariablesByType, getVariablesForCollection, independentCornerChanges, inferFormulaType, isFormulaOperation, isFormulaReference, isNumericVariableBindingField, isUnsupportedVariableValue, layersUsingVariables, mapVariableValueReferences, modesDefaultFirst, paintBindingTarget, parseVariableFormula, pinnedRunBindingScales, printFormula, readFormulaToken, reconcileVariableBindings, removeCollection, removeMode, removeVariable, renameMode, resolveColorVariable, resolveColorVariableForNode, resolveNumberVariable, resolveNumberVariableForNode, resolveStringVariableForNode, resolveVariable, resolveVariableForNode, resolveVariableInModes, resolveVariableValue, resolvedIconBinding, resolvedNumericBindings, resolvedPaintBindings, resolvedRunBindings, resolvedValueBindings, runBindingScale, scaleVariableBindingUnits, setActiveMode, setDefaultMode, tokenExpressionForValue, tokenNumberFromUnit, tokenNumberInUnit, unbindVariable, updateTokenExpression, variableAliasSchema, variableBindingOwner, variableCollectionSchema, variableColorExpressionSchema, variableFontFamily, variableFormulaReference, variableFormulaSchema, variableSchema, variableText, variableTruthy, variableValueInMode, variableValueReferences, variablesResolvingThrough, withBoundBindingScales };
|
|
245
275
|
|
|
246
276
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/variables/index.ts"],"sourcesContent":["import { partition } from 'es-toolkit/array'\nimport { omit, omitBy } from 'es-toolkit/object'\n\nimport { BLACK } from '../constants'\nimport type { SceneGraph } from '../graph'\nimport { findInstanceAncestor } from '../instances'\nimport { bindingOverrideField, setInstanceOverride } from '../instances/overrides'\nimport { isShaderSourcePaint, shaderOfPaint, withShaderPaints } from '../shaders/model'\nimport type {\n Variable,\n VariableCollection,\n VariableCollectionMode,\n VariableType,\n VariableValue\n} from '../types'\nimport {\n isNumericVariableBindingField,\n variableBindingOwner,\n assignVariableBindingUnits\n} from './bindings'\nimport {\n BOOLEAN_BINDING_FIELDS,\n ICON_BINDING_FIELDS,\n paintBindingTarget,\n STRING_BINDING_FIELDS,\n TEXT_CONTENT_VARIABLE_TYPES,\n uniformBindingTarget,\n VISIBILITY_VARIABLE_TYPES\n} from './fields'\n\nexport * from './resolution'\n\nexport function addVariable(graph: SceneGraph, variable: Variable): void {\n graph.variables.set(variable.id, variable)\n const collection = graph.variableCollections.get(variable.collectionId)\n if (collection && !collection.variableIds.includes(variable.id)) {\n collection.variableIds.push(variable.id)\n }\n}\n\nexport function removeVariable(graph: SceneGraph, id: string): void {\n const variable = graph.variables.get(id)\n if (!variable) return\n graph.variables.delete(id)\n const collection = graph.variableCollections.get(variable.collectionId)\n if (collection) {\n collection.variableIds = collection.variableIds.filter((vid) => vid !== id)\n }\n for (const node of graph.nodes.values()) {\n const hadBinding = Object.values(node.boundVariables).includes(id)\n if (!hadBinding) continue\n graph.willChangeNode(node)\n node.boundVariables = omitBy(node.boundVariables, (varId) => varId === id) as Record<\n string,\n string\n >\n node.variableBindingScales = omitBy(\n node.variableBindingScales,\n (_, field) => !(field in node.boundVariables)\n )\n graph.emitter.emit('node:updated', node.id, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales }\n })\n markBoundVariablesOverrideOnInstance(graph, node.id)\n }\n}\n\nexport function addCollection(graph: SceneGraph, collection: VariableCollection): void {\n graph.variableCollections.set(collection.id, collection)\n if (!graph.activeMode.has(collection.id)) {\n graph.activeMode.set(collection.id, collection.defaultModeId)\n }\n}\n\nfunction defaultVariableValue(type: VariableType, value?: VariableValue): VariableValue {\n if (value !== undefined) return value\n if (type === 'COLOR') return { ...BLACK }\n if (type === 'FLOAT') return 0\n if (type === 'BOOLEAN') return false\n return ''\n}\n\nexport function createVariable(\n graph: SceneGraph,\n generateId: () => string,\n name: string,\n type: VariableType,\n collectionId: string,\n value?: VariableValue\n): Variable {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) throw new Error(`Collection \"${collectionId}\" not found`)\n const id = generateId()\n const defaultValue = defaultVariableValue(type, value)\n const valuesByMode: Record<string, VariableValue> = {}\n for (const mode of collection.modes) {\n valuesByMode[mode.modeId] = structuredClone(defaultValue)\n }\n const variable: Variable = {\n id,\n name,\n type,\n collectionId,\n valuesByMode,\n description: '',\n hiddenFromPublishing: false\n }\n addVariable(graph, variable)\n return variable\n}\n\nexport function createCollection(\n graph: SceneGraph,\n generateId: () => string,\n name: string\n): VariableCollection {\n const id = generateId()\n const modeId = generateId()\n const collection: VariableCollection = {\n id,\n name,\n modes: [{ modeId, name: 'Mode 1' }],\n defaultModeId: modeId,\n variableIds: []\n }\n addCollection(graph, collection)\n return collection\n}\n\nexport function removeCollection(graph: SceneGraph, id: string): void {\n const collection = graph.variableCollections.get(id)\n if (collection) {\n for (const varId of Array.from(collection.variableIds)) {\n removeVariable(graph, varId)\n }\n }\n graph.variableCollections.delete(id)\n graph.activeMode.delete(id)\n}\n\nexport function setActiveMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n graph.activeMode.set(collectionId, modeId)\n}\n\nexport function addMode(\n graph: SceneGraph,\n collectionId: string,\n modeId: string,\n name: string,\n sourceMode?: string\n): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n collection.modes.push({ modeId, name })\n const sourceModeId = sourceMode ?? collection.defaultModeId\n for (const varId of collection.variableIds) {\n const variable = graph.variables.get(varId)\n if (!variable) continue\n variable.valuesByMode[modeId] = structuredClone(\n variable.valuesByMode[sourceModeId] ?? Object.values(variable.valuesByMode)[0]\n )\n }\n}\n\n/** Add a mode with a new ID from `generateId`; undo and redo replay it with `addMode`. */\nexport function createMode(\n graph: SceneGraph,\n generateId: () => string,\n collectionId: string,\n name: string,\n sourceMode?: string\n): string | undefined {\n if (!graph.variableCollections.has(collectionId)) return undefined\n const modeId = generateId()\n addMode(graph, collectionId, modeId, name, sourceMode)\n return modeId\n}\n\nexport function removeMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection || collection.modes.length <= 1) return\n collection.modes = collection.modes.filter((m) => m.modeId !== modeId)\n if (collection.defaultModeId === modeId) {\n collection.defaultModeId = collection.modes[0].modeId\n }\n for (const varId of collection.variableIds) {\n const variable = graph.variables.get(varId)\n if (variable) variable.valuesByMode = omit(variable.valuesByMode, [modeId])\n }\n if (graph.activeMode.get(collectionId) === modeId) {\n graph.activeMode.set(collectionId, collection.defaultModeId)\n }\n}\n\nexport function renameMode(\n graph: SceneGraph,\n collectionId: string,\n modeId: string,\n name: string\n): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n const mode = collection.modes.find((m) => m.modeId === modeId)\n if (mode) mode.name = name\n}\n\nexport function setDefaultMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n if (!collection.modes.some((m) => m.modeId === modeId)) return\n collection.defaultModeId = modeId\n collection.modes = modesDefaultFirst(collection)\n}\n\n/** Figma has no default-mode field: the first mode is the default. */\nexport function modesDefaultFirst(collection: VariableCollection): VariableCollectionMode[] {\n const [defaults, rest] = partition(collection.modes, (m) => m.modeId === collection.defaultModeId)\n return [...defaults, ...rest]\n}\n\nexport function getVariablesForCollection(graph: SceneGraph, collectionId: string): Variable[] {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return []\n return collection.variableIds\n .map((id) => graph.variables.get(id))\n .filter((v): v is Variable => v !== undefined)\n}\n\nexport function getVariablesByType(graph: SceneGraph, type: VariableType): Variable[] {\n return [...graph.variables.values()].filter((v) => v.type === type)\n}\n\n/**\n * Throws when a variable of `type` cannot bind to `field`, or for a field no binding takes. A\n * paint target is checked by its caller, which also validates its index.\n */\nfunction checkBindingFieldType(field: string, type: VariableType): void {\n if (isNumericVariableBindingField(field) && type !== 'FLOAT') {\n throw new Error(`Cannot bind ${type} variable to scalar field \"${field}\"`)\n }\n\n const textTypes: readonly VariableType[] =\n field === 'text' ? TEXT_CONTENT_VARIABLE_TYPES : ['STRING']\n if (STRING_BINDING_FIELDS.has(field) && !textTypes.includes(type)) {\n throw new Error(`Cannot bind ${type} variable to string field \"${field}\"`)\n }\n\n if (\n BOOLEAN_BINDING_FIELDS.has(field) &&\n !VISIBILITY_VARIABLE_TYPES.some((kind) => kind === type)\n ) {\n throw new Error(`Cannot bind ${type} variable to boolean field \"${field}\"`)\n }\n\n if (ICON_BINDING_FIELDS.has(field) && type !== 'STRING') {\n throw new Error(`Cannot bind ${type} variable to icon field \"${field}\"`)\n }\n\n // A shader uniform takes a number, a colour, or a boolean; its shader declares which.\n const uniform = uniformBindingTarget(field)\n if (uniform && type !== 'FLOAT' && type !== 'COLOR' && type !== 'BOOLEAN') {\n throw new Error(`Cannot bind ${type} variable to shader input \"${field}\"`)\n }\n\n const isKnownField =\n isNumericVariableBindingField(field) ||\n STRING_BINDING_FIELDS.has(field) ||\n BOOLEAN_BINDING_FIELDS.has(field) ||\n ICON_BINDING_FIELDS.has(field) ||\n paintBindingTarget(field) !== null ||\n uniform !== null\n\n if (!isKnownField) {\n throw new Error(`Unknown binding field \"${field}\"`)\n }\n}\nexport function bindVariable(\n graph: SceneGraph,\n nodeId: string,\n field: string,\n variableId: string\n): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n\n // Validate variable exists\n const variable = graph.variables.get(variableId)\n if (!variable) {\n throw new Error(`Variable \"${variableId}\" not found`)\n }\n\n // Color fields require COLOR variable type\n const paint = paintBindingTarget(field)\n if (paint) {\n if (variable.type !== 'COLOR') {\n throw new Error(`Cannot bind ${variable.type} variable to color field \"${field}\"`)\n }\n // Validate index is within current array bounds\n const currentLength = node[paint.list].length\n if (paint.index >= currentLength) {\n throw new Error(\n `Index ${paint.index} out of range for ${paint.list} (length ${currentLength})`\n )\n }\n // Auto-remove top-level dead binding (e.g. 'fills') when setting indexed binding\n if (paint.list in node.boundVariables) {\n node.boundVariables = omit(node.boundVariables, [paint.list])\n }\n }\n\n checkBindingFieldType(field, variable.type)\n\n // A shader input belongs to one paint, so its index must exist on the layer.\n const uniform = uniformBindingTarget(field)\n if (uniform && uniform.index >= node[uniform.list].length) {\n throw new Error(\n `Index ${uniform.index} out of range for ${uniform.list} (length ${node[uniform.list].length})`\n )\n }\n if (uniform) {\n // The binding lives with the shader entry, next to the value it resolves, so any renderer\n // that draws the paint resolves it the same way.\n const paints = node[uniform.list]\n const paint = paints.at(uniform.index)\n const shader = paint ? shaderOfPaint(node, paint) : null\n if (paint && shader && isShaderSourcePaint(shader)) {\n node.pluginData = withShaderPaints(node, paints, [\n {\n ...shader,\n uniformBindings: {\n ...shader.uniformBindings,\n [uniform.name]: variableId\n }\n }\n ])\n }\n graph.willChangeNode(node)\n graph.emitter.emit('node:updated', nodeId, {\n pluginData: node.pluginData,\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales }\n })\n return\n }\n graph.willChangeNode(node)\n node.boundVariables = { ...node.boundVariables, [field]: variableId }\n assignVariableBindingUnits(graph, node, field)\n markBoundVariablesOverrideOnInstance(graph, nodeId, field)\n graph.emitter.emit('node:updated', nodeId, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales }\n })\n}\n\nexport function unbindVariable(graph: SceneGraph, nodeId: string, field: string): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n if (!(field in node.boundVariables)) return\n graph.willChangeNode(node)\n node.boundVariables = omit(node.boundVariables, [field])\n node.variableBindingScales = omit(node.variableBindingScales, [field])\n markBoundVariablesOverrideOnInstance(graph, nodeId, field)\n graph.emitter.emit('node:updated', nodeId, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales }\n })\n}\n\nfunction markBoundVariablesOverrideOnInstance(\n graph: SceneGraph,\n nodeId: string,\n field?: string\n): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n\n const owner = variableBindingOwner(graph, node)\n if (owner.type !== 'INSTANCE') return\n const nearest = findInstanceAncestor(graph, nodeId)\n if (nearest) setInstanceOverride(nearest.instanceOverrides, nearest.id, nodeId, 'boundVariables')\n setInstanceOverride(owner.instanceOverrides, owner.id, nodeId, 'boundVariables')\n if (field)\n setInstanceOverride(\n owner.instanceOverrides,\n owner.id,\n nodeId,\n bindingOverrideField(field),\n node.boundVariables[field] ?? null\n )\n}\n\nexport * from './bindings'\nexport * from './corners'\nexport * from './formula'\nexport * from './formula/schema'\nexport * from './schema'\nexport * from './text'\nexport * from './token'\nexport * from './value'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAg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O,MAAM,MAAM,IAAI,MAAM;CACnC,IAAI,CAAC,MAAM;CAEX,MAAM,QAAQ,qBAAqB,OAAO,IAAI;CAC9C,IAAI,MAAM,SAAS,YAAY;CAC/B,MAAM,UAAU,qBAAqB,OAAO,MAAM;CAClD,IAAI,SAAS,oBAAoB,QAAQ,mBAAmB,QAAQ,IAAI,QAAQ,gBAAgB;CAChG,oBAAoB,MAAM,mBAAmB,MAAM,IAAI,QAAQ,gBAAgB;CAC/E,IAAI,OACF,oBACE,MAAM,mBACN,MAAM,IACN,QACA,qBAAqB,KAAK,GAC1B,KAAK,eAAe,UAAU,IAChC;AACJ"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/variables/index.ts"],"sourcesContent":["import { partition } from 'es-toolkit/array'\nimport { omit, omitBy } from 'es-toolkit/object'\n\nimport { BLACK } from '../constants'\nimport type { SceneGraph } from '../graph'\nimport { findInstanceAncestor } from '../instances'\nimport { bindingOverrideField, setInstanceOverride } from '../instances/overrides'\nimport { isShaderSourcePaint, shaderOfPaint, withShaderPaints } from '../shaders/model'\nimport type {\n SceneNode,\n Variable,\n VariableCollection,\n VariableCollectionMode,\n VariableType,\n VariableValue\n} from '../types'\nimport {\n isNumericVariableBindingField,\n variableBindingOwner,\n assignVariableBindingUnits\n} from './bindings'\nimport {\n BOOLEAN_BINDING_FIELDS,\n ICON_BINDING_FIELDS,\n NUMERIC_FIELDS,\n paintBindingTarget,\n STRING_BINDING_FIELDS,\n TEXT_CONTENT_VARIABLE_TYPES,\n uniformBindingTarget,\n VISIBILITY_VARIABLE_TYPES,\n type PaintBindingList\n} from './fields'\nimport { pinnedRunBindingScales } from './units'\n\nexport * from './resolution'\n\n/**\n * Gives the runs that bind `fields` the scale they resolve with as their own, before the layer's\n * scale for those fields changes or goes, and the change to announce.\n */\nfunction pinRunBindingScales(\n node: SceneNode,\n fields: readonly string[]\n): Pick<Partial<SceneNode>, 'styleRuns'> {\n const styleRuns = pinnedRunBindingScales(node, fields)\n if (!styleRuns) return {}\n node.styleRuns = styleRuns\n return { styleRuns }\n}\n\nexport function addVariable(graph: SceneGraph, variable: Variable): void {\n graph.variables.set(variable.id, variable)\n const collection = graph.variableCollections.get(variable.collectionId)\n if (collection && !collection.variableIds.includes(variable.id)) {\n collection.variableIds.push(variable.id)\n }\n}\n\nexport function removeVariable(graph: SceneGraph, id: string): void {\n const variable = graph.variables.get(id)\n if (!variable) return\n graph.variables.delete(id)\n const collection = graph.variableCollections.get(variable.collectionId)\n if (collection) {\n collection.variableIds = collection.variableIds.filter((vid) => vid !== id)\n }\n for (const node of graph.nodes.values()) {\n const hadBinding = Object.values(node.boundVariables).includes(id)\n if (!hadBinding) continue\n graph.willChangeNode(node)\n node.boundVariables = omitBy(node.boundVariables, (varId) => varId === id) as Record<\n string,\n string\n >\n const pruned = Object.keys(node.variableBindingScales).filter(\n (field) => !(field in node.boundVariables)\n )\n const runs = pinRunBindingScales(node, pruned)\n node.variableBindingScales = omit(node.variableBindingScales, pruned)\n graph.emitter.emit('node:updated', node.id, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales },\n ...runs\n })\n markBoundVariablesOverrideOnInstance(graph, node.id)\n }\n}\n\nexport function addCollection(graph: SceneGraph, collection: VariableCollection): void {\n graph.variableCollections.set(collection.id, collection)\n if (!graph.activeMode.has(collection.id)) {\n graph.activeMode.set(collection.id, collection.defaultModeId)\n }\n}\n\nfunction defaultVariableValue(type: VariableType, value?: VariableValue): VariableValue {\n if (value !== undefined) return value\n if (type === 'COLOR') return { ...BLACK }\n if (type === 'FLOAT') return 0\n if (type === 'BOOLEAN') return false\n return ''\n}\n\nexport function createVariable(\n graph: SceneGraph,\n generateId: () => string,\n name: string,\n type: VariableType,\n collectionId: string,\n value?: VariableValue\n): Variable {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) throw new Error(`Collection \"${collectionId}\" not found`)\n const id = generateId()\n const defaultValue = defaultVariableValue(type, value)\n const valuesByMode: Record<string, VariableValue> = {}\n for (const mode of collection.modes) {\n valuesByMode[mode.modeId] = structuredClone(defaultValue)\n }\n const variable: Variable = {\n id,\n name,\n type,\n collectionId,\n valuesByMode,\n description: '',\n hiddenFromPublishing: false\n }\n addVariable(graph, variable)\n return variable\n}\n\nexport function createCollection(\n graph: SceneGraph,\n generateId: () => string,\n name: string\n): VariableCollection {\n const id = generateId()\n const modeId = generateId()\n const collection: VariableCollection = {\n id,\n name,\n modes: [{ modeId, name: 'Mode 1' }],\n defaultModeId: modeId,\n variableIds: []\n }\n addCollection(graph, collection)\n return collection\n}\n\nexport function removeCollection(graph: SceneGraph, id: string): void {\n const collection = graph.variableCollections.get(id)\n if (collection) {\n for (const varId of Array.from(collection.variableIds)) {\n removeVariable(graph, varId)\n }\n }\n graph.variableCollections.delete(id)\n graph.activeMode.delete(id)\n}\n\nexport function setActiveMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n graph.activeMode.set(collectionId, modeId)\n}\n\nexport function addMode(\n graph: SceneGraph,\n collectionId: string,\n modeId: string,\n name: string,\n sourceMode?: string\n): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n collection.modes.push({ modeId, name })\n const sourceModeId = sourceMode ?? collection.defaultModeId\n for (const varId of collection.variableIds) {\n const variable = graph.variables.get(varId)\n if (!variable) continue\n variable.valuesByMode[modeId] = structuredClone(\n variable.valuesByMode[sourceModeId] ?? Object.values(variable.valuesByMode)[0]\n )\n }\n}\n\n/** Add a mode with a new ID from `generateId`; undo and redo replay it with `addMode`. */\nexport function createMode(\n graph: SceneGraph,\n generateId: () => string,\n collectionId: string,\n name: string,\n sourceMode?: string\n): string | undefined {\n if (!graph.variableCollections.has(collectionId)) return undefined\n const modeId = generateId()\n addMode(graph, collectionId, modeId, name, sourceMode)\n return modeId\n}\n\nexport function removeMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection || collection.modes.length <= 1) return\n collection.modes = collection.modes.filter((m) => m.modeId !== modeId)\n if (collection.defaultModeId === modeId) {\n collection.defaultModeId = collection.modes[0].modeId\n }\n for (const varId of collection.variableIds) {\n const variable = graph.variables.get(varId)\n if (variable) variable.valuesByMode = omit(variable.valuesByMode, [modeId])\n }\n if (graph.activeMode.get(collectionId) === modeId) {\n graph.activeMode.set(collectionId, collection.defaultModeId)\n }\n}\n\nexport function renameMode(\n graph: SceneGraph,\n collectionId: string,\n modeId: string,\n name: string\n): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n const mode = collection.modes.find((m) => m.modeId === modeId)\n if (mode) mode.name = name\n}\n\nexport function setDefaultMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n if (!collection.modes.some((m) => m.modeId === modeId)) return\n collection.defaultModeId = modeId\n collection.modes = modesDefaultFirst(collection)\n}\n\n/** Figma has no default-mode field: the first mode is the default. */\nexport function modesDefaultFirst(collection: VariableCollection): VariableCollectionMode[] {\n const [defaults, rest] = partition(collection.modes, (m) => m.modeId === collection.defaultModeId)\n return [...defaults, ...rest]\n}\n\nexport function getVariablesForCollection(graph: SceneGraph, collectionId: string): Variable[] {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return []\n return collection.variableIds\n .map((id) => graph.variables.get(id))\n .filter((v): v is Variable => v !== undefined)\n}\n\nexport function getVariablesByType(graph: SceneGraph, type: VariableType): Variable[] {\n return [...graph.variables.values()].filter((v) => v.type === type)\n}\n\nconst PAINT_BINDING_LISTS = ['fills', 'strokes'] as const satisfies readonly PaintBindingList[]\n\n/**\n * Every field a binding takes, from the same sets `checkBindingFieldType` reads, so a refusal for\n * an unknown one names what the caller can send instead of leaving them to guess.\n */\nconst ACCEPTED_BINDING_FIELDS: readonly string[] = [\n ...NUMERIC_FIELDS,\n ...STRING_BINDING_FIELDS,\n ...BOOLEAN_BINDING_FIELDS,\n ...ICON_BINDING_FIELDS,\n ...PAINT_BINDING_LISTS.flatMap((list) => [`${list}/<n>/color`, `${list}/<n>/uniforms/<name>`])\n]\n\n/**\n * Throws when a variable of `type` cannot bind to `field`, or for a field no binding takes. A\n * paint target is checked by its caller, which also validates its index.\n */\nfunction checkBindingFieldType(field: string, type: VariableType): void {\n if (isNumericVariableBindingField(field) && type !== 'FLOAT') {\n throw new Error(`Cannot bind ${type} variable to scalar field \"${field}\"`)\n }\n\n const textTypes: readonly VariableType[] =\n field === 'text' ? TEXT_CONTENT_VARIABLE_TYPES : ['STRING']\n if (STRING_BINDING_FIELDS.has(field) && !textTypes.includes(type)) {\n throw new Error(`Cannot bind ${type} variable to string field \"${field}\"`)\n }\n\n if (\n BOOLEAN_BINDING_FIELDS.has(field) &&\n !VISIBILITY_VARIABLE_TYPES.some((kind) => kind === type)\n ) {\n throw new Error(`Cannot bind ${type} variable to boolean field \"${field}\"`)\n }\n\n if (ICON_BINDING_FIELDS.has(field) && type !== 'STRING') {\n throw new Error(`Cannot bind ${type} variable to icon field \"${field}\"`)\n }\n\n // A shader uniform takes a number, a colour, or a boolean; its shader declares which.\n const uniform = uniformBindingTarget(field)\n if (uniform && type !== 'FLOAT' && type !== 'COLOR' && type !== 'BOOLEAN') {\n throw new Error(`Cannot bind ${type} variable to shader input \"${field}\"`)\n }\n\n const isKnownField =\n isNumericVariableBindingField(field) ||\n STRING_BINDING_FIELDS.has(field) ||\n BOOLEAN_BINDING_FIELDS.has(field) ||\n ICON_BINDING_FIELDS.has(field) ||\n paintBindingTarget(field) !== null ||\n uniform !== null\n\n if (!isKnownField) {\n throw new Error(\n `Unknown binding field \"${field}\". Accepted: ${ACCEPTED_BINDING_FIELDS.join(', ')}`\n )\n }\n}\nexport function bindVariable(\n graph: SceneGraph,\n nodeId: string,\n field: string,\n variableId: string\n): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n\n // Validate variable exists\n const variable = graph.variables.get(variableId)\n if (!variable) {\n throw new Error(`Variable \"${variableId}\" not found`)\n }\n\n // Color fields require COLOR variable type\n const paint = paintBindingTarget(field)\n if (paint) {\n if (variable.type !== 'COLOR') {\n throw new Error(`Cannot bind ${variable.type} variable to color field \"${field}\"`)\n }\n // Validate index is within current array bounds\n const currentLength = node[paint.list].length\n if (paint.index >= currentLength) {\n throw new Error(\n `Index ${paint.index} out of range for ${paint.list} (length ${currentLength})`\n )\n }\n // Auto-remove top-level dead binding (e.g. 'fills') when setting indexed binding\n if (paint.list in node.boundVariables) {\n node.boundVariables = omit(node.boundVariables, [paint.list])\n }\n }\n\n checkBindingFieldType(field, variable.type)\n\n // A shader input belongs to one paint, so its index must exist on the layer.\n const uniform = uniformBindingTarget(field)\n if (uniform && uniform.index >= node[uniform.list].length) {\n throw new Error(\n `Index ${uniform.index} out of range for ${uniform.list} (length ${node[uniform.list].length})`\n )\n }\n if (uniform) {\n // The binding lives with the shader entry, next to the value it resolves, so any renderer\n // that draws the paint resolves it the same way.\n const paints = node[uniform.list]\n const paint = paints.at(uniform.index)\n const shader = paint ? shaderOfPaint(node, paint) : null\n if (paint && shader && isShaderSourcePaint(shader)) {\n node.pluginData = withShaderPaints(node, paints, [\n {\n ...shader,\n uniformBindings: {\n ...shader.uniformBindings,\n [uniform.name]: variableId\n }\n }\n ])\n }\n graph.willChangeNode(node)\n graph.emitter.emit('node:updated', nodeId, {\n pluginData: node.pluginData,\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales }\n })\n return\n }\n graph.willChangeNode(node)\n node.boundVariables = { ...node.boundVariables, [field]: variableId }\n const runs = pinRunBindingScales(node, [field])\n assignVariableBindingUnits(graph, node, field)\n markBoundVariablesOverrideOnInstance(graph, nodeId, field)\n graph.emitter.emit('node:updated', nodeId, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales },\n ...runs\n })\n}\n\nexport function unbindVariable(graph: SceneGraph, nodeId: string, field: string): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n if (!(field in node.boundVariables)) return\n graph.willChangeNode(node)\n node.boundVariables = omit(node.boundVariables, [field])\n const runs = pinRunBindingScales(node, [field])\n node.variableBindingScales = omit(node.variableBindingScales, [field])\n markBoundVariablesOverrideOnInstance(graph, nodeId, field)\n graph.emitter.emit('node:updated', nodeId, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales },\n ...runs\n })\n}\n\nfunction markBoundVariablesOverrideOnInstance(\n graph: SceneGraph,\n nodeId: string,\n field?: string\n): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n\n const owner = variableBindingOwner(graph, node)\n if (owner.type !== 'INSTANCE') return\n const nearest = findInstanceAncestor(graph, nodeId)\n if (nearest) setInstanceOverride(nearest.instanceOverrides, nearest.id, nodeId, 'boundVariables')\n setInstanceOverride(owner.instanceOverrides, owner.id, nodeId, 'boundVariables')\n if (field)\n setInstanceOverride(\n owner.instanceOverrides,\n owner.id,\n nodeId,\n bindingOverrideField(field),\n node.boundVariables[field] ?? null\n )\n}\n\nexport * from './bindings'\nexport * from './corners'\nexport * from './formula'\nexport * from './formula/schema'\nexport * from './schema'\nexport * from './text'\nexport * from './token'\nexport * from './units'\nexport * from './value'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAS,oBACP,MACA,QACuC;CACvC,MAAM,YAAY,uBAAuB,MAAM,MAAM;CACrD,IAAI,CAAC,WAAW,OAAO,CAAC;CACxB,KAAK,YAAY;CACjB,OAAO,EAAE,UAAU;AACrB;AAEA,SAAgB,YAAY,OAAmB,UAA0B;CACvE,MAAM,UAAU,IAAI,SAAS,IAAI,QAAQ;CACzC,MAAM,aAAa,MAAM,oBAAoB,IAAI,SAAS,YAAY;CACtE,IAAI,cAAc,CAAC,WAAW,YAAY,SAAS,SAAS,EAAE,GAC5D,WAAW,YAAY,KAAK,SAAS,EAAE;AAE3C;AAEA,SAAgB,eAAe,OAAmB,IAAkB;CAClE,MAAM,WAAW,MAAM,UAAU,IAAI,EAAE;CACvC,IAAI,CAAC,UAAU;CACf,MAAM,UAAU,OAAO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e;EACzC,uBAAuB,EAAE,GAAG,KAAK,sBAAsB;EACvD,GAAG;CACL,CAAC;AACH;AAEA,SAAS,qCACP,OACA,QACA,OACM;CACN,MAAM,OAAO,MAAM,MAAM,IAAI,MAAM;CACnC,IAAI,CAAC,MAAM;CAEX,MAAM,QAAQ,qBAAqB,OAAO,IAAI;CAC9C,IAAI,MAAM,SAAS,YAAY;CAC/B,MAAM,UAAU,qBAAqB,OAAO,MAAM;CAClD,IAAI,SAAS,oBAAoB,QAAQ,mBAAmB,QAAQ,IAAI,QAAQ,gBAAgB;CAChG,oBAAoB,MAAM,mBAAmB,MAAM,IAAI,QAAQ,gBAAgB;CAC/E,IAAI,OACF,oBACE,MAAM,mBACN,MAAM,IACN,QACA,qBAAqB,KAAK,GAC1B,KAAK,eAAe,UAAU,IAChC;AACJ"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { CharacterStyleOverride, SceneNode, StyleRun, TextBindableField } from "../types.js";
|
|
2
|
+
//#region src/variables/units.d.ts
|
|
3
|
+
declare const SCALED_RUN_BINDING_FIELD_LIST: readonly ["fontSize", "letterSpacing", "lineHeight"];
|
|
4
|
+
/** A size or spacing a text's characters bind that a rescale scales with the layer. */
|
|
5
|
+
type ScaledRunBindingField = (typeof SCALED_RUN_BINDING_FIELD_LIST)[number];
|
|
6
|
+
/**
|
|
7
|
+
* Numbers a text's characters bind that a rescale scales with the layer. Each run keeps its own
|
|
8
|
+
* scale for the field, because the rescale scales the layer and its characters alike.
|
|
9
|
+
*/
|
|
10
|
+
declare const SCALED_RUN_BINDING_FIELDS: ReadonlySet<string>;
|
|
11
|
+
/**
|
|
12
|
+
* The scale a run's binding of `field` resolves with: the run's own, else, for a run saved before
|
|
13
|
+
* runs kept one, the layer's scale for a size or spacing, as every run once shared it.
|
|
14
|
+
*/
|
|
15
|
+
declare function runBindingScale(node: Pick<SceneNode, 'variableBindingScales'>, style: CharacterStyleOverride, field: TextBindableField): number;
|
|
16
|
+
/** A run's style keeping scales only for the numbers it still binds, and no empty scales. */
|
|
17
|
+
declare function withBoundBindingScales(style: CharacterStyleOverride): CharacterStyleOverride;
|
|
18
|
+
/**
|
|
19
|
+
* The runs with every size or spacing they bind holding the scale it resolves with as their own,
|
|
20
|
+
* or `undefined` when each already does. Called before the layer's scale for a field changes or
|
|
21
|
+
* goes, it migrates a run that still resolves with the layer's, so the run keeps its look.
|
|
22
|
+
*/
|
|
23
|
+
declare function pinnedRunBindingScales(node: SceneNode, fields?: readonly string[]): StyleRun[] | undefined;
|
|
24
|
+
/**
|
|
25
|
+
* The binding scales of a layer rescaled by `factor`. `styleRuns` are the runs the rescale leaves,
|
|
26
|
+
* when it also scales their values, so each keeps them and gains its own scales.
|
|
27
|
+
*/
|
|
28
|
+
declare function scaleVariableBindingUnits(node: SceneNode, factor: number, styleRuns?: readonly StyleRun[]): Partial<SceneNode>;
|
|
29
|
+
//#endregion
|
|
30
|
+
export { SCALED_RUN_BINDING_FIELDS, ScaledRunBindingField, pinnedRunBindingScales, runBindingScale, scaleVariableBindingUnits, withBoundBindingScales };
|
|
31
|
+
//# sourceMappingURL=units.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"units.d.ts","names":[],"sources":["../../src/variables/units.ts"],"mappings":";;cAMM;;KAGM,gCAAgC;;;;;cAM/B,2BAA2B;;;;;iBAMxB,gBACd,MAAM,KAAK,qCACX,OAAO,wBACP,OAAO;;iBAQO,uBAAuB,OAAO,yBAAyB;;;;;;iBAqCvD,uBACd,MAAM,WACN,6BACC;;;;;iBAUa,0BACd,MAAM,WACN,gBACA,qBAAoB,aACnB,QAAQ"}
|
package/dist/variables/units.js
CHANGED
|
@@ -1,19 +1,94 @@
|
|
|
1
1
|
import { NUMERIC_FIELDS } from "./fields.js";
|
|
2
|
+
import { omit, pickBy } from "es-toolkit/object";
|
|
3
|
+
import { isEmptyObject } from "es-toolkit/predicate";
|
|
2
4
|
//#region src/variables/units.ts
|
|
3
|
-
|
|
5
|
+
const SCALED_RUN_BINDING_FIELD_LIST = [
|
|
6
|
+
"fontSize",
|
|
7
|
+
"letterSpacing",
|
|
8
|
+
"lineHeight"
|
|
9
|
+
];
|
|
10
|
+
/**
|
|
11
|
+
* Numbers a text's characters bind that a rescale scales with the layer. Each run keeps its own
|
|
12
|
+
* scale for the field, because the rescale scales the layer and its characters alike.
|
|
13
|
+
*/
|
|
14
|
+
const SCALED_RUN_BINDING_FIELDS = new Set(SCALED_RUN_BINDING_FIELD_LIST);
|
|
15
|
+
/**
|
|
16
|
+
* The scale a run's binding of `field` resolves with: the run's own, else, for a run saved before
|
|
17
|
+
* runs kept one, the layer's scale for a size or spacing, as every run once shared it.
|
|
18
|
+
*/
|
|
19
|
+
function runBindingScale(node, style, field) {
|
|
20
|
+
const own = style.variableBindingScales?.[field];
|
|
21
|
+
if (own !== void 0) return own;
|
|
22
|
+
return SCALED_RUN_BINDING_FIELDS.has(field) ? node.variableBindingScales[field] ?? 1 : 1;
|
|
23
|
+
}
|
|
24
|
+
/** A run's style keeping scales only for the numbers it still binds, and no empty scales. */
|
|
25
|
+
function withBoundBindingScales(style) {
|
|
26
|
+
if (!Object.hasOwn(style, "variableBindingScales")) return style;
|
|
27
|
+
const scales = pickBy(style.variableBindingScales ?? {}, (_, field) => style.boundVariables?.[field] !== void 0);
|
|
28
|
+
if (isEmptyObject(scales)) return omit(style, ["variableBindingScales"]);
|
|
29
|
+
return {
|
|
30
|
+
...style,
|
|
31
|
+
variableBindingScales: scales
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** `runs` with each binding of `fields` holding `next` of the scale it resolves with. */
|
|
35
|
+
function runsWithBindingScales(node, runs, fields, next) {
|
|
36
|
+
const styleRuns = runs.map((run) => {
|
|
37
|
+
const bound = run.style.boundVariables;
|
|
38
|
+
if (!bound) return run;
|
|
39
|
+
let scales = run.style.variableBindingScales;
|
|
40
|
+
for (const field of fields) {
|
|
41
|
+
if (!bound[field]) continue;
|
|
42
|
+
const scale = next(runBindingScale(node, run.style, field));
|
|
43
|
+
if (scales?.[field] !== scale) scales = {
|
|
44
|
+
...scales,
|
|
45
|
+
[field]: scale
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
if (scales === run.style.variableBindingScales) return run;
|
|
49
|
+
return {
|
|
50
|
+
...run,
|
|
51
|
+
style: {
|
|
52
|
+
...run.style,
|
|
53
|
+
variableBindingScales: scales
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
});
|
|
57
|
+
return styleRuns.some((run, index) => run !== runs[index]) ? styleRuns : void 0;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* The runs with every size or spacing they bind holding the scale it resolves with as their own,
|
|
61
|
+
* or `undefined` when each already does. Called before the layer's scale for a field changes or
|
|
62
|
+
* goes, it migrates a run that still resolves with the layer's, so the run keeps its look.
|
|
63
|
+
*/
|
|
64
|
+
function pinnedRunBindingScales(node, fields = SCALED_RUN_BINDING_FIELD_LIST) {
|
|
65
|
+
const scaled = SCALED_RUN_BINDING_FIELD_LIST.filter((field) => fields.includes(field));
|
|
66
|
+
if (scaled.length === 0) return void 0;
|
|
67
|
+
return runsWithBindingScales(node, node.styleRuns, scaled, (scale) => scale);
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The binding scales of a layer rescaled by `factor`. `styleRuns` are the runs the rescale leaves,
|
|
71
|
+
* when it also scales their values, so each keeps them and gains its own scales.
|
|
72
|
+
*/
|
|
73
|
+
function scaleVariableBindingUnits(node, factor, styleRuns = node.styleRuns) {
|
|
4
74
|
const variableBindingScales = { ...node.variableBindingScales };
|
|
5
75
|
const variableAssignmentScales = { ...node.variableAssignmentScales };
|
|
6
76
|
for (const field of NUMERIC_FIELDS) {
|
|
7
|
-
if (field === "opacity" || field === "rotation") continue;
|
|
77
|
+
if (field === "opacity" || field === "rotation" || field === "fontWeight") continue;
|
|
8
78
|
if (field in node.boundVariables) variableBindingScales[field] = (variableBindingScales[field] ?? 1) * factor;
|
|
9
79
|
if (node.type === "INSTANCE") variableAssignmentScales[field] = (variableAssignmentScales[field] ?? 1) * factor;
|
|
10
80
|
}
|
|
11
|
-
|
|
81
|
+
const scaledRuns = runsWithBindingScales(node, styleRuns, SCALED_RUN_BINDING_FIELD_LIST, (scale) => scale * factor);
|
|
82
|
+
return scaledRuns ? {
|
|
83
|
+
variableBindingScales,
|
|
84
|
+
variableAssignmentScales,
|
|
85
|
+
styleRuns: scaledRuns
|
|
86
|
+
} : {
|
|
12
87
|
variableBindingScales,
|
|
13
88
|
variableAssignmentScales
|
|
14
89
|
};
|
|
15
90
|
}
|
|
16
91
|
//#endregion
|
|
17
|
-
export { scaleVariableBindingUnits };
|
|
92
|
+
export { SCALED_RUN_BINDING_FIELDS, pinnedRunBindingScales, runBindingScale, scaleVariableBindingUnits, withBoundBindingScales };
|
|
18
93
|
|
|
19
94
|
//# sourceMappingURL=units.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"units.js","names":[],"sources":["../../src/variables/units.ts"],"sourcesContent":["import type { SceneNode } from '../types'\nimport { NUMERIC_FIELDS } from './fields'\n\nexport function
|
|
1
|
+
{"version":3,"file":"units.js","names":[],"sources":["../../src/variables/units.ts"],"sourcesContent":["import { omit, pickBy } from 'es-toolkit/object'\nimport { isEmptyObject } from 'es-toolkit/predicate'\n\nimport type { CharacterStyleOverride, SceneNode, StyleRun, TextBindableField } from '../types'\nimport { NUMERIC_FIELDS } from './fields'\n\nconst SCALED_RUN_BINDING_FIELD_LIST = ['fontSize', 'letterSpacing', 'lineHeight'] as const\n\n/** A size or spacing a text's characters bind that a rescale scales with the layer. */\nexport type ScaledRunBindingField = (typeof SCALED_RUN_BINDING_FIELD_LIST)[number]\n\n/**\n * Numbers a text's characters bind that a rescale scales with the layer. Each run keeps its own\n * scale for the field, because the rescale scales the layer and its characters alike.\n */\nexport const SCALED_RUN_BINDING_FIELDS: ReadonlySet<string> = new Set(SCALED_RUN_BINDING_FIELD_LIST)\n\n/**\n * The scale a run's binding of `field` resolves with: the run's own, else, for a run saved before\n * runs kept one, the layer's scale for a size or spacing, as every run once shared it.\n */\nexport function runBindingScale(\n node: Pick<SceneNode, 'variableBindingScales'>,\n style: CharacterStyleOverride,\n field: TextBindableField\n): number {\n const own = style.variableBindingScales?.[field]\n if (own !== undefined) return own\n return SCALED_RUN_BINDING_FIELDS.has(field) ? (node.variableBindingScales[field] ?? 1) : 1\n}\n\n/** A run's style keeping scales only for the numbers it still binds, and no empty scales. */\nexport function withBoundBindingScales(style: CharacterStyleOverride): CharacterStyleOverride {\n if (!Object.hasOwn(style, 'variableBindingScales')) return style\n const scales = pickBy(\n style.variableBindingScales ?? {},\n (_, field) => style.boundVariables?.[field] !== undefined\n )\n if (isEmptyObject(scales)) return omit(style, ['variableBindingScales'])\n return { ...style, variableBindingScales: scales }\n}\n\n/** `runs` with each binding of `fields` holding `next` of the scale it resolves with. */\nfunction runsWithBindingScales(\n node: SceneNode,\n runs: readonly StyleRun[],\n fields: readonly ScaledRunBindingField[],\n next: (scale: number) => number\n): StyleRun[] | undefined {\n const styleRuns = runs.map((run) => {\n const bound = run.style.boundVariables\n if (!bound) return run\n let scales = run.style.variableBindingScales\n for (const field of fields) {\n if (!bound[field]) continue\n const scale = next(runBindingScale(node, run.style, field))\n if (scales?.[field] !== scale) scales = { ...scales, [field]: scale }\n }\n if (scales === run.style.variableBindingScales) return run\n return { ...run, style: { ...run.style, variableBindingScales: scales } }\n })\n return styleRuns.some((run, index) => run !== runs[index]) ? styleRuns : undefined\n}\n\n/**\n * The runs with every size or spacing they bind holding the scale it resolves with as their own,\n * or `undefined` when each already does. Called before the layer's scale for a field changes or\n * goes, it migrates a run that still resolves with the layer's, so the run keeps its look.\n */\nexport function pinnedRunBindingScales(\n node: SceneNode,\n fields: readonly string[] = SCALED_RUN_BINDING_FIELD_LIST\n): StyleRun[] | undefined {\n const scaled = SCALED_RUN_BINDING_FIELD_LIST.filter((field) => fields.includes(field))\n if (scaled.length === 0) return undefined\n return runsWithBindingScales(node, node.styleRuns, scaled, (scale) => scale)\n}\n\n/**\n * The binding scales of a layer rescaled by `factor`. `styleRuns` are the runs the rescale leaves,\n * when it also scales their values, so each keeps them and gains its own scales.\n */\nexport function scaleVariableBindingUnits(\n node: SceneNode,\n factor: number,\n styleRuns: readonly StyleRun[] = node.styleRuns\n): Partial<SceneNode> {\n const variableBindingScales = { ...node.variableBindingScales }\n const variableAssignmentScales = { ...node.variableAssignmentScales }\n for (const field of NUMERIC_FIELDS) {\n // A rescale keeps opacity, rotation, and font weight as they are.\n if (field === 'opacity' || field === 'rotation' || field === 'fontWeight') continue\n if (field in node.boundVariables)\n variableBindingScales[field] = (variableBindingScales[field] ?? 1) * factor\n if (node.type === 'INSTANCE')\n variableAssignmentScales[field] = (variableAssignmentScales[field] ?? 1) * factor\n }\n // Each run scales the sizes and spacings it binds in its own scale.\n const scaledRuns = runsWithBindingScales(\n node,\n styleRuns,\n SCALED_RUN_BINDING_FIELD_LIST,\n (scale) => scale * factor\n )\n return scaledRuns\n ? { variableBindingScales, variableAssignmentScales, styleRuns: scaledRuns }\n : { variableBindingScales, variableAssignmentScales }\n}\n"],"mappings":";;;;AAMA,MAAM,gCAAgC;CAAC;CAAY;CAAiB;AAAY;;;;;AAShF,MAAa,4BAAiD,IAAI,IAAI,6BAA6B;;;;;AAMnG,SAAgB,gBACd,MACA,OACA,OACQ;CACR,MAAM,MAAM,MAAM,wBAAwB;CAC1C,IAAI,QAAQ,KAAA,GAAW,OAAO;CAC9B,OAAO,0BAA0B,IAAI,KAAK,IAAK,KAAK,sBAAsB,UAAU,IAAK;AAC3F;;AAGA,SAAgB,uBAAuB,OAAuD;CAC5F,IAAI,CAAC,OAAO,OAAO,OAAO,uBAAuB,GAAG,OAAO;CAC3D,MAAM,SAAS,OACb,MAAM,yBAAyB,CAAC,IAC/B,GAAG,UAAU,MAAM,iBAAiB,WAAW,KAAA,CAClD;CACA,IAAI,cAAc,MAAM,GAAG,OAAO,KAA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AU,KAAK;CAC/E;CAEA,MAAM,aAAa,sBACjB,MACA,WACA,gCACC,UAAU,QAAQ,MACrB;CACA,OAAO,aACH;EAAE;EAAuB;EAA0B,WAAW;CAAW,IACzE;EAAE;EAAuB;CAAyB;AACxD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pairdraw/scene-graph",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist",
|
|
@@ -95,6 +95,11 @@
|
|
|
95
95
|
"import": "./dist/css/index.js",
|
|
96
96
|
"default": "./dist/css/index.js"
|
|
97
97
|
},
|
|
98
|
+
"./effects": {
|
|
99
|
+
"types": "./dist/effects.d.ts",
|
|
100
|
+
"import": "./dist/effects.js",
|
|
101
|
+
"default": "./dist/effects.js"
|
|
102
|
+
},
|
|
98
103
|
"./export-format": {
|
|
99
104
|
"types": "./dist/export-format.d.ts",
|
|
100
105
|
"import": "./dist/export-format.js",
|
package/src/checkpoint.ts
CHANGED
|
@@ -5,8 +5,8 @@ import type { InstanceOverrideState } from './instances/overrides'
|
|
|
5
5
|
import type { SceneNode } from './types'
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
|
-
* The document state outside its layers, copied: variables, collections, modes, the instance
|
|
9
|
-
*
|
|
8
|
+
* The document state outside its layers, copied: variables, collections, modes, the instance and
|
|
9
|
+
* connector indexes, libraries, images, and document metadata, which a rollback restores in place.
|
|
10
10
|
*/
|
|
11
11
|
function captureTables(graph: SceneGraph) {
|
|
12
12
|
const variableRefs = new Map(graph.variables)
|
|
@@ -16,8 +16,10 @@ function captureTables(graph: SceneGraph) {
|
|
|
16
16
|
variableCollections: graph.variableCollections,
|
|
17
17
|
activeMode: graph.activeMode,
|
|
18
18
|
instanceIndex: graph.instanceIndex,
|
|
19
|
+
connectorIds: graph.connectorIds,
|
|
19
20
|
enabledLibraries: graph.enabledLibraries,
|
|
20
21
|
rootId: graph.rootId,
|
|
22
|
+
documentKind: graph.documentKind,
|
|
21
23
|
figKiwiVersion: graph.figKiwiVersion,
|
|
22
24
|
figSchemaDeflated: graph.figSchemaDeflated,
|
|
23
25
|
documentColorSpace: graph.documentColorSpace
|
|
@@ -48,6 +50,7 @@ function captureTables(graph: SceneGraph) {
|
|
|
48
50
|
images.size !== graph.images.size ||
|
|
49
51
|
[...images].some(([id, bytes]) => graph.images.get(id) !== bytes) ||
|
|
50
52
|
graph.rootId !== snapshot.rootId ||
|
|
53
|
+
graph.documentKind !== snapshot.documentKind ||
|
|
51
54
|
graph.documentColorSpace !== snapshot.documentColorSpace ||
|
|
52
55
|
graph.figKiwiVersion !== snapshot.figKiwiVersion ||
|
|
53
56
|
!isEqual(graph.figSchemaDeflated, snapshot.figSchemaDeflated)
|
|
@@ -61,9 +64,12 @@ function captureTables(graph: SceneGraph) {
|
|
|
61
64
|
restoreObjects(graph.variableCollections, snapshot.variableCollections, collectionRefs)
|
|
62
65
|
restoreMap(graph.activeMode, structuredClone(snapshot.activeMode))
|
|
63
66
|
restoreMap(graph.instanceIndex, structuredClone(snapshot.instanceIndex))
|
|
67
|
+
graph.connectorIds.clear()
|
|
68
|
+
for (const id of snapshot.connectorIds) graph.connectorIds.add(id)
|
|
64
69
|
restoreMap(graph.enabledLibraries, structuredClone(snapshot.enabledLibraries))
|
|
65
70
|
restoreMap(graph.images, images)
|
|
66
71
|
graph.rootId = snapshot.rootId
|
|
72
|
+
graph.documentKind = snapshot.documentKind
|
|
67
73
|
graph.figKiwiVersion = snapshot.figKiwiVersion
|
|
68
74
|
graph.figSchemaDeflated = structuredClone(snapshot.figSchemaDeflated)
|
|
69
75
|
graph.documentColorSpace = snapshot.documentColorSpace
|
package/src/color/index.ts
CHANGED
|
@@ -2,11 +2,13 @@ export * from './contrast'
|
|
|
2
2
|
export * from './management'
|
|
3
3
|
export { normalizeColor } from './normalize'
|
|
4
4
|
export * from './okhcl'
|
|
5
|
+
export { colorSchema } from './schema'
|
|
5
6
|
|
|
6
7
|
import { parse, formatHex, formatHex8, formatRgb, converter, differenceEuclidean } from 'culori'
|
|
7
8
|
|
|
8
9
|
import { BLACK } from '../constants'
|
|
9
10
|
import type { Color } from '../primitives'
|
|
11
|
+
import { normalizeColor } from './normalize'
|
|
10
12
|
|
|
11
13
|
const toRGB = converter('rgb')
|
|
12
14
|
|
|
@@ -15,12 +17,8 @@ export function tryParseColor(input: string): Color | null {
|
|
|
15
17
|
const parsed = parse(input)
|
|
16
18
|
if (!parsed) return null
|
|
17
19
|
const rgb = toRGB(parsed)
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
g: rgb.g,
|
|
21
|
-
b: rgb.b,
|
|
22
|
-
a: parsed.alpha ?? 1
|
|
23
|
-
}
|
|
20
|
+
// culori leaves a `none` channel out, which normalizing reads as zero.
|
|
21
|
+
return normalizeColor({ r: rgb.r, g: rgb.g, b: rgb.b, a: parsed.alpha })
|
|
24
22
|
}
|
|
25
23
|
|
|
26
24
|
/** A CSS color, or black when `input` is not one. */
|
package/src/color/management.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { converter, formatCss, formatRgb, inGamut, parse, toGamut } from 'culori'
|
|
1
|
+
import { clampGamut, converter, formatCss, formatRgb, inGamut, parse, toGamut } from 'culori'
|
|
2
2
|
|
|
3
3
|
import type { Color } from '../primitives'
|
|
4
4
|
import type { DocumentColorSpace, Fill, SceneNode, Stroke } from '../types'
|
|
@@ -28,6 +28,7 @@ const toP3 = converter('p3')
|
|
|
28
28
|
const toDisplayableRGB = toGamut('rgb', 'oklch')
|
|
29
29
|
const toDisplayableP3 = toGamut('p3', 'oklch')
|
|
30
30
|
const isDisplayableRGB = inGamut('rgb')
|
|
31
|
+
const clampToRGB = clampGamut('rgb')
|
|
31
32
|
const isDisplayableP3 = inGamut('p3')
|
|
32
33
|
|
|
33
34
|
function normalizeOkLCH(color: OkHCLColor) {
|
|
@@ -158,7 +159,12 @@ export function parseDisplayableColor(input: string): Color | null {
|
|
|
158
159
|
const parsed = parse(input)
|
|
159
160
|
if (!parsed) return null
|
|
160
161
|
// Mapping through OKLCH shifts colors already in sRGB by float noise, so only map the rest.
|
|
161
|
-
|
|
162
|
+
// CSS clamps out-of-range sRGB channels and gamut-maps wider colors; clamping also removes the
|
|
163
|
+
// float noise gamut mapping can leave just outside 0..1.
|
|
164
|
+
const rgb = isDisplayableRGB(parsed)
|
|
165
|
+
? toRGB(parsed)
|
|
166
|
+
: clampToRGB(parsed.mode === 'rgb' ? parsed : toDisplayableRGB(parsed))
|
|
167
|
+
if (!rgb) return null
|
|
162
168
|
// culori leaves a `none` channel out, which normalizing reads as zero.
|
|
163
169
|
return normalizeColor({ r: rgb.r, g: rgb.g, b: rgb.b, a: parsed.alpha })
|
|
164
170
|
}
|
package/src/coordinate.ts
CHANGED
|
@@ -6,9 +6,12 @@ import type { SceneNode } from './types'
|
|
|
6
6
|
|
|
7
7
|
export function getWorldMatrix(node: SceneNode, graph: Pick<SceneGraph, 'getNode'>): Mat3 {
|
|
8
8
|
const chain: SceneNode[] = []
|
|
9
|
+
const visited = new Set<string>()
|
|
9
10
|
let current: SceneNode | undefined = node
|
|
10
11
|
|
|
11
|
-
|
|
12
|
+
// A parent cycle in bad data must end the walk instead of hanging it.
|
|
13
|
+
while (current && !visited.has(current.id)) {
|
|
14
|
+
visited.add(current.id)
|
|
12
15
|
chain.unshift(current)
|
|
13
16
|
if (!current.parentId) break
|
|
14
17
|
current = graph.getNode(current.parentId)
|
package/src/copy.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* no shared references between source and copy.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
+
import { normalizeEffects } from './effects'
|
|
11
12
|
import { geometryCommandCoordCount } from './geometry'
|
|
12
13
|
import { cloneInstanceOverrideState } from './instances/overrides'
|
|
13
14
|
import { createDefaultSourceMetadata } from './node-defaults'
|
|
@@ -55,10 +56,12 @@ export function copyStroke(s: Stroke): Stroke {
|
|
|
55
56
|
|
|
56
57
|
export function copyEffect(e: Effect): Effect {
|
|
57
58
|
if (e.type === 'SHADER') return structuredClone(e)
|
|
59
|
+
const normalized = normalizeEffects([e])[0] ?? e
|
|
60
|
+
if (normalized.type === 'SHADER') return structuredClone(normalized)
|
|
58
61
|
return {
|
|
59
|
-
...
|
|
60
|
-
color: { ...
|
|
61
|
-
offset: { ...
|
|
62
|
+
...normalized,
|
|
63
|
+
color: { ...normalized.color },
|
|
64
|
+
offset: { ...normalized.offset }
|
|
62
65
|
}
|
|
63
66
|
}
|
|
64
67
|
|
|
@@ -81,6 +84,8 @@ export function copyStyleRun(r: StyleRun): StyleRun {
|
|
|
81
84
|
if (r.style.lineHeight) copy.style.lineHeight = { ...r.style.lineHeight }
|
|
82
85
|
if (r.style.letterSpacing) copy.style.letterSpacing = { ...r.style.letterSpacing }
|
|
83
86
|
if (r.style.boundVariables) copy.style.boundVariables = { ...r.style.boundVariables }
|
|
87
|
+
if (r.style.variableBindingScales)
|
|
88
|
+
copy.style.variableBindingScales = { ...r.style.variableBindingScales }
|
|
84
89
|
return copy
|
|
85
90
|
}
|
|
86
91
|
|
package/src/css/values.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import valueParser from 'postcss-value-parser'
|
|
2
2
|
|
|
3
|
-
import {
|
|
3
|
+
import { parseDisplayableColor } from '../color'
|
|
4
4
|
import type { Color } from '../primitives'
|
|
5
5
|
|
|
6
6
|
/** Pixels in a rem, as browsers use by default. */
|
|
@@ -30,7 +30,8 @@ export function parseCSSNumber(value: string | undefined): number | null {
|
|
|
30
30
|
/** A CSS color that paints something; null for an invalid or fully transparent one. */
|
|
31
31
|
export function parseCSSColor(value: string | undefined): Color | null {
|
|
32
32
|
if (!value) return null
|
|
33
|
-
|
|
33
|
+
// CSS clamps `rgb()` channels and maps wide-gamut colors into sRGB, as a stored color must be.
|
|
34
|
+
const color = parseDisplayableColor(value.trim())
|
|
34
35
|
return color && color.a > 0 ? color : null
|
|
35
36
|
}
|
|
36
37
|
|
package/src/effects.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { Vector } from './primitives'
|
|
2
|
+
import type { Effect, ShaderEffect, ShadowEffect } from './types'
|
|
3
|
+
|
|
4
|
+
const SHADOW_OFFSET: Vector = { x: 0, y: 4 }
|
|
5
|
+
const BLUR_OFFSET: Vector = { x: 0, y: 0 }
|
|
6
|
+
|
|
7
|
+
/** A shadow or blur whose offset may still be missing or only partly present. */
|
|
8
|
+
type ShadowInput = Omit<ShadowEffect, 'offset'> & {
|
|
9
|
+
offset?: Partial<Vector> | null
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function fallbackOffset(type: ShadowEffect['type']): Vector {
|
|
13
|
+
return type === 'DROP_SHADOW' || type === 'INNER_SHADOW' ? SHADOW_OFFSET : BLUR_OFFSET
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function component(offset: object, key: 'x' | 'y', fallback: number): number {
|
|
17
|
+
if (!(key in offset)) return fallback
|
|
18
|
+
const value: unknown = Reflect.get(offset, key)
|
|
19
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : fallback
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** A new offset when `effect.offset` is missing or not finite; null when it can stay. */
|
|
23
|
+
function finiteOffset(effect: ShadowInput): Vector | null {
|
|
24
|
+
const fallback = fallbackOffset(effect.type)
|
|
25
|
+
const offset: unknown = effect.offset
|
|
26
|
+
if (offset === null || typeof offset !== 'object') return { x: fallback.x, y: fallback.y }
|
|
27
|
+
const x = component(offset, 'x', fallback.x)
|
|
28
|
+
const y = component(offset, 'y', fallback.y)
|
|
29
|
+
if (Reflect.get(offset, 'x') === x && Reflect.get(offset, 'y') === y) return null
|
|
30
|
+
return { x, y }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function isStoredShadow(effect: ShadowInput): effect is ShadowEffect {
|
|
34
|
+
const offset = effect.offset
|
|
35
|
+
return (
|
|
36
|
+
!!offset &&
|
|
37
|
+
typeof offset.x === 'number' &&
|
|
38
|
+
Number.isFinite(offset.x) &&
|
|
39
|
+
typeof offset.y === 'number' &&
|
|
40
|
+
Number.isFinite(offset.y)
|
|
41
|
+
)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function withFiniteOffset(effect: ShadowInput): Effect {
|
|
45
|
+
const offset = finiteOffset(effect)
|
|
46
|
+
if (!offset) {
|
|
47
|
+
if (isStoredShadow(effect)) return effect
|
|
48
|
+
return { ...effect, offset: fallbackOffset(effect.type) }
|
|
49
|
+
}
|
|
50
|
+
return { ...effect, offset }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function isStoredEffect(effect: ShaderEffect | ShadowInput): effect is Effect {
|
|
54
|
+
return effect.type === 'SHADER' || isStoredShadow(effect)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Shadows and blurs keep a finite offset. A drop or inner shadow missing one uses `{x: 0, y: 4}`,
|
|
59
|
+
* the same default as `dropShadow()` and `set_effects`; a blur uses `{x: 0, y: 0}`. Shader effects
|
|
60
|
+
* are left alone. An array that is already valid is returned as itself.
|
|
61
|
+
*/
|
|
62
|
+
export function normalizeEffects(effects: (ShaderEffect | ShadowInput)[]): Effect[] {
|
|
63
|
+
let next: Effect[] | null = null
|
|
64
|
+
for (const [index, effect] of effects.entries()) {
|
|
65
|
+
const normalized = effect.type === 'SHADER' ? effect : withFiniteOffset(effect)
|
|
66
|
+
if (normalized === effect) {
|
|
67
|
+
if (next && isStoredEffect(effect)) next.push(effect)
|
|
68
|
+
continue
|
|
69
|
+
}
|
|
70
|
+
next ??= effects.slice(0, index).filter(isStoredEffect)
|
|
71
|
+
next.push(normalized)
|
|
72
|
+
}
|
|
73
|
+
if (next) return next
|
|
74
|
+
if (effects.every(isStoredEffect)) return effects
|
|
75
|
+
return effects.filter(isStoredEffect)
|
|
76
|
+
}
|