@pairdraw/scene-graph 0.18.0 → 0.19.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/components/index.d.ts +2 -2
- package/dist/components/index.js +2 -2
- package/dist/components/properties.d.ts +6 -1
- package/dist/components/properties.d.ts.map +1 -1
- package/dist/components/properties.js +14 -3
- package/dist/components/properties.js.map +1 -1
- package/dist/copy.d.ts.map +1 -1
- package/dist/copy.js +1 -0
- package/dist/copy.js.map +1 -1
- package/dist/css/gradient.d.ts +23 -0
- package/dist/css/gradient.d.ts.map +1 -0
- package/dist/css/gradient.js +404 -0
- package/dist/css/gradient.js.map +1 -0
- package/dist/css/index.d.ts +2 -1
- package/dist/css/index.js +2 -1
- package/dist/css/shadows.d.ts.map +1 -1
- package/dist/css/shadows.js +2 -13
- package/dist/css/shadows.js.map +1 -1
- package/dist/css/values.js +24 -1
- package/dist/css/values.js.map +1 -1
- package/dist/font-style.d.ts +2 -1
- package/dist/font-style.d.ts.map +1 -1
- package/dist/font-style.js +31 -6
- package/dist/font-style.js.map +1 -1
- package/dist/geometry.d.ts +10 -1
- package/dist/geometry.d.ts.map +1 -1
- package/dist/geometry.js +21 -6
- package/dist/geometry.js.map +1 -1
- package/dist/graph.d.ts +49 -3
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +179 -17
- package/dist/graph.js.map +1 -1
- package/dist/hit-test.d.ts +3 -1
- package/dist/hit-test.d.ts.map +1 -1
- package/dist/hit-test.js +38 -23
- package/dist/hit-test.js.map +1 -1
- package/dist/icons/index.d.ts +2 -2
- package/dist/icons/index.js +2 -2
- package/dist/icons/model.d.ts +8 -2
- package/dist/icons/model.d.ts.map +1 -1
- package/dist/icons/model.js +10 -1
- package/dist/icons/model.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/instances/assignments.js +40 -6
- package/dist/instances/assignments.js.map +1 -1
- package/dist/instances/fields.d.ts +2 -2
- package/dist/instances/fields.d.ts.map +1 -1
- package/dist/instances/fields.js +18 -1
- package/dist/instances/fields.js.map +1 -1
- package/dist/instances/index.d.ts +38 -2
- package/dist/instances/index.d.ts.map +1 -1
- package/dist/instances/index.js +134 -15
- package/dist/instances/index.js.map +1 -1
- package/dist/instances/overrides.d.ts +10 -1
- package/dist/instances/overrides.d.ts.map +1 -1
- package/dist/instances/overrides.js +28 -2
- package/dist/instances/overrides.js.map +1 -1
- package/dist/instances/placement.js +1 -1
- package/dist/instances/placement.js.map +1 -1
- package/dist/instances/swap-overrides.js +94 -0
- package/dist/instances/swap-overrides.js.map +1 -0
- package/dist/instances/sync.js +90 -12
- package/dist/instances/sync.js.map +1 -1
- package/dist/layout/draw-order.d.ts +11 -0
- package/dist/layout/draw-order.d.ts.map +1 -0
- package/dist/layout/draw-order.js +14 -0
- package/dist/layout/draw-order.js.map +1 -0
- package/dist/layout/index.d.ts +2 -1
- package/dist/layout/index.js +2 -1
- package/dist/node-defaults.d.ts +11 -1
- package/dist/node-defaults.d.ts.map +1 -1
- package/dist/node-defaults.js +16 -1
- package/dist/node-defaults.js.map +1 -1
- package/dist/order-keys.d.ts +3 -1
- package/dist/order-keys.d.ts.map +1 -1
- package/dist/order-keys.js +6 -1
- package/dist/order-keys.js.map +1 -1
- package/dist/resize.d.ts +29 -9
- package/dist/resize.d.ts.map +1 -1
- package/dist/resize.js +95 -62
- package/dist/resize.js.map +1 -1
- package/dist/shared-styles.d.ts.map +1 -1
- package/dist/shared-styles.js +1 -8
- package/dist/shared-styles.js.map +1 -1
- package/dist/slots/authoring.d.ts +3 -2
- package/dist/slots/authoring.d.ts.map +1 -1
- package/dist/slots/authoring.js +5 -3
- package/dist/slots/authoring.js.map +1 -1
- package/dist/slots/content.d.ts.map +1 -1
- package/dist/slots/content.js +4 -1
- package/dist/slots/content.js.map +1 -1
- package/dist/source-metadata.d.ts +4 -2
- package/dist/source-metadata.d.ts.map +1 -1
- package/dist/source-metadata.js +10 -3
- package/dist/source-metadata.js.map +1 -1
- package/dist/strokes.d.ts +39 -0
- package/dist/strokes.d.ts.map +1 -0
- package/dist/strokes.js +104 -0
- package/dist/strokes.js.map +1 -0
- package/dist/text/direction.d.ts +6 -2
- package/dist/text/direction.d.ts.map +1 -1
- package/dist/text/direction.js +2 -1
- package/dist/text/direction.js.map +1 -1
- package/dist/text/index.d.ts +3 -3
- package/dist/text/index.js +3 -3
- package/dist/text/lengths.d.ts +6 -1
- package/dist/text/lengths.d.ts.map +1 -1
- package/dist/text/lengths.js +10 -1
- package/dist/text/lengths.js.map +1 -1
- package/dist/text/overflow.d.ts +22 -6
- package/dist/text/overflow.d.ts.map +1 -1
- package/dist/text/overflow.js +24 -6
- package/dist/text/overflow.js.map +1 -1
- package/dist/transfer/nodes.js +9 -5
- package/dist/transfer/nodes.js.map +1 -1
- package/dist/types.d.ts +18 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/undo.d.ts +36 -1
- package/dist/undo.d.ts.map +1 -1
- package/dist/undo.js +52 -2
- package/dist/undo.js.map +1 -1
- package/dist/variables/bindings.d.ts +14 -6
- package/dist/variables/bindings.d.ts.map +1 -1
- package/dist/variables/bindings.js +42 -67
- package/dist/variables/bindings.js.map +1 -1
- package/dist/variables/formula/signatures.js +1 -1
- package/dist/variables/index.d.ts +10 -4
- package/dist/variables/index.d.ts.map +1 -1
- package/dist/variables/index.js +58 -15
- package/dist/variables/index.js.map +1 -1
- package/dist/variables/paints.d.ts +101 -0
- package/dist/variables/paints.d.ts.map +1 -0
- package/dist/variables/paints.js +313 -0
- package/dist/variables/paints.js.map +1 -0
- package/dist/variables/resolution.d.ts +14 -1
- package/dist/variables/resolution.d.ts.map +1 -1
- package/dist/variables/resolution.js +44 -4
- package/dist/variables/resolution.js.map +1 -1
- package/dist/variables/subtree.js +17 -0
- package/dist/variables/subtree.js.map +1 -0
- package/package.json +6 -1
- package/src/components/properties.ts +17 -2
- package/src/copy.ts +1 -0
- package/src/css/gradient.ts +438 -0
- package/src/css/index.ts +1 -0
- package/src/css/shadows.ts +2 -18
- package/src/css/values.ts +27 -1
- package/src/font-style.ts +38 -4
- package/src/geometry.ts +25 -6
- package/src/graph.ts +207 -17
- package/src/hit-test.ts +67 -24
- package/src/icons/model.ts +11 -1
- package/src/instances/assignments.ts +65 -7
- package/src/instances/fields.ts +21 -0
- package/src/instances/index.ts +237 -14
- package/src/instances/overrides.ts +36 -1
- package/src/instances/placement.ts +5 -1
- package/src/instances/swap-overrides.ts +123 -0
- package/src/instances/sync.ts +139 -12
- package/src/layout/draw-order.ts +13 -0
- package/src/layout/index.ts +1 -0
- package/src/node-defaults.ts +21 -0
- package/src/order-keys.ts +6 -0
- package/src/resize.ts +133 -69
- package/src/shared-styles.ts +1 -3
- package/src/slots/authoring.ts +5 -3
- package/src/slots/content.ts +4 -1
- package/src/source-metadata.ts +18 -3
- package/src/strokes.ts +121 -0
- package/src/text/direction.ts +7 -5
- package/src/text/lengths.ts +10 -0
- package/src/text/overflow.ts +30 -7
- package/src/transfer/nodes.ts +7 -5
- package/src/types.ts +17 -0
- package/src/undo.ts +79 -2
- package/src/variables/bindings.ts +52 -74
- package/src/variables/index.ts +80 -14
- package/src/variables/paints.ts +413 -0
- package/src/variables/resolution.ts +56 -5
- package/src/variables/subtree.ts +15 -0
package/dist/undo.d.ts
CHANGED
|
@@ -5,10 +5,32 @@ interface UndoEntry {
|
|
|
5
5
|
inverse: () => void;
|
|
6
6
|
coalesceKey?: string;
|
|
7
7
|
}
|
|
8
|
+
/**
|
|
9
|
+
* Committed history, kept aside while another graph is open so a document opened in the same
|
|
10
|
+
* editor never inherits the last one's steps.
|
|
11
|
+
*/
|
|
12
|
+
interface UndoHistory {
|
|
13
|
+
readonly undo: readonly UndoEntry[];
|
|
14
|
+
readonly redo: readonly UndoEntry[];
|
|
15
|
+
}
|
|
8
16
|
interface UndoManagerOptions {
|
|
9
17
|
limit?: number;
|
|
10
18
|
/** Called after recording, undoing, redoing, or clearing committed history. */
|
|
11
19
|
onChange?: () => void;
|
|
20
|
+
/**
|
|
21
|
+
* The edited-field marks an edit adds. A step takes its marks back when undone and puts them
|
|
22
|
+
* back when redone, so a layer ends a step exactly as it began one, marks included.
|
|
23
|
+
*/
|
|
24
|
+
marks?: UndoSourceMarks;
|
|
25
|
+
}
|
|
26
|
+
/** Marks an edit left on layers, kept by the graph for one undo step. */
|
|
27
|
+
interface UndoSourceMarks {
|
|
28
|
+
/** The marks added since the last step, which that step owns. */
|
|
29
|
+
take: () => Array<[nodeId: string, field: string]>;
|
|
30
|
+
add: (nodeId: string, fields: readonly string[]) => void;
|
|
31
|
+
remove: (nodeId: string, fields: readonly string[]) => void;
|
|
32
|
+
/** Runs a replay that writes values only, so it marks no field of its own. */
|
|
33
|
+
preserve: (run: () => void) => void;
|
|
12
34
|
}
|
|
13
35
|
/** How many edits undo keeps by default. */
|
|
14
36
|
declare const DEFAULT_HISTORY_LIMIT = 200;
|
|
@@ -21,11 +43,17 @@ declare class UndoManager {
|
|
|
21
43
|
private readonly settlers;
|
|
22
44
|
private readonly limit;
|
|
23
45
|
private readonly onChange;
|
|
46
|
+
private readonly marks;
|
|
24
47
|
constructor(options?: UndoManagerOptions);
|
|
25
48
|
apply(entry: UndoEntry): void;
|
|
26
49
|
execute(entry: UndoEntry): void;
|
|
27
50
|
push(entry: UndoEntry): void;
|
|
28
51
|
record(entry: UndoEntry): void;
|
|
52
|
+
/**
|
|
53
|
+
* The step's replay writes values without marking them, then the marks the edit added come
|
|
54
|
+
* back on redo and go with it on undo.
|
|
55
|
+
*/
|
|
56
|
+
private withSourceMarks;
|
|
29
57
|
/**
|
|
30
58
|
* Records an entry as a step of its own, outside the batches being built, such as an agent's
|
|
31
59
|
* edit made while a colour picker is open. Batches settle first, so the step follows the
|
|
@@ -47,6 +75,13 @@ declare class UndoManager {
|
|
|
47
75
|
/** Abandon provisional history without replaying it or changing committed undo/redo entries. */
|
|
48
76
|
discardBatches(): void;
|
|
49
77
|
clear(): void;
|
|
78
|
+
/**
|
|
79
|
+
* Takes the committed history out, for the graph it was recorded on, and leaves this one empty;
|
|
80
|
+
* `adoptHistory` puts it back when that graph opens again.
|
|
81
|
+
*/
|
|
82
|
+
takeHistory(): UndoHistory;
|
|
83
|
+
/** Makes `history`, recorded on the graph now open, the committed one. */
|
|
84
|
+
adoptHistory(history: UndoHistory | undefined): void;
|
|
50
85
|
/** Whether undo or redo is replaying a step, whose changes are history rather than new edits. */
|
|
51
86
|
get isReplaying(): boolean;
|
|
52
87
|
/**
|
|
@@ -90,5 +125,5 @@ declare class UndoManager {
|
|
|
90
125
|
private trimUndoStack;
|
|
91
126
|
}
|
|
92
127
|
//#endregion
|
|
93
|
-
export { DEFAULT_HISTORY_LIMIT, UndoEntry, UndoManager, UndoManagerOptions };
|
|
128
|
+
export { DEFAULT_HISTORY_LIMIT, UndoEntry, UndoHistory, UndoManager, UndoManagerOptions, UndoSourceMarks };
|
|
94
129
|
//# sourceMappingURL=undo.d.ts.map
|
package/dist/undo.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"undo.d.ts","names":[],"sources":["../src/undo.ts"],"mappings":";UAAiB;EACf;EACA;EACA;EACA;;
|
|
1
|
+
{"version":3,"file":"undo.d.ts","names":[],"sources":["../src/undo.ts"],"mappings":";UAAiB;EACf;EACA;EACA;EACA;;;;;;UAOe;WACN,eAAe;WACf,eAAe;;UAGT;EACf;;EAEA;;;;;EAKA,QAAQ;;;UAIO;;EAEf,YAAY,OAAO,gBAAgB;EACnC,MAAM,gBAAgB;EACtB,SAAS,gBAAgB;;EAEzB,WAAW;;;cAUA;cAEA;UACH;UACA;UACA;UACA;UACA;mBACS;mBACA;mBACA;mBACA;EAEL,YAAA,UAAS;EAMrB,MAAM,OAAO;EAIb,QAAQ,OAAO;EAKf,KAAK,OAAO;EAIZ,OAAO,OAAO;;;;;UAcN;;;;;;EA+BR,SAAS,OAAO;;;;;EAShB,gBAAgB;UAKR;EAIR;EAUA;EAUA,WAAW,eAAe;EAI1B;EAUA,SAAS,GAAG,eAAe,UAAU,GAAG,uBAAuB;EAY/D;;EAOA;EAIA;;;;;EAYA,eAAe;;EASf,aAAa,SAAS;;MAOlB;;;;;;EASJ,eAAe,OAAO;UAoBd;MASJ;;;;;EAQJ;;;;;MAcI;;MAKA;MAKA;;;;;EAQJ,SAAS,iBAAY;;EAKrB,SAAS,iBAAY;;;;;EAQrB,QAAQ,OAAO;MAMX;MAIA;cAIQ;UAIJ;UASA;UAeA"}
|
package/dist/undo.js
CHANGED
|
@@ -10,9 +10,11 @@ var UndoManager = class {
|
|
|
10
10
|
settlers = /* @__PURE__ */ new Set();
|
|
11
11
|
limit;
|
|
12
12
|
onChange;
|
|
13
|
+
marks;
|
|
13
14
|
constructor(options = {}) {
|
|
14
15
|
this.limit = options.limit ?? 200;
|
|
15
16
|
this.onChange = options.onChange;
|
|
17
|
+
this.marks = options.marks;
|
|
16
18
|
}
|
|
17
19
|
apply(entry) {
|
|
18
20
|
this.execute(entry);
|
|
@@ -25,12 +27,39 @@ var UndoManager = class {
|
|
|
25
27
|
this.record(entry);
|
|
26
28
|
}
|
|
27
29
|
record(entry) {
|
|
30
|
+
const marked = this.withSourceMarks(entry);
|
|
28
31
|
const batch = this.currentBatch;
|
|
29
32
|
if (batch) {
|
|
30
|
-
batch.entries.push(
|
|
33
|
+
batch.entries.push(marked);
|
|
31
34
|
return;
|
|
32
35
|
}
|
|
33
|
-
this.pushUndoEntry(
|
|
36
|
+
this.pushUndoEntry(marked);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The step's replay writes values without marking them, then the marks the edit added come
|
|
40
|
+
* back on redo and go with it on undo.
|
|
41
|
+
*/
|
|
42
|
+
withSourceMarks(entry) {
|
|
43
|
+
const marks = this.marks;
|
|
44
|
+
if (!marks) return entry;
|
|
45
|
+
const taken = marks.take();
|
|
46
|
+
const byNode = /* @__PURE__ */ new Map();
|
|
47
|
+
for (const [id, field] of taken) {
|
|
48
|
+
const fields = byNode.get(id);
|
|
49
|
+
if (fields) fields.push(field);
|
|
50
|
+
else byNode.set(id, [field]);
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
...entry,
|
|
54
|
+
forward: () => {
|
|
55
|
+
entry.forward();
|
|
56
|
+
for (const [id, fields] of byNode) marks.add(id, fields);
|
|
57
|
+
},
|
|
58
|
+
inverse: () => {
|
|
59
|
+
marks.preserve(() => entry.inverse());
|
|
60
|
+
for (const [id, fields] of byNode) marks.remove(id, fields);
|
|
61
|
+
}
|
|
62
|
+
};
|
|
34
63
|
}
|
|
35
64
|
/**
|
|
36
65
|
* Records an entry as a step of its own, outside the batches being built, such as an agent's
|
|
@@ -109,8 +138,29 @@ var UndoManager = class {
|
|
|
109
138
|
this.undoStack = [];
|
|
110
139
|
this.redoStack = [];
|
|
111
140
|
this.discardBatches();
|
|
141
|
+
this.marks?.take();
|
|
112
142
|
this.onChange?.();
|
|
113
143
|
}
|
|
144
|
+
/**
|
|
145
|
+
* Takes the committed history out, for the graph it was recorded on, and leaves this one empty;
|
|
146
|
+
* `adoptHistory` puts it back when that graph opens again.
|
|
147
|
+
*/
|
|
148
|
+
takeHistory() {
|
|
149
|
+
const history = {
|
|
150
|
+
undo: this.undoStack,
|
|
151
|
+
redo: this.redoStack
|
|
152
|
+
};
|
|
153
|
+
this.undoStack = [];
|
|
154
|
+
this.redoStack = [];
|
|
155
|
+
this.discardBatches();
|
|
156
|
+
return history;
|
|
157
|
+
}
|
|
158
|
+
/** Makes `history`, recorded on the graph now open, the committed one. */
|
|
159
|
+
adoptHistory(history) {
|
|
160
|
+
this.undoStack = history ? [...history.undo] : [];
|
|
161
|
+
this.redoStack = history ? [...history.redo] : [];
|
|
162
|
+
this.discardBatches();
|
|
163
|
+
}
|
|
114
164
|
/** Whether undo or redo is replaying a step, whose changes are history rather than new edits. */
|
|
115
165
|
get isReplaying() {
|
|
116
166
|
return this.replaying > 0;
|
package/dist/undo.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"undo.js","names":[],"sources":["../src/undo.ts"],"sourcesContent":["export interface UndoEntry {\n label: string\n forward: () => void\n inverse: () => void\n coalesceKey?: string\n}\n\nexport interface UndoManagerOptions {\n limit?: number\n /** Called after recording, undoing, redoing, or clearing committed history. */\n onChange?: () => void\n}\n\ninterface UndoBatch {\n label: string\n entries: UndoEntry[]\n coalesceKey?: string\n}\n\n/** How many edits undo keeps by default. */\nexport const DEFAULT_HISTORY_LIMIT = 200\n\nexport class UndoManager {\n private undoStack: UndoEntry[] = []\n private redoStack: UndoEntry[] = []\n private batches: UndoBatch[] = []\n private replaying = 0\n private openEdits = 0\n private readonly settlers = new Set<() => void>()\n private readonly limit: number\n private readonly onChange: (() => void) | undefined\n\n constructor(options: UndoManagerOptions = {}) {\n this.limit = options.limit ?? DEFAULT_HISTORY_LIMIT\n this.onChange = options.onChange\n }\n\n apply(entry: UndoEntry): void {\n this.execute(entry)\n }\n\n execute(entry: UndoEntry): void {\n entry.forward()\n this.record(entry)\n }\n\n push(entry: UndoEntry): void {\n this.record(entry)\n }\n\n record(entry: UndoEntry): void {\n const batch = this.currentBatch\n if (batch) {\n batch.entries.push(entry)\n return\n }\n this.pushUndoEntry(entry)\n }\n\n /**\n * Records an entry as a step of its own, outside the batches being built, such as an agent's\n * edit made while a colour picker is open. Batches settle first, so the step follows the\n * changes they hold so far.\n */\n pushStep(entry: UndoEntry): void {\n this.settle()\n this.pushUndoEntry(entry)\n }\n\n /**\n * Registers a hook that commits an edit still being coalesced, such as a run of picker changes.\n * Undo and redo run every hook first, so they act on the newest change.\n */\n onBeforeHistory(settle: () => void): () => void {\n this.settlers.add(settle)\n return () => this.settlers.delete(settle)\n }\n\n private settle() {\n for (const settle of this.settlers) settle()\n }\n\n undo(): string | null {\n this.settle()\n const entry = this.undoStack.pop()\n if (!entry) return null\n this.replay(() => entry.inverse())\n this.redoStack.push(entry)\n this.onChange?.()\n return entry.label\n }\n\n redo(): string | null {\n this.settle()\n const entry = this.redoStack.pop()\n if (!entry) return null\n this.replay(() => entry.forward())\n this.undoStack.push(entry)\n this.onChange?.()\n return entry.label\n }\n\n beginBatch(label: string, coalesceKey?: string): void {\n this.batches.push({ label, entries: [], coalesceKey })\n }\n\n commitBatch(): void {\n const batch = this.batches.pop()\n if (!batch || batch.entries.length === 0) return\n\n const entry = this.createBatchEntry(batch)\n const parentBatch = this.currentBatch\n if (parentBatch) parentBatch.entries.push(entry)\n else this.pushUndoEntry(entry)\n }\n\n runBatch<T>(label: string, fn: () => T, coalesceKey?: string): T {\n this.beginBatch(label, coalesceKey)\n try {\n const result = fn()\n this.commitBatch()\n return result\n } catch (error) {\n this.rollbackBatch()\n throw error\n }\n }\n\n rollbackBatch(): void {\n const batch = this.batches.pop()\n if (!batch) return\n for (const entry of batch.entries.toReversed()) entry.inverse()\n }\n\n /** Abandon provisional history without replaying it or changing committed undo/redo entries. */\n discardBatches(): void {\n this.batches = []\n }\n\n clear(): void {\n this.undoStack = []\n this.redoStack = []\n this.discardBatches()\n this.onChange?.()\n }\n\n /** Whether undo or redo is replaying a step, whose changes are history rather than new edits. */\n get isReplaying(): boolean {\n return this.replaying > 0\n }\n\n /**\n * Adds a change that the newest step caused, as one an editor makes in response to it, so undo\n * and redo apply them together. Inside a batch it joins the batch. False with no step to join,\n * including after an undo, when the newest step is on the redo stack and not applied.\n */\n extendLastStep(entry: UndoEntry): boolean {\n if (this.currentBatch) {\n this.currentBatch.entries.push(entry)\n return true\n }\n const last = this.undoStack.at(-1)\n if (!last || this.redoStack.length > 0) return false\n // The step keeps its identity, so callers that hold it still find it in the history.\n const { forward, inverse } = last\n last.forward = () => {\n forward()\n entry.forward()\n }\n last.inverse = () => {\n entry.inverse()\n inverse()\n }\n return true\n }\n\n private replay(step: () => void) {\n this.replaying++\n try {\n step()\n } finally {\n this.replaying--\n }\n }\n\n get isBatching(): boolean {\n return this.batches.length > 0\n }\n\n /**\n * Marks an edit whose step is recorded when it ends, such as an agent's call that awaits fonts\n * or a layout before it finishes. Returns the function that ends it; ending it twice is a no-op.\n */\n openEdit(): () => void {\n this.openEdits++\n let open = true\n return () => {\n if (!open) return\n open = false\n this.openEdits--\n }\n }\n\n /**\n * Whether a batch or an edit opened with `openEdit` will record a step for the changes made now,\n * so they are not edits outside the history.\n */\n get isRecording(): boolean {\n return this.isBatching || this.openEdits > 0\n }\n\n /** Committed history, or changes in an open batch that a settling hook commits first. */\n get canUndo(): boolean {\n if (this.undoStack.length > 0) return true\n return this.settlers.size > 0 && this.batches.some((batch) => batch.entries.length > 0)\n }\n\n get canRedo(): boolean {\n return this.redoStack.length > 0\n }\n\n /**\n * The entry `depth` steps below the top of the undo stack, so a caller that pushed entries\n * can tell whether they are still the most recent ones.\n */\n peekUndo(depth = 0): UndoEntry | undefined {\n return this.undoStack.at(-1 - depth)\n }\n\n /** The entry `depth` steps below the top of the redo stack, the next one Redo applies at 0. */\n peekRedo(depth = 0): UndoEntry | undefined {\n return this.redoStack.at(-1 - depth)\n }\n\n /**\n * Whether `entry` is applied (on the undo stack) or undone (on the redo stack); null once it\n * left the history, trimmed or dropped when an edit cleared Redo.\n */\n stateOf(entry: UndoEntry): 'applied' | 'undone' | null {\n if (this.undoStack.includes(entry)) return 'applied'\n if (this.redoStack.includes(entry)) return 'undone'\n return null\n }\n\n get undoLabel(): string | null {\n return this.undoStack.at(-1)?.label ?? null\n }\n\n get redoLabel(): string | null {\n return this.redoStack.at(-1)?.label ?? null\n }\n\n private get currentBatch(): UndoBatch | null {\n return this.batches.at(-1) ?? null\n }\n\n private createBatchEntry(batch: UndoBatch): UndoEntry {\n return {\n label: batch.label,\n forward: () => batch.entries.forEach((entry) => entry.forward()),\n inverse: () => batch.entries.toReversed().forEach((entry) => entry.inverse()),\n coalesceKey: batch.coalesceKey\n }\n }\n\n private pushUndoEntry(entry: UndoEntry): void {\n const previous = this.undoStack.at(-1)\n if (entry.coalesceKey && previous?.coalesceKey === entry.coalesceKey) {\n this.undoStack[this.undoStack.length - 1] = {\n ...entry,\n inverse: previous.inverse\n }\n } else {\n this.undoStack.push(entry)\n }\n this.redoStack = []\n this.trimUndoStack()\n this.onChange?.()\n }\n\n private trimUndoStack(): void {\n if (!Number.isFinite(this.limit) || this.limit <= 0) return\n const overflow = this.undoStack.length - this.limit\n if (overflow > 0) this.undoStack.splice(0, overflow)\n }\n}\n"],"mappings":";;AAoBA,MAAa,wBAAwB;AAErC,IAAa,cAAb,MAAyB;CACvB,YAAiC,CAAC;CAClC,YAAiC,CAAC;CAClC,UAA+B,CAAC;CAChC,YAAoB;CACpB,YAAoB;CACpB,2BAA4B,IAAI,IAAgB;CAChD;CACA;CAEA,YAAY,UAA8B,CAAC,GAAG;EAC5C,KAAK,QAAQ,QAAQ,SAAA;EACrB,KAAK,WAAW,QAAQ;CAC1B;CAEA,MAAM,OAAwB;EAC5B,KAAK,QAAQ,KAAK;CACpB;CAEA,QAAQ,OAAwB;EAC9B,MAAM,QAAQ;EACd,KAAK,OAAO,KAAK;CACnB;CAEA,KAAK,OAAwB;EAC3B,KAAK,OAAO,KAAK;CACnB;CAEA,OAAO,OAAwB;EAC7B,MAAM,QAAQ,KAAK;EACnB,IAAI,OAAO;GACT,MAAM,QAAQ,KAAK,KAAK;GACxB;EACF;EACA,KAAK,cAAc,KAAK;CAC1B;;;;;;CAOA,SAAS,OAAwB;EAC/B,KAAK,OAAO;EACZ,KAAK,cAAc,KAAK;CAC1B;;;;;CAMA,gBAAgB,QAAgC;EAC9C,KAAK,SAAS,IAAI,MAAM;EACxB,aAAa,KAAK,SAAS,OAAO,MAAM;CAC1C;CAEA,SAAiB;EACf,KAAK,MAAM,UAAU,KAAK,UAAU,OAAO;CAC7C;CAEA,OAAsB;EACpB,KAAK,OAAO;EACZ,MAAM,QAAQ,KAAK,UAAU,IAAI;EACjC,IAAI,CAAC,OAAO,OAAO;EACnB,KAAK,aAAa,MAAM,QAAQ,CAAC;EACjC,KAAK,UAAU,KAAK,KAAK;EACzB,KAAK,WAAW;EAChB,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;EAC3C,OAAO,KAAK,QAAQ,GAAG,EAAE,KAAK;CAChC;CAEA,iBAAyB,OAA6B;EACpD,OAAO;GACL,OAAO,MAAM;GACb,eAAe,MAAM,QAAQ,SAAS,UAAU,MAAM,QAAQ,CAAC;GAC/D,eAAe,MAAM,QAAQ,WAAW,CAAC,CAAC,SAAS,UAAU,MAAM,QAAQ,CAAC;GAC5E,aAAa,MAAM;EACrB;CACF;CAEA,cAAsB,OAAwB;EAC5C,MAAM,WAAW,KAAK,UAAU,GAAG,EAAE;EACrC,IAAI,MAAM,eAAe,UAAU,gBAAgB,MAAM,aACvD,KAAK,UAAU,KAAK,UAAU,SAAS,KAAK;GAC1C,GAAG;GACH,SAAS,SAAS;EACpB;OAEA,KAAK,UAAU,KAAK,KAAK;EAE3B,KAAK,YAAY,CAAC;EAClB,KAAK,cAAc;EACnB,KAAK,WAAW;CAClB;CAEA,gBAA8B;EAC5B,IAAI,CAAC,OAAO,SAAS,KAAK,KAAK,KAAK,KAAK,SAAS,GAAG;EACrD,MAAM,WAAW,KAAK,UAAU,SAAS,KAAK;EAC9C,IAAI,WAAW,GAAG,KAAK,UAAU,OAAO,GAAG,QAAQ;CACrD;AACF"}
|
|
1
|
+
{"version":3,"file":"undo.js","names":[],"sources":["../src/undo.ts"],"sourcesContent":["export interface UndoEntry {\n label: string\n forward: () => void\n inverse: () => void\n coalesceKey?: string\n}\n\n/**\n * Committed history, kept aside while another graph is open so a document opened in the same\n * editor never inherits the last one's steps.\n */\nexport interface UndoHistory {\n readonly undo: readonly UndoEntry[]\n readonly redo: readonly UndoEntry[]\n}\n\nexport interface UndoManagerOptions {\n limit?: number\n /** Called after recording, undoing, redoing, or clearing committed history. */\n onChange?: () => void\n /**\n * The edited-field marks an edit adds. A step takes its marks back when undone and puts them\n * back when redone, so a layer ends a step exactly as it began one, marks included.\n */\n marks?: UndoSourceMarks\n}\n\n/** Marks an edit left on layers, kept by the graph for one undo step. */\nexport interface UndoSourceMarks {\n /** The marks added since the last step, which that step owns. */\n take: () => Array<[nodeId: string, field: string]>\n add: (nodeId: string, fields: readonly string[]) => void\n remove: (nodeId: string, fields: readonly string[]) => void\n /** Runs a replay that writes values only, so it marks no field of its own. */\n preserve: (run: () => void) => void\n}\n\ninterface UndoBatch {\n label: string\n entries: UndoEntry[]\n coalesceKey?: string\n}\n\n/** How many edits undo keeps by default. */\nexport const DEFAULT_HISTORY_LIMIT = 200\n\nexport class UndoManager {\n private undoStack: UndoEntry[] = []\n private redoStack: UndoEntry[] = []\n private batches: UndoBatch[] = []\n private replaying = 0\n private openEdits = 0\n private readonly settlers = new Set<() => void>()\n private readonly limit: number\n private readonly onChange: (() => void) | undefined\n private readonly marks: UndoSourceMarks | undefined\n\n constructor(options: UndoManagerOptions = {}) {\n this.limit = options.limit ?? DEFAULT_HISTORY_LIMIT\n this.onChange = options.onChange\n this.marks = options.marks\n }\n\n apply(entry: UndoEntry): void {\n this.execute(entry)\n }\n\n execute(entry: UndoEntry): void {\n entry.forward()\n this.record(entry)\n }\n\n push(entry: UndoEntry): void {\n this.record(entry)\n }\n\n record(entry: UndoEntry): void {\n const marked = this.withSourceMarks(entry)\n const batch = this.currentBatch\n if (batch) {\n batch.entries.push(marked)\n return\n }\n this.pushUndoEntry(marked)\n }\n\n /**\n * The step's replay writes values without marking them, then the marks the edit added come\n * back on redo and go with it on undo.\n */\n private withSourceMarks(entry: UndoEntry): UndoEntry {\n const marks = this.marks\n if (!marks) return entry\n const taken = marks.take()\n const byNode = new Map<string, string[]>()\n for (const [id, field] of taken) {\n const fields = byNode.get(id)\n if (fields) fields.push(field)\n else byNode.set(id, [field])\n }\n return {\n ...entry,\n forward: () => {\n // Redo repeats the edit, marks its layout adds included, then keeps the marks the step\n // owned even if the replay wrote fewer fields than the edit did.\n entry.forward()\n for (const [id, fields] of byNode) marks.add(id, fields)\n },\n inverse: () => {\n // Undo puts a state back rather than editing, so it marks nothing of its own.\n marks.preserve(() => entry.inverse())\n for (const [id, fields] of byNode) marks.remove(id, fields)\n }\n }\n }\n\n /**\n * Records an entry as a step of its own, outside the batches being built, such as an agent's\n * edit made while a colour picker is open. Batches settle first, so the step follows the\n * changes they hold so far.\n */\n pushStep(entry: UndoEntry): void {\n this.settle()\n this.pushUndoEntry(entry)\n }\n\n /**\n * Registers a hook that commits an edit still being coalesced, such as a run of picker changes.\n * Undo and redo run every hook first, so they act on the newest change.\n */\n onBeforeHistory(settle: () => void): () => void {\n this.settlers.add(settle)\n return () => this.settlers.delete(settle)\n }\n\n private settle() {\n for (const settle of this.settlers) settle()\n }\n\n undo(): string | null {\n this.settle()\n const entry = this.undoStack.pop()\n if (!entry) return null\n this.replay(() => entry.inverse())\n this.redoStack.push(entry)\n this.onChange?.()\n return entry.label\n }\n\n redo(): string | null {\n this.settle()\n const entry = this.redoStack.pop()\n if (!entry) return null\n this.replay(() => entry.forward())\n this.undoStack.push(entry)\n this.onChange?.()\n return entry.label\n }\n\n beginBatch(label: string, coalesceKey?: string): void {\n this.batches.push({ label, entries: [], coalesceKey })\n }\n\n commitBatch(): void {\n const batch = this.batches.pop()\n if (!batch || batch.entries.length === 0) return\n\n const entry = this.createBatchEntry(batch)\n const parentBatch = this.currentBatch\n if (parentBatch) parentBatch.entries.push(entry)\n else this.pushUndoEntry(entry)\n }\n\n runBatch<T>(label: string, fn: () => T, coalesceKey?: string): T {\n this.beginBatch(label, coalesceKey)\n try {\n const result = fn()\n this.commitBatch()\n return result\n } catch (error) {\n this.rollbackBatch()\n throw error\n }\n }\n\n rollbackBatch(): void {\n const batch = this.batches.pop()\n if (!batch) return\n for (const entry of batch.entries.toReversed()) entry.inverse()\n }\n\n /** Abandon provisional history without replaying it or changing committed undo/redo entries. */\n discardBatches(): void {\n this.batches = []\n }\n\n clear(): void {\n this.undoStack = []\n this.redoStack = []\n this.discardBatches()\n this.marks?.take()\n this.onChange?.()\n }\n\n /**\n * Takes the committed history out, for the graph it was recorded on, and leaves this one empty;\n * `adoptHistory` puts it back when that graph opens again.\n */\n takeHistory(): UndoHistory {\n const history = { undo: this.undoStack, redo: this.redoStack }\n this.undoStack = []\n this.redoStack = []\n this.discardBatches()\n return history\n }\n\n /** Makes `history`, recorded on the graph now open, the committed one. */\n adoptHistory(history: UndoHistory | undefined): void {\n this.undoStack = history ? [...history.undo] : []\n this.redoStack = history ? [...history.redo] : []\n this.discardBatches()\n }\n\n /** Whether undo or redo is replaying a step, whose changes are history rather than new edits. */\n get isReplaying(): boolean {\n return this.replaying > 0\n }\n\n /**\n * Adds a change that the newest step caused, as one an editor makes in response to it, so undo\n * and redo apply them together. Inside a batch it joins the batch. False with no step to join,\n * including after an undo, when the newest step is on the redo stack and not applied.\n */\n extendLastStep(entry: UndoEntry): boolean {\n if (this.currentBatch) {\n this.currentBatch.entries.push(entry)\n return true\n }\n const last = this.undoStack.at(-1)\n if (!last || this.redoStack.length > 0) return false\n // The step keeps its identity, so callers that hold it still find it in the history.\n const { forward, inverse } = last\n last.forward = () => {\n forward()\n entry.forward()\n }\n last.inverse = () => {\n entry.inverse()\n inverse()\n }\n return true\n }\n\n private replay(step: () => void) {\n this.replaying++\n try {\n step()\n } finally {\n this.replaying--\n }\n }\n\n get isBatching(): boolean {\n return this.batches.length > 0\n }\n\n /**\n * Marks an edit whose step is recorded when it ends, such as an agent's call that awaits fonts\n * or a layout before it finishes. Returns the function that ends it; ending it twice is a no-op.\n */\n openEdit(): () => void {\n this.openEdits++\n let open = true\n return () => {\n if (!open) return\n open = false\n this.openEdits--\n }\n }\n\n /**\n * Whether a batch or an edit opened with `openEdit` will record a step for the changes made now,\n * so they are not edits outside the history.\n */\n get isRecording(): boolean {\n return this.isBatching || this.openEdits > 0\n }\n\n /** Committed history, or changes in an open batch that a settling hook commits first. */\n get canUndo(): boolean {\n if (this.undoStack.length > 0) return true\n return this.settlers.size > 0 && this.batches.some((batch) => batch.entries.length > 0)\n }\n\n get canRedo(): boolean {\n return this.redoStack.length > 0\n }\n\n /**\n * The entry `depth` steps below the top of the undo stack, so a caller that pushed entries\n * can tell whether they are still the most recent ones.\n */\n peekUndo(depth = 0): UndoEntry | undefined {\n return this.undoStack.at(-1 - depth)\n }\n\n /** The entry `depth` steps below the top of the redo stack, the next one Redo applies at 0. */\n peekRedo(depth = 0): UndoEntry | undefined {\n return this.redoStack.at(-1 - depth)\n }\n\n /**\n * Whether `entry` is applied (on the undo stack) or undone (on the redo stack); null once it\n * left the history, trimmed or dropped when an edit cleared Redo.\n */\n stateOf(entry: UndoEntry): 'applied' | 'undone' | null {\n if (this.undoStack.includes(entry)) return 'applied'\n if (this.redoStack.includes(entry)) return 'undone'\n return null\n }\n\n get undoLabel(): string | null {\n return this.undoStack.at(-1)?.label ?? null\n }\n\n get redoLabel(): string | null {\n return this.redoStack.at(-1)?.label ?? null\n }\n\n private get currentBatch(): UndoBatch | null {\n return this.batches.at(-1) ?? null\n }\n\n private createBatchEntry(batch: UndoBatch): UndoEntry {\n return {\n label: batch.label,\n forward: () => batch.entries.forEach((entry) => entry.forward()),\n inverse: () => batch.entries.toReversed().forEach((entry) => entry.inverse()),\n coalesceKey: batch.coalesceKey\n }\n }\n\n private pushUndoEntry(entry: UndoEntry): void {\n const previous = this.undoStack.at(-1)\n if (entry.coalesceKey && previous?.coalesceKey === entry.coalesceKey) {\n this.undoStack[this.undoStack.length - 1] = {\n ...entry,\n inverse: previous.inverse\n }\n } else {\n this.undoStack.push(entry)\n }\n this.redoStack = []\n this.trimUndoStack()\n this.onChange?.()\n }\n\n private trimUndoStack(): void {\n if (!Number.isFinite(this.limit) || this.limit <= 0) return\n const overflow = this.undoStack.length - this.limit\n if (overflow > 0) this.undoStack.splice(0, overflow)\n }\n}\n"],"mappings":";;AA4CA,MAAa,wBAAwB;AAErC,IAAa,cAAb,MAAyB;CACvB,YAAiC,CAAC;CAClC,YAAiC,CAAC;CAClC,UAA+B,CAAC;CAChC,YAAoB;CACpB,YAAoB;CACpB,2BAA4B,IAAI,IAAgB;CAChD;CACA;CACA;CAEA,YAAY,UAA8B,CAAC,GAAG;E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,IAAI,WAAW,GAAG,KAAK,UAAU,OAAO,GAAG,QAAQ;CACrD;AACF"}
|
|
@@ -33,8 +33,6 @@ declare function resolvedIconBinding(graph: SceneGraph, node: SceneNode, fallbac
|
|
|
33
33
|
* field, as a rescale left it (`runBindingScale`). Bound font styles are left as stored.
|
|
34
34
|
*/
|
|
35
35
|
declare function resolvedRunBindings(graph: SceneGraph, node: SceneNode, fallback?: VariableModeFallback): Pick<Partial<SceneNode>, 'styleRuns'>;
|
|
36
|
-
/** The fills and strokes a node's color bindings resolve to in its mode, when it has any. */
|
|
37
|
-
declare function resolvedPaintBindings(graph: SceneGraph, node: SceneNode, fallback?: VariableModeFallback): Pick<Partial<SceneNode>, 'fills' | 'strokes'>;
|
|
38
36
|
/**
|
|
39
37
|
* The layers a reconcile looks at: those bound to these variables, directly or through a variable
|
|
40
38
|
* aliasing them, or the layers in these subtrees. Without a scope, every layer.
|
|
@@ -57,11 +55,21 @@ declare function collectionsBoundIn(graph: SceneGraph, roots: Iterable<string>):
|
|
|
57
55
|
*/
|
|
58
56
|
declare function layersUsingVariables(graph: SceneGraph, ids: Iterable<string>): SceneNode[];
|
|
59
57
|
/**
|
|
60
|
-
* Resolve live numeric, text, font family, and visibility bindings, numbers in scene units,
|
|
61
|
-
*
|
|
62
|
-
*
|
|
58
|
+
* Resolve live numeric, text, font family, and visibility bindings, numbers in scene units, and
|
|
59
|
+
* refresh bound paints whose variable's color for the layer changed (`refreshBoundPaints`),
|
|
60
|
+
* without authoring instance overrides. A scope limits it to the layers a change can reach, so
|
|
61
|
+
* layers whose saved values differ from their bindings elsewhere in the document are left as
|
|
62
|
+
* saved.
|
|
63
63
|
*/
|
|
64
64
|
declare function reconcileVariableBindings(graph: SceneGraph, scope?: BindingScope): string[];
|
|
65
|
+
/** A layer list whose items carry their own bindings, keyed by position such as `fills/1/color`. */
|
|
66
|
+
type BoundLayerList = 'fills' | 'strokes' | 'effects';
|
|
67
|
+
/**
|
|
68
|
+
* `boundVariables` once the `list` items are rebuilt from `sources`, where `sources[i]` is the
|
|
69
|
+
* position the new item `i` had before, or null for an added item. A binding moves with its item
|
|
70
|
+
* and goes with a removed one, as Figma keeps a binding on its paint or effect.
|
|
71
|
+
*/
|
|
72
|
+
declare function listBindingsAfterEdit(boundVariables: Readonly<Record<string, string>>, list: BoundLayerList, sources: readonly (number | null)[]): Record<string, string>;
|
|
65
73
|
//#endregion
|
|
66
|
-
export { BindingScope, ICON_BINDING_FIELDS, type PaintBindingList, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, assignVariableBindingUnits, boundNumberValue, collectionsBoundIn, isNumericVariableBindingField, layersUsingVariables, paintBindingTarget, reconcileVariableBindings, resolvedIconBinding, resolvedNumericBindings,
|
|
74
|
+
export { BindingScope, BoundLayerList, ICON_BINDING_FIELDS, type PaintBindingList, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, assignVariableBindingUnits, boundNumberValue, collectionsBoundIn, isNumericVariableBindingField, layersUsingVariables, listBindingsAfterEdit, paintBindingTarget, reconcileVariableBindings, resolvedIconBinding, resolvedNumericBindings, resolvedRunBindings, resolvedValueBindings, variableBindingOwner, variablesResolvingThrough };
|
|
67
75
|
//# sourceMappingURL=bindings.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bindings.d.ts","names":[],"sources":["../../src/variables/bindings.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"bindings.d.ts","names":[],"sources":["../../src/variables/bindings.ts"],"mappings":";;;;;;iBA0BgB,qBAAqB,OAAO,YAAY,MAAM,YAAY;iBAW1D,2BACd,OAAO,YACP,MAAM,WACN;;iBAoBc,iBAAiB,eAAe,yBAAyB;;;;;iBAQzD,wBACd,OAAO,YACP,MAAM,WACN,WAAU,uBACT,QAAQ;;;;;;;;iBA2BK,sBACd,OAAO,YACP,MAAM,WACN,WAAU,uBACT,QAAQ;;;;;;iBAsBK,oBACd,OAAO,YACP,MAAM,WACN,WAAU;;;;;;iBAsBI,oBACd,OAAO,YACP,MAAM,WACN,WAAU,uBACT,KAAK,QAAQ;;;;;KAwCJ;EAAiB,WAAW;;EAAuB,UAAU;;;iBAGzD,0BAA0B,OAAO,YAAY,KAAK,mBAAmB;;;;;iBAuBrE,mBAAmB,OAAO,YAAY,OAAO,mBAAmB;;;;;iBAQhE,qBAAqB,OAAO,YAAY,KAAK,mBAAmB;;;;;;;;iBAoBhE,0BAA0B,OAAO,YAAY,QAAQ;;KAkBzD;;;;;;iBAOI,sBACd,gBAAgB,SAAS,yBACzB,MAAM,gBACN,sCACC"}
|
|
@@ -1,12 +1,14 @@
|
|
|
1
|
+
import { hasInstanceOverride } from "../instances/overrides.js";
|
|
1
2
|
import { pixelLength } from "../text/lengths.js";
|
|
2
|
-
import { copyFills, copyStrokes } from "../copy.js";
|
|
3
3
|
import { ICON_BINDING_FIELDS, NUMERIC_FIELDS, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, isNumericVariableBindingField, paintBindingTarget } from "./fields.js";
|
|
4
|
-
import { runBindingScale } from "./units.js";
|
|
5
|
-
import { hasInstanceOverride } from "../instances/index.js";
|
|
6
4
|
import { ICON_NAME } from "../icons/schema.js";
|
|
7
5
|
import { readIcon } from "../icons/model.js";
|
|
8
6
|
import { variableFontFamily, variableText, variableTruthy } from "./text.js";
|
|
9
7
|
import { variableValueReferences } from "./value.js";
|
|
8
|
+
import { collectionsResolving } from "./resolution.js";
|
|
9
|
+
import { subtreeNodes } from "./subtree.js";
|
|
10
|
+
import { refreshBoundPaints } from "./paints.js";
|
|
11
|
+
import { runBindingScale } from "./units.js";
|
|
10
12
|
import { isEqual } from "es-toolkit/predicate";
|
|
11
13
|
//#region src/variables/bindings.ts
|
|
12
14
|
/** New declarations belong to the outermost occurrence, bounded by a component definition. */
|
|
@@ -30,6 +32,11 @@ function assignVariableBindingUnits(graph, node, field) {
|
|
|
30
32
|
}
|
|
31
33
|
/** Fields a bound number sets as a length in pixels, as Figma's do, whatever unit they held. */
|
|
32
34
|
const TEXT_LENGTH_FIELDS = /* @__PURE__ */ new Set(["lineHeight", "letterSpacing"]);
|
|
35
|
+
/** Whether the instance a layer sits in, or the instance itself, overrides one of its fields. */
|
|
36
|
+
function overriddenInInstance(graph, nodeId, field) {
|
|
37
|
+
const instance = graph.closest(nodeId, (node) => node.type === "INSTANCE");
|
|
38
|
+
return !!instance && hasInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field);
|
|
39
|
+
}
|
|
33
40
|
/** A bound number as the field stores it. */
|
|
34
41
|
function boundNumberValue(field, value) {
|
|
35
42
|
return TEXT_LENGTH_FIELDS.has(field) ? pixelLength(value) : value;
|
|
@@ -42,7 +49,7 @@ function resolvedNumericBindings(graph, node, fallback = "active") {
|
|
|
42
49
|
const updates = {};
|
|
43
50
|
for (const [field, variableId] of Object.entries(node.boundVariables)) {
|
|
44
51
|
if (!NUMERIC_FIELDS.has(field)) continue;
|
|
45
|
-
if ((field === "width" || field === "height") &&
|
|
52
|
+
if ((field === "width" || field === "height") && overriddenInInstance(graph, node.id, field)) continue;
|
|
46
53
|
const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback);
|
|
47
54
|
if (value === void 0 || !Number.isFinite(value)) continue;
|
|
48
55
|
const effective = value * (node.variableBindingScales[field] ?? 1);
|
|
@@ -63,7 +70,7 @@ function resolvedValueBindings(graph, node, fallback = "active") {
|
|
|
63
70
|
const updates = {};
|
|
64
71
|
const resolve = (field) => {
|
|
65
72
|
const variableId = node.boundVariables[field];
|
|
66
|
-
if (!variableId ||
|
|
73
|
+
if (!variableId || overriddenInInstance(graph, node.id, field)) return void 0;
|
|
67
74
|
return graph.resolveVariableForNode(node.id, variableId, fallback);
|
|
68
75
|
};
|
|
69
76
|
const text = node.type === "TEXT" ? variableText(resolve("text")) : void 0;
|
|
@@ -84,7 +91,7 @@ function resolvedIconBinding(graph, node, fallback = "active") {
|
|
|
84
91
|
const icon = readIcon(node);
|
|
85
92
|
if (!icon) return void 0;
|
|
86
93
|
const variableId = node.boundVariables["iconName"];
|
|
87
|
-
if (!variableId ||
|
|
94
|
+
if (!variableId || overriddenInInstance(graph, node.id, "iconName")) return void 0;
|
|
88
95
|
const resolved = graph.resolveVariableForNode(node.id, variableId, fallback);
|
|
89
96
|
if (typeof resolved !== "string") return void 0;
|
|
90
97
|
const name = resolved.trim();
|
|
@@ -139,39 +146,6 @@ function resolvedRunBindings(graph, node, fallback = "active") {
|
|
|
139
146
|
function boundVariableIds(node) {
|
|
140
147
|
return [...Object.values(node.boundVariables), ...node.styleRuns.flatMap((run) => Object.values(run.style.boundVariables ?? {}))].filter((id) => typeof id === "string");
|
|
141
148
|
}
|
|
142
|
-
/**
|
|
143
|
-
* A bound paint takes its whole color from the variable, alpha included, the way Figma stores
|
|
144
|
-
* it: the variable's RGB at full alpha, and its alpha as the paint's opacity.
|
|
145
|
-
*/
|
|
146
|
-
function applyBoundColor(paint, color) {
|
|
147
|
-
paint.color = {
|
|
148
|
-
...color,
|
|
149
|
-
a: 1
|
|
150
|
-
};
|
|
151
|
-
paint.opacity = color.a;
|
|
152
|
-
}
|
|
153
|
-
/** The fills and strokes a node's color bindings resolve to in its mode, when it has any. */
|
|
154
|
-
function resolvedPaintBindings(graph, node, fallback = "active") {
|
|
155
|
-
const changes = {};
|
|
156
|
-
for (const field in node.boundVariables) {
|
|
157
|
-
if (!field.endsWith("/color")) continue;
|
|
158
|
-
const paint = paintBindingTarget(field);
|
|
159
|
-
if (!paint) continue;
|
|
160
|
-
const color = graph.resolveColorVariableForNode(node.id, node.boundVariables[field], fallback);
|
|
161
|
-
const { index } = paint;
|
|
162
|
-
if (!color) continue;
|
|
163
|
-
if (paint.list === "fills") {
|
|
164
|
-
if (!node.fills[index]) continue;
|
|
165
|
-
changes.fills ??= copyFills(node.fills);
|
|
166
|
-
applyBoundColor(changes.fills[index], color);
|
|
167
|
-
} else {
|
|
168
|
-
if (!node.strokes[index]) continue;
|
|
169
|
-
changes.strokes ??= copyStrokes(node.strokes);
|
|
170
|
-
applyBoundColor(changes.strokes[index], color);
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
return changes;
|
|
174
|
-
}
|
|
175
149
|
/** These variables and every variable that aliases one of them, at any depth and in any mode. */
|
|
176
150
|
function variablesResolvingThrough(graph, ids) {
|
|
177
151
|
const found = new Set(ids);
|
|
@@ -188,34 +162,12 @@ function variablesResolvingThrough(graph, ids) {
|
|
|
188
162
|
}
|
|
189
163
|
return found;
|
|
190
164
|
}
|
|
191
|
-
function subtreeNodes(graph, roots) {
|
|
192
|
-
const nodes = [];
|
|
193
|
-
const pending = [...roots];
|
|
194
|
-
for (let id = pending.pop(); id !== void 0; id = pending.pop()) {
|
|
195
|
-
const node = graph.getNode(id);
|
|
196
|
-
if (!node) continue;
|
|
197
|
-
nodes.push(node);
|
|
198
|
-
pending.push(...node.childIds);
|
|
199
|
-
}
|
|
200
|
-
return nodes;
|
|
201
|
-
}
|
|
202
165
|
/**
|
|
203
166
|
* The collections whose variables the layers in these subtrees resolve: those they bind, and
|
|
204
167
|
* those the bound variables alias, so a mode set on the subtrees can change what they show.
|
|
205
168
|
*/
|
|
206
169
|
function collectionsBoundIn(graph, roots) {
|
|
207
|
-
|
|
208
|
-
const seen = /* @__PURE__ */ new Set();
|
|
209
|
-
const collections = /* @__PURE__ */ new Set();
|
|
210
|
-
for (let id = pending.pop(); id !== void 0; id = pending.pop()) {
|
|
211
|
-
if (seen.has(id)) continue;
|
|
212
|
-
seen.add(id);
|
|
213
|
-
const variable = graph.variables.get(id);
|
|
214
|
-
if (!variable) continue;
|
|
215
|
-
collections.add(variable.collectionId);
|
|
216
|
-
for (const value of Object.values(variable.valuesByMode)) pending.push(...variableValueReferences(value));
|
|
217
|
-
}
|
|
218
|
-
return collections;
|
|
170
|
+
return collectionsResolving(graph, subtreeNodes(graph, roots).flatMap(boundVariableIds));
|
|
219
171
|
}
|
|
220
172
|
/**
|
|
221
173
|
* The layers a change to these variables reaches: those binding one of them, or a variable that
|
|
@@ -231,13 +183,17 @@ function scopedNodes(graph, scope) {
|
|
|
231
183
|
return layersUsingVariables(graph, scope.variables);
|
|
232
184
|
}
|
|
233
185
|
/**
|
|
234
|
-
* Resolve live numeric, text, font family, and visibility bindings, numbers in scene units,
|
|
235
|
-
*
|
|
236
|
-
*
|
|
186
|
+
* Resolve live numeric, text, font family, and visibility bindings, numbers in scene units, and
|
|
187
|
+
* refresh bound paints whose variable's color for the layer changed (`refreshBoundPaints`),
|
|
188
|
+
* without authoring instance overrides. A scope limits it to the layers a change can reach, so
|
|
189
|
+
* layers whose saved values differ from their bindings elsewhere in the document are left as
|
|
190
|
+
* saved.
|
|
237
191
|
*/
|
|
238
192
|
function reconcileVariableBindings(graph, scope) {
|
|
239
193
|
const changed = [];
|
|
240
|
-
|
|
194
|
+
const nodes = [...scopedNodes(graph, scope)];
|
|
195
|
+
for (const node of nodes) refreshBoundPaints(graph, node);
|
|
196
|
+
for (const node of nodes) {
|
|
241
197
|
const updates = {
|
|
242
198
|
...resolvedNumericBindings(graph, node),
|
|
243
199
|
...resolvedValueBindings(graph, node),
|
|
@@ -249,7 +205,26 @@ function reconcileVariableBindings(graph, scope) {
|
|
|
249
205
|
}
|
|
250
206
|
return changed;
|
|
251
207
|
}
|
|
208
|
+
/**
|
|
209
|
+
* `boundVariables` once the `list` items are rebuilt from `sources`, where `sources[i]` is the
|
|
210
|
+
* position the new item `i` had before, or null for an added item. A binding moves with its item
|
|
211
|
+
* and goes with a removed one, as Figma keeps a binding on its paint or effect.
|
|
212
|
+
*/
|
|
213
|
+
function listBindingsAfterEdit(boundVariables, list, sources) {
|
|
214
|
+
const prefix = `${list}/`;
|
|
215
|
+
const moved = {};
|
|
216
|
+
for (const [field, variableId] of Object.entries(boundVariables)) {
|
|
217
|
+
if (!field.startsWith(prefix)) {
|
|
218
|
+
moved[field] = variableId;
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
const [index, ...property] = field.slice(prefix.length).split("/");
|
|
222
|
+
const next = sources.indexOf(Number(index));
|
|
223
|
+
if (next !== -1 && property.length > 0) moved[`${prefix}${next}/${property.join("/")}`] = variableId;
|
|
224
|
+
}
|
|
225
|
+
return moved;
|
|
226
|
+
}
|
|
252
227
|
//#endregion
|
|
253
|
-
export { ICON_BINDING_FIELDS, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, assignVariableBindingUnits, boundNumberValue, collectionsBoundIn, isNumericVariableBindingField, layersUsingVariables, paintBindingTarget, reconcileVariableBindings, resolvedIconBinding, resolvedNumericBindings,
|
|
228
|
+
export { ICON_BINDING_FIELDS, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, assignVariableBindingUnits, boundNumberValue, collectionsBoundIn, isNumericVariableBindingField, layersUsingVariables, listBindingsAfterEdit, paintBindingTarget, reconcileVariableBindings, resolvedIconBinding, resolvedNumericBindings, resolvedRunBindings, resolvedValueBindings, variableBindingOwner, variablesResolvingThrough };
|
|
254
229
|
|
|
255
230
|
//# sourceMappingURL=bindings.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bindings.js","names":[],"sources":["../../src/variables/bindings.ts"],"sourcesContent":["import { isEqual } from 'es-toolkit/predicate'\n\nimport type { VariableModeFallback } from '.'\nimport { copyFills, copyStrokes } from '../copy'\nimport type { SceneGraph } from '../graph'\nimport { readIcon } from '../icons/model'\nimport { ICON_NAME } from '../icons/schema'\nimport { hasInstanceOverride } from '../instances'\nimport type { Color } from '../primitives'\nimport { pixelLength } from '../text/lengths'\nimport type { Fill, SceneNode, Stroke, StyleRun, TextLength } from '../types'\nimport { NUMERIC_FIELDS, isNumericVariableBindingField, paintBindingTarget } from './fields'\nimport { variableFontFamily, variableText, variableTruthy } from './text'\nimport { runBindingScale } from './units'\nimport { variableValueReferences } from './value'\nexport {\n ICON_BINDING_FIELDS,\n isNumericVariableBindingField,\n paintBindingTarget,\n TEXT_CONTENT_VARIABLE_TYPES,\n VISIBILITY_VARIABLE_TYPES,\n type PaintBindingList\n} from './fields'\n\n/** New declarations belong to the outermost occurrence, bounded by a component definition. */\nexport function variableBindingOwner(graph: SceneGraph, node: SceneNode): SceneNode {\n let owner = node\n let current: SceneNode | undefined = node\n while (current) {\n if (current.type === 'COMPONENT' || current.type === 'COMPONENT_SET') break\n if (current.type === 'INSTANCE') owner = current\n current = current.parentId ? graph.getNode(current.parentId) : undefined\n }\n return owner\n}\n\nexport function assignVariableBindingUnits(\n graph: SceneGraph,\n node: SceneNode,\n field: string\n): void {\n if (!isNumericVariableBindingField(field)) return\n const owner = variableBindingOwner(graph, node)\n node.variableBindingScales = {\n ...node.variableBindingScales,\n [field]: owner.variableAssignmentScales[field] ?? 1\n }\n}\n\n/** Fields a bound number sets as a length in pixels, as Figma's do, whatever unit they held. */\nconst TEXT_LENGTH_FIELDS: ReadonlySet<string> = new Set(['lineHeight', 'letterSpacing'])\n\n/** A bound number as the field stores it. */\nexport function boundNumberValue(field: string, value: number): number | TextLength {\n return TEXT_LENGTH_FIELDS.has(field) ? pixelLength(value) : value\n}\n\n/**\n * The values a node's numeric bindings resolve to in its mode, in scene units, for the fields\n * whose stored value differs. A width or height an instance overrides keeps its own value.\n */\nexport function resolvedNumericBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): Partial<SceneNode> {\n const updates: Partial<SceneNode> = {}\n for (const [field, variableId] of Object.entries(node.boundVariables)) {\n if (!NUMERIC_FIELDS.has(field)) continue\n if ((field === 'width' || field === 'height') && hasInstanceOverride(graph, node.id, field))\n continue\n const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback)\n if (value === undefined || !Number.isFinite(value)) continue\n const scale = node.variableBindingScales[field] ?? 1\n const effective = value * scale\n if (!Number.isFinite(effective)) continue\n const next = boundNumberValue(\n field,\n field === 'opacity' ? Math.max(0, Math.min(1, effective)) : effective\n )\n if (!isEqual(node[field as keyof SceneNode], next)) Object.assign(updates, { [field]: next })\n }\n return updates\n}\n\n/**\n * The text, font family, and visibility a node's string and boolean bindings resolve to in its\n * mode, for the fields whose stored value differs. Text, a font family, or visibility an instance\n * overrides, which typing in a layer or toggling its eye records, keeps its own value, as an\n * overridden width or height does. A font family is only named here; the editor loads its faces\n * after the reconcile (`loadBoundFonts` in Core), and the text draws in a fallback until they do.\n */\nexport function resolvedValueBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): Partial<SceneNode> {\n const updates: Partial<SceneNode> = {}\n const resolve = (field: 'text' | 'fontFamily' | 'visible') => {\n const variableId = node.boundVariables[field]\n if (!variableId || hasInstanceOverride(graph, node.id, field)) return undefined\n return graph.resolveVariableForNode(node.id, variableId, fallback)\n }\n const text = node.type === 'TEXT' ? variableText(resolve('text')) : undefined\n if (text !== undefined && text !== node.text) updates.text = text\n const fontFamily = node.type === 'TEXT' ? variableFontFamily(resolve('fontFamily')) : undefined\n if (fontFamily !== undefined && fontFamily !== node.fontFamily) updates.fontFamily = fontFamily\n // Figma binds visibility to text too, and shows the layer when the text reads as true.\n const visible = variableTruthy(resolve('visible'))\n if (visible !== undefined && visible !== node.visible) updates.visible = visible\n return updates\n}\n\n/**\n * The icon an icon frame's `iconName` binding names in its mode, when it differs from the icon\n * it draws. Only frames that are icons resolve it; other layers keep the binding inert. The\n * caller redraws the frame, as resolving only names the icon.\n */\nexport function resolvedIconBinding(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): string | undefined {\n if (node.type !== 'FRAME') return undefined\n const icon = readIcon(node)\n if (!icon) return undefined\n const variableId = node.boundVariables['iconName']\n if (!variableId || hasInstanceOverride(graph, node.id, 'iconName')) return undefined\n const resolved = graph.resolveVariableForNode(node.id, variableId, fallback)\n if (typeof resolved !== 'string') return undefined\n const name = resolved.trim()\n if (name === '' || name === icon.name || !ICON_NAME.test(name)) return undefined\n return name\n}\n\n/** Fields of a range of characters a bound number gives its value. */\nconst NUMERIC_RUN_FIELDS = ['fontSize', 'fontWeight', 'letterSpacing', 'lineHeight'] as const\n\n/**\n * The runs a text's character bindings resolve to in its mode, when a bound number or font family\n * differs from what its characters hold, a size or spacing in the run's binding scale for the\n * field, as a rescale left it (`runBindingScale`). Bound font styles are left as stored.\n */\nexport function resolvedRunBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): Pick<Partial<SceneNode>, 'styleRuns'> {\n const styleRuns = node.styleRuns.map((run): StyleRun => {\n const bound = run.style.boundVariables\n if (!bound) return run\n let style = run.style\n for (const field of NUMERIC_RUN_FIELDS) {\n const variableId = bound[field]\n if (!variableId) continue\n const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback)\n if (value === undefined || !Number.isFinite(value)) continue\n const effective = value * runBindingScale(node, style, field)\n if (!Number.isFinite(effective)) continue\n const next = boundNumberValue(field, effective)\n if (isEqual(style[field], next)) continue\n style = { ...style, [field]: next }\n }\n const familyId = bound.fontFamily\n const family = familyId\n ? variableFontFamily(graph.resolveVariableForNode(node.id, familyId, fallback))\n : undefined\n if (family !== undefined && family !== style.fontFamily)\n style = { ...style, fontFamily: family }\n return style === run.style ? run : { ...run, style }\n })\n const changed = styleRuns.some((run, index) => run !== node.styleRuns[index])\n return changed ? { styleRuns } : {}\n}\n\n/** The variables a node binds, its own and its characters'. */\nfunction boundVariableIds(node: SceneNode): string[] {\n return [\n ...Object.values(node.boundVariables),\n ...node.styleRuns.flatMap((run) => Object.values(run.style.boundVariables ?? {}))\n ].filter((id): id is string => typeof id === 'string')\n}\n\n/**\n * A bound paint takes its whole color from the variable, alpha included, the way Figma stores\n * it: the variable's RGB at full alpha, and its alpha as the paint's opacity.\n */\nfunction applyBoundColor(paint: Fill | Stroke, color: Color): void {\n paint.color = { ...color, a: 1 }\n paint.opacity = color.a\n}\n\n/** The fills and strokes a node's color bindings resolve to in its mode, when it has any. */\nexport function resolvedPaintBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): Pick<Partial<SceneNode>, 'fills' | 'strokes'> {\n // Most nodes bind nothing, so no copy is made until a paint binding is actually found.\n const changes: Pick<Partial<SceneNode>, 'fills' | 'strokes'> = {}\n for (const field in node.boundVariables) {\n if (!field.endsWith('/color')) continue\n const paint = paintBindingTarget(field)\n if (!paint) continue\n const color = graph.resolveColorVariableForNode(node.id, node.boundVariables[field], fallback)\n const { index } = paint\n if (!color) continue\n if (paint.list === 'fills') {\n if (!node.fills[index]) continue\n changes.fills ??= copyFills(node.fills)\n applyBoundColor(changes.fills[index], color)\n } else {\n if (!node.strokes[index]) continue\n changes.strokes ??= copyStrokes(node.strokes)\n applyBoundColor(changes.strokes[index], color)\n }\n }\n return changes\n}\n\n/**\n * The layers a reconcile looks at: those bound to these variables, directly or through a variable\n * aliasing them, or the layers in these subtrees. Without a scope, every layer.\n */\nexport type BindingScope = { variables: Iterable<string> } | { subtrees: Iterable<string> }\n\n/** These variables and every variable that aliases one of them, at any depth and in any mode. */\nexport function variablesResolvingThrough(graph: SceneGraph, ids: Iterable<string>): Set<string> {\n const found = new Set(ids)\n let grew = true\n while (grew) {\n grew = false\n for (const variable of graph.variables.values()) {\n if (found.has(variable.id)) continue\n const aliases = Object.values(variable.valuesByMode).some((value) =>\n variableValueReferences(value).some((id) => found.has(id))\n )\n if (aliases) {\n found.add(variable.id)\n grew = true\n }\n }\n }\n return found\n}\n\nfunction subtreeNodes(graph: SceneGraph, roots: Iterable<string>): SceneNode[] {\n const nodes: SceneNode[] = []\n const pending = [...roots]\n for (let id = pending.pop(); id !== undefined; id = pending.pop()) {\n const node = graph.getNode(id)\n if (!node) continue\n nodes.push(node)\n pending.push(...node.childIds)\n }\n return nodes\n}\n\n/**\n * The collections whose variables the layers in these subtrees resolve: those they bind, and\n * those the bound variables alias, so a mode set on the subtrees can change what they show.\n */\nexport function collectionsBoundIn(graph: SceneGraph, roots: Iterable<string>): Set<string> {\n const pending = subtreeNodes(graph, roots).flatMap(boundVariableIds)\n const seen = new Set<string>()\n const collections = new Set<string>()\n for (let id = pending.pop(); id !== undefined; id = pending.pop()) {\n if (seen.has(id)) continue\n seen.add(id)\n const variable = graph.variables.get(id)\n if (!variable) continue\n collections.add(variable.collectionId)\n for (const value of Object.values(variable.valuesByMode))\n pending.push(...variableValueReferences(value))\n }\n return collections\n}\n\n/**\n * The layers a change to these variables reaches: those binding one of them, or a variable that\n * aliases one, on the layer itself or on its characters.\n */\nexport function layersUsingVariables(graph: SceneGraph, ids: Iterable<string>): SceneNode[] {\n const variables = variablesResolvingThrough(graph, ids)\n return [...graph.getAllNodes()].filter((node) =>\n boundVariableIds(node).some((id) => variables.has(id))\n )\n}\n\nfunction scopedNodes(graph: SceneGraph, scope: BindingScope | undefined): Iterable<SceneNode> {\n if (!scope) return graph.getAllNodes()\n if ('subtrees' in scope) return subtreeNodes(graph, scope.subtrees)\n return layersUsingVariables(graph, scope.variables)\n}\n\n/**\n * Resolve live numeric, text, font family, and visibility bindings, numbers in scene units, without authoring\n * instance overrides. A scope limits it to the layers a change can reach, so layers whose saved\n * values differ from their bindings elsewhere in the document are left as saved.\n */\nexport function reconcileVariableBindings(graph: SceneGraph, scope?: BindingScope): string[] {\n const changed: string[] = []\n for (const node of scopedNodes(graph, scope)) {\n const updates = {\n ...resolvedNumericBindings(graph, node),\n ...resolvedValueBindings(graph, node),\n ...resolvedRunBindings(graph, node)\n }\n if (Object.keys(updates).length === 0) continue\n graph.updateNode(node.id, updates)\n changed.push(node.id)\n }\n return changed\n}\n"],"mappings":";;;;;;;;;;;;AAyBA,SAAgB,qBAAqB,OAAmB,MAA4B;CAClF,IAAI,QAAQ;CACZ,IAAI,UAAiC;CACrC,OAAO,SAAS;EACd,IAAI,QAAQ,SAAS,eAAe,QAAQ,SAAS,iBAAiB;EACtE,IAAI,QAAQ,SAAS,YAAY,QAAQ;EACzC,UAAU,QAAQ,WAAW,MAAM,QAAQ,QAAQ,QAAQ,IAAI,KAAA;CACjE;CACA,OA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,WAAW,GAAG;EACvC,MAAM,WAAW,KAAK,IAAI,OAAO;EACjC,QAAQ,KAAK,KAAK,EAAE;CACtB;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"bindings.js","names":[],"sources":["../../src/variables/bindings.ts"],"sourcesContent":["import { isEqual } from 'es-toolkit/predicate'\n\nimport type { VariableModeFallback } from '.'\nimport type { SceneGraph } from '../graph'\nimport { readIcon } from '../icons/model'\nimport { ICON_NAME } from '../icons/schema'\nimport { hasInstanceOverride } from '../instances/overrides'\nimport { pixelLength } from '../text/lengths'\nimport type { SceneNode, StyleRun, TextLength } from '../types'\nimport { NUMERIC_FIELDS, isNumericVariableBindingField } from './fields'\nimport { refreshBoundPaints } from './paints'\nimport { collectionsResolving } from './resolution'\nimport { subtreeNodes } from './subtree'\nimport { variableFontFamily, variableText, variableTruthy } from './text'\nimport { runBindingScale } from './units'\nimport { variableValueReferences } from './value'\nexport {\n ICON_BINDING_FIELDS,\n isNumericVariableBindingField,\n paintBindingTarget,\n TEXT_CONTENT_VARIABLE_TYPES,\n VISIBILITY_VARIABLE_TYPES,\n type PaintBindingList\n} from './fields'\n\n/** New declarations belong to the outermost occurrence, bounded by a component definition. */\nexport function variableBindingOwner(graph: SceneGraph, node: SceneNode): SceneNode {\n let owner = node\n let current: SceneNode | undefined = node\n while (current) {\n if (current.type === 'COMPONENT' || current.type === 'COMPONENT_SET') break\n if (current.type === 'INSTANCE') owner = current\n current = current.parentId ? graph.getNode(current.parentId) : undefined\n }\n return owner\n}\n\nexport function assignVariableBindingUnits(\n graph: SceneGraph,\n node: SceneNode,\n field: string\n): void {\n if (!isNumericVariableBindingField(field)) return\n const owner = variableBindingOwner(graph, node)\n node.variableBindingScales = {\n ...node.variableBindingScales,\n [field]: owner.variableAssignmentScales[field] ?? 1\n }\n}\n\n/** Fields a bound number sets as a length in pixels, as Figma's do, whatever unit they held. */\nconst TEXT_LENGTH_FIELDS: ReadonlySet<string> = new Set(['lineHeight', 'letterSpacing'])\n\n/** Whether the instance a layer sits in, or the instance itself, overrides one of its fields. */\nfunction overriddenInInstance(graph: SceneGraph, nodeId: string, field: string): boolean {\n const instance = graph.closest(nodeId, (node) => node.type === 'INSTANCE')\n return !!instance && hasInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)\n}\n\n/** A bound number as the field stores it. */\nexport function boundNumberValue(field: string, value: number): number | TextLength {\n return TEXT_LENGTH_FIELDS.has(field) ? pixelLength(value) : value\n}\n\n/**\n * The values a node's numeric bindings resolve to in its mode, in scene units, for the fields\n * whose stored value differs. A width or height an instance overrides keeps its own value.\n */\nexport function resolvedNumericBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): Partial<SceneNode> {\n const updates: Partial<SceneNode> = {}\n for (const [field, variableId] of Object.entries(node.boundVariables)) {\n if (!NUMERIC_FIELDS.has(field)) continue\n if ((field === 'width' || field === 'height') && overriddenInInstance(graph, node.id, field))\n continue\n const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback)\n if (value === undefined || !Number.isFinite(value)) continue\n const scale = node.variableBindingScales[field] ?? 1\n const effective = value * scale\n if (!Number.isFinite(effective)) continue\n const next = boundNumberValue(\n field,\n field === 'opacity' ? Math.max(0, Math.min(1, effective)) : effective\n )\n if (!isEqual(node[field as keyof SceneNode], next)) Object.assign(updates, { [field]: next })\n }\n return updates\n}\n\n/**\n * The text, font family, and visibility a node's string and boolean bindings resolve to in its\n * mode, for the fields whose stored value differs. Text, a font family, or visibility an instance\n * overrides, which typing in a layer or toggling its eye records, keeps its own value, as an\n * overridden width or height does. A font family is only named here; the editor loads its faces\n * after the reconcile (`loadBoundFonts` in Core), and the text draws in a fallback until they do.\n */\nexport function resolvedValueBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): Partial<SceneNode> {\n const updates: Partial<SceneNode> = {}\n const resolve = (field: 'text' | 'fontFamily' | 'visible') => {\n const variableId = node.boundVariables[field]\n if (!variableId || overriddenInInstance(graph, node.id, field)) return undefined\n return graph.resolveVariableForNode(node.id, variableId, fallback)\n }\n const text = node.type === 'TEXT' ? variableText(resolve('text')) : undefined\n if (text !== undefined && text !== node.text) updates.text = text\n const fontFamily = node.type === 'TEXT' ? variableFontFamily(resolve('fontFamily')) : undefined\n if (fontFamily !== undefined && fontFamily !== node.fontFamily) updates.fontFamily = fontFamily\n // Figma binds visibility to text too, and shows the layer when the text reads as true.\n const visible = variableTruthy(resolve('visible'))\n if (visible !== undefined && visible !== node.visible) updates.visible = visible\n return updates\n}\n\n/**\n * The icon an icon frame's `iconName` binding names in its mode, when it differs from the icon\n * it draws. Only frames that are icons resolve it; other layers keep the binding inert. The\n * caller redraws the frame, as resolving only names the icon.\n */\nexport function resolvedIconBinding(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): string | undefined {\n if (node.type !== 'FRAME') return undefined\n const icon = readIcon(node)\n if (!icon) return undefined\n const variableId = node.boundVariables['iconName']\n if (!variableId || overriddenInInstance(graph, node.id, 'iconName')) return undefined\n const resolved = graph.resolveVariableForNode(node.id, variableId, fallback)\n if (typeof resolved !== 'string') return undefined\n const name = resolved.trim()\n if (name === '' || name === icon.name || !ICON_NAME.test(name)) return undefined\n return name\n}\n\n/** Fields of a range of characters a bound number gives its value. */\nconst NUMERIC_RUN_FIELDS = ['fontSize', 'fontWeight', 'letterSpacing', 'lineHeight'] as const\n\n/**\n * The runs a text's character bindings resolve to in its mode, when a bound number or font family\n * differs from what its characters hold, a size or spacing in the run's binding scale for the\n * field, as a rescale left it (`runBindingScale`). Bound font styles are left as stored.\n */\nexport function resolvedRunBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): Pick<Partial<SceneNode>, 'styleRuns'> {\n const styleRuns = node.styleRuns.map((run): StyleRun => {\n const bound = run.style.boundVariables\n if (!bound) return run\n let style = run.style\n for (const field of NUMERIC_RUN_FIELDS) {\n const variableId = bound[field]\n if (!variableId) continue\n const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback)\n if (value === undefined || !Number.isFinite(value)) continue\n const effective = value * runBindingScale(node, style, field)\n if (!Number.isFinite(effective)) continue\n const next = boundNumberValue(field, effective)\n if (isEqual(style[field], next)) continue\n style = { ...style, [field]: next }\n }\n const familyId = bound.fontFamily\n const family = familyId\n ? variableFontFamily(graph.resolveVariableForNode(node.id, familyId, fallback))\n : undefined\n if (family !== undefined && family !== style.fontFamily)\n style = { ...style, fontFamily: family }\n return style === run.style ? run : { ...run, style }\n })\n const changed = styleRuns.some((run, index) => run !== node.styleRuns[index])\n return changed ? { styleRuns } : {}\n}\n\n/** The variables a node binds, its own and its characters'. */\nfunction boundVariableIds(node: SceneNode): string[] {\n return [\n ...Object.values(node.boundVariables),\n ...node.styleRuns.flatMap((run) => Object.values(run.style.boundVariables ?? {}))\n ].filter((id): id is string => typeof id === 'string')\n}\n\n/**\n * The layers a reconcile looks at: those bound to these variables, directly or through a variable\n * aliasing them, or the layers in these subtrees. Without a scope, every layer.\n */\nexport type BindingScope = { variables: Iterable<string> } | { subtrees: Iterable<string> }\n\n/** These variables and every variable that aliases one of them, at any depth and in any mode. */\nexport function variablesResolvingThrough(graph: SceneGraph, ids: Iterable<string>): Set<string> {\n const found = new Set(ids)\n let grew = true\n while (grew) {\n grew = false\n for (const variable of graph.variables.values()) {\n if (found.has(variable.id)) continue\n const aliases = Object.values(variable.valuesByMode).some((value) =>\n variableValueReferences(value).some((id) => found.has(id))\n )\n if (aliases) {\n found.add(variable.id)\n grew = true\n }\n }\n }\n return found\n}\n\n/**\n * The collections whose variables the layers in these subtrees resolve: those they bind, and\n * those the bound variables alias, so a mode set on the subtrees can change what they show.\n */\nexport function collectionsBoundIn(graph: SceneGraph, roots: Iterable<string>): Set<string> {\n return collectionsResolving(graph, subtreeNodes(graph, roots).flatMap(boundVariableIds))\n}\n\n/**\n * The layers a change to these variables reaches: those binding one of them, or a variable that\n * aliases one, on the layer itself or on its characters.\n */\nexport function layersUsingVariables(graph: SceneGraph, ids: Iterable<string>): SceneNode[] {\n const variables = variablesResolvingThrough(graph, ids)\n return [...graph.getAllNodes()].filter((node) =>\n boundVariableIds(node).some((id) => variables.has(id))\n )\n}\n\nfunction scopedNodes(graph: SceneGraph, scope: BindingScope | undefined): Iterable<SceneNode> {\n if (!scope) return graph.getAllNodes()\n if ('subtrees' in scope) return subtreeNodes(graph, scope.subtrees)\n return layersUsingVariables(graph, scope.variables)\n}\n\n/**\n * Resolve live numeric, text, font family, and visibility bindings, numbers in scene units, and\n * refresh bound paints whose variable's color for the layer changed (`refreshBoundPaints`),\n * without authoring instance overrides. A scope limits it to the layers a change can reach, so\n * layers whose saved values differ from their bindings elsewhere in the document are left as\n * saved.\n */\nexport function reconcileVariableBindings(graph: SceneGraph, scope?: BindingScope): string[] {\n const changed: string[] = []\n const nodes = [...scopedNodes(graph, scope)]\n for (const node of nodes) refreshBoundPaints(graph, node)\n for (const node of nodes) {\n const updates = {\n ...resolvedNumericBindings(graph, node),\n ...resolvedValueBindings(graph, node),\n ...resolvedRunBindings(graph, node)\n }\n if (Object.keys(updates).length === 0) continue\n graph.updateNode(node.id, updates)\n changed.push(node.id)\n }\n return changed\n}\n\n/** A layer list whose items carry their own bindings, keyed by position such as `fills/1/color`. */\nexport type BoundLayerList = 'fills' | 'strokes' | 'effects'\n\n/**\n * `boundVariables` once the `list` items are rebuilt from `sources`, where `sources[i]` is the\n * position the new item `i` had before, or null for an added item. A binding moves with its item\n * and goes with a removed one, as Figma keeps a binding on its paint or effect.\n */\nexport function listBindingsAfterEdit(\n boundVariables: Readonly<Record<string, string>>,\n list: BoundLayerList,\n sources: readonly (number | null)[]\n): Record<string, string> {\n const prefix = `${list}/`\n const moved: Record<string, string> = {}\n for (const [field, variableId] of Object.entries(boundVariables)) {\n if (!field.startsWith(prefix)) {\n moved[field] = variableId\n continue\n }\n const [index, ...property] = field.slice(prefix.length).split('/')\n const next = sources.indexOf(Number(index))\n if (next !== -1 && property.length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;;;;;AASA,SAAgB,0BAA0B,OAAmB,OAAgC;CAC3F,MAAM,UAAoB,CAAC;CAC3B,MAAM,QAAQ,CAAC,GAAG,YAAY,OAAO,KAAK,CAAC;CAC3C,KAAK,MAAM,QAAQ,OAAO,mBAAmB,OAAO,IAAI;CACxD,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,UAAU;GACd,GAAG,wBAAwB,OAAO,IAAI;GACtC,GAAG,sBAAsB,OAAO,IAAI;GACpC,GAAG,oBAAoB,OAAO,IAAI;EACpC;EACA,IAAI,OAAO,KAAK,OAAO,CAAC,CAAC,WAAW,GAAG;EACvC,MAAM,WAAW,KAAK,IAAI,OAAO;EACjC,QAAQ,KAAK,KAAK,EAAE;CACtB;CACA,OAAO;AACT;;;;;;AAUA,SAAgB,sBACd,gBACA,MACA,SACwB;CACxB,MAAM,SAAS,GAAG,KAAK;CACvB,MAAM,QAAgC,CAAC;CACvC,KAAK,MAAM,CAAC,OAAO,eAAe,OAAO,QAAQ,cAAc,GAAG;EAChE,IAAI,CAAC,MAAM,WAAW,MAAM,GAAG;GAC7B,MAAM,SAAS;GACf;EACF;EACA,MAAM,CAAC,OAAO,GAAG,YAAY,MAAM,MAAM,OAAO,MAAM,CAAC,CAAC,MAAM,GAAG;EACjE,MAAM,OAAO,QAAQ,QAAQ,OAAO,KAAK,CAAC;EAC1C,IAAI,SAAS,MAAM,SAAS,SAAS,GACnC,MAAM,GAAG,SAAS,KAAK,GAAG,SAAS,KAAK,GAAG,OAAO;CACtD;CACA,OAAO;AACT"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { FormulaFold, MAX_FORMULA_DEPTH, VariableFormulaError, foldFormula, isFormulaOperation, isFormulaReference } from "./formula/tree.js";
|
|
2
|
-
import { NodeVariableResolver, VariableModeFallback, VariableResolutionError, createBatchVariableResolver, getActiveModeId, getNodeVariableModeId, resolveColorVariable, resolveColorVariableForNode, resolveNumberVariable, resolveNumberVariableForNode, resolveStringVariableForNode, resolveVariable, resolveVariableForNode, resolveVariableInModes, variableValueInMode } from "./resolution.js";
|
|
2
|
+
import { NodeVariableResolver, VariableModeFallback, VariableResolutionError, collectionsResolving, createBatchVariableResolver, getActiveModeId, getNodeExplicitVariableModeId, getNodeVariableModeId, resolveColorVariable, resolveColorVariableForNode, resolveNumberVariable, resolveNumberVariableForNode, resolveStringVariableForNode, resolveVariable, resolveVariableForNode, resolveVariableInModes, resolvedVariableModes, variableValueInMode } from "./resolution.js";
|
|
3
3
|
import { ICON_BINDING_FIELDS, PaintBindingList, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, isNumericVariableBindingField, paintBindingTarget } from "./fields.js";
|
|
4
|
-
import { BindingScope, assignVariableBindingUnits, boundNumberValue, collectionsBoundIn, layersUsingVariables, reconcileVariableBindings, resolvedIconBinding, resolvedNumericBindings,
|
|
4
|
+
import { BindingScope, BoundLayerList, assignVariableBindingUnits, boundNumberValue, collectionsBoundIn, layersUsingVariables, listBindingsAfterEdit, reconcileVariableBindings, resolvedIconBinding, resolvedNumericBindings, resolvedRunBindings, resolvedValueBindings, variableBindingOwner, variablesResolvingThrough } from "./bindings.js";
|
|
5
5
|
import { independentCornerChanges } from "./corners.js";
|
|
6
6
|
import { FormulaValueType, formulaArity, formulaSymbol } from "./formula/signatures.js";
|
|
7
7
|
import { PrintFormulaOptions, printFormula } from "./formula/print.js";
|
|
@@ -10,6 +10,7 @@ import { evaluateVariableFormula } from "./formula/evaluate.js";
|
|
|
10
10
|
import { formulaValueType, inferFormulaType } from "./formula/check.js";
|
|
11
11
|
import { formatVariableFormula, parseVariableFormula, variableFormulaReference } from "./formula/index.js";
|
|
12
12
|
import { variableFormulaSchema } from "./formula/schema.js";
|
|
13
|
+
import { AppliedBoundPaints, AppliedColor, applyBoundPaintColor, applyBoundPaintColorsIn, captureAppliedBoundPaints, copiesComponentPaints, copyAppliedBoundPaints, hasBoundPaints, keepCopyBoundPaints, keepPastedBoundPaints, paintColorApplied, recordWrittenBoundPaints, refreshBoundPaints, refreshBoundPaintsIn, refreshMovedBoundPaints, shownPaintBindings } from "./paints.js";
|
|
13
14
|
import { variableAliasSchema, variableCollectionSchema, variableColorExpressionSchema, variableSchema } from "./schema.js";
|
|
14
15
|
import { variableFontFamily, variableText, variableTruthy } from "./text.js";
|
|
15
16
|
import { ROOT_FONT_SIZE_PX, tokenExpressionForValue, tokenNumberFromUnit, tokenNumberInUnit, updateTokenExpression } from "./token.js";
|
|
@@ -31,12 +32,17 @@ declare function createMode(graph: SceneGraph, generateId: () => string, collect
|
|
|
31
32
|
declare function removeMode(graph: SceneGraph, collectionId: string, modeId: string): void;
|
|
32
33
|
declare function renameMode(graph: SceneGraph, collectionId: string, modeId: string, name: string): void;
|
|
33
34
|
declare function setDefaultMode(graph: SceneGraph, collectionId: string, modeId: string): void;
|
|
34
|
-
/** Figma has no default-mode field: the first mode is the default. */
|
|
35
|
+
/** Figma has no default-mode field: the first listed mode is the default. */
|
|
35
36
|
declare function modesDefaultFirst(collection: VariableCollection): VariableCollectionMode[];
|
|
37
|
+
/**
|
|
38
|
+
* The modes as Figma lists them: by `sortPosition`, modes without one following in saved order.
|
|
39
|
+
* The collection's own array keeps the file's saved order, which an export writes back as it was.
|
|
40
|
+
*/
|
|
41
|
+
declare function modesInListedOrder(collection: VariableCollection): VariableCollectionMode[];
|
|
36
42
|
declare function getVariablesForCollection(graph: SceneGraph, collectionId: string): Variable[];
|
|
37
43
|
declare function getVariablesByType(graph: SceneGraph, type: VariableType): Variable[];
|
|
38
44
|
declare function bindVariable(graph: SceneGraph, nodeId: string, field: string, variableId: string): void;
|
|
39
45
|
declare function unbindVariable(graph: SceneGraph, nodeId: string, field: string): void;
|
|
40
46
|
//#endregion
|
|
41
|
-
export { BindingScope, type FormulaFold, type FormulaToken, type FormulaTokenKind, type FormulaValueType, ICON_BINDING_FIELDS, MAX_FORMULA_DEPTH, NodeVariableResolver, type PaintBindingList, type PrintFormulaOptions, ROOT_FONT_SIZE_PX, SCALED_RUN_BINDING_FIELDS, ScaledRunBindingField, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, VariableFormulaError, VariableModeFallback, 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,
|
|
47
|
+
export { AppliedBoundPaints, AppliedColor, BindingScope, BoundLayerList, type FormulaFold, type FormulaToken, type FormulaTokenKind, type FormulaValueType, ICON_BINDING_FIELDS, MAX_FORMULA_DEPTH, NodeVariableResolver, type PaintBindingList, type PrintFormulaOptions, ROOT_FONT_SIZE_PX, SCALED_RUN_BINDING_FIELDS, ScaledRunBindingField, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, VariableFormulaError, VariableModeFallback, VariableResolutionError, addCollection, addMode, addVariable, applyBoundPaintColor, applyBoundPaintColorsIn, assignVariableBindingUnits, bindVariable, boundNumberValue, captureAppliedBoundPaints, collectionsBoundIn, collectionsResolving, copiesComponentPaints, copyAppliedBoundPaints, createBatchVariableResolver, createCollection, createMode, createVariable, evaluateVariableFormula, foldFormula, formatVariableFormula, formulaArity, formulaSymbol, formulaTokenName, formulaTokens, formulaValueType, getActiveModeId, getNodeExplicitVariableModeId, getNodeVariableModeId, getVariablesByType, getVariablesForCollection, hasBoundPaints, independentCornerChanges, inferFormulaType, isFormulaOperation, isFormulaReference, isNumericVariableBindingField, isUnsupportedVariableValue, keepCopyBoundPaints, keepPastedBoundPaints, layersUsingVariables, listBindingsAfterEdit, mapVariableValueReferences, modesDefaultFirst, modesInListedOrder, paintBindingTarget, paintColorApplied, parseVariableFormula, pinnedRunBindingScales, printFormula, readFormulaToken, reconcileVariableBindings, recordWrittenBoundPaints, refreshBoundPaints, refreshBoundPaintsIn, refreshMovedBoundPaints, removeCollection, removeMode, removeVariable, renameMode, resolveColorVariable, resolveColorVariableForNode, resolveNumberVariable, resolveNumberVariableForNode, resolveStringVariableForNode, resolveVariable, resolveVariableForNode, resolveVariableInModes, resolveVariableValue, resolvedIconBinding, resolvedNumericBindings, resolvedRunBindings, resolvedValueBindings, resolvedVariableModes, runBindingScale, scaleVariableBindingUnits, setActiveMode, setDefaultMode, shownPaintBindings, tokenExpressionForValue, tokenNumberFromUnit, tokenNumberInUnit, unbindVariable, updateTokenExpression, variableAliasSchema, variableBindingOwner, variableCollectionSchema, variableColorExpressionSchema, variableFontFamily, variableFormulaReference, variableFormulaSchema, variableSchema, variableText, variableTruthy, variableValueInMode, variableValueReferences, variablesResolvingThrough, withBoundBindingScales };
|
|
42
48
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/variables/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/variables/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;iBAwDgB,YAAY,OAAO,YAAY,UAAU;iBAQzC,eAAe,OAAO,YAAY;iBA8BlC,cAAc,OAAO,YAAY,YAAY;iBAe7C,eACd,OAAO,YACP,0BACA,cACA,MAAM,cACN,sBACA,QAAQ,gBACP;iBAsBa,iBACd,OAAO,YACP,0BACA,eACC;iBAca,iBAAiB,OAAO,YAAY;iBAmBpC,cAAc,OAAO,YAAY,sBAAsB;iBAIvD,QACd,OAAO,YACP,sBACA,gBACA,cACA;;iBAgBc,WACd,OAAO,YACP,0BACA,sBACA,cACA;iBAQc,WAAW,OAAO,YAAY,sBAAsB;iBA8BpD,WACd,OAAO,YACP,sBACA,gBACA;iBAQc,eAAe,OAAO,YAAY,sBAAsB;;iBAuBxD,kBAAkB,YAAY,qBAAqB;;;;;iBAYnD,mBAAmB,YAAY,qBAAqB;iBAOpD,0BAA0B,OAAO,YAAY,uBAAuB;iBAQpE,mBAAmB,OAAO,YAAY,MAAM,eAAe;iBAgE3D,aACd,OAAO,YACP,gBACA,eACA;iBA8Ec,eAAe,OAAO,YAAY,gBAAgB"}
|