-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.js
More file actions
295 lines (251 loc) · 8.46 KB
/
code.js
File metadata and controls
295 lines (251 loc) · 8.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
figma.showUI(__html__, { width: 320, height: 400 });
// Flag to track if update is in progress
let shouldCancelUpdate = false;
// When the plugin starts, check if there's a selection
checkSelection();
// Listen for selection changes
figma.on("selectionchange", () => {
checkSelection();
});
// Function to check the current selection
function checkSelection() {
const selection = figma.currentPage.selection;
if (selection.length === 0) {
figma.ui.postMessage({ type: "no-selection" });
} else {
figma.ui.postMessage({
type: "selection-ready",
count: selection.length
});
}
}
// Listen for messages from the UI
figma.ui.onmessage = async (msg) => {
if (msg.type === "update-components") {
shouldCancelUpdate = false;
await updateComponentsAndVariablesToLatest();
} else if (msg.type === "cancel-update") {
shouldCancelUpdate = true;
figma.ui.postMessage({ type: "update-cancelled" });
// After 3 seconds, recheck the selection to update the status
setTimeout(() => {
checkSelection();
}, 3000);
} else if (msg.type === "cancel") {
figma.closePlugin();
}
};
// The main function to update components and variables to their latest versions
async function updateComponentsAndVariablesToLatest() {
const selection = figma.currentPage.selection;
if (selection.length === 0) {
figma.ui.postMessage({ type: "error", message: "No selection found" });
return;
}
// Track our progress
let totalComponents = 0;
let updatedComponents = 0;
let skippedComponents = 0;
let errors = 0;
// For variables
let totalVariables = 0;
let updatedVariables = 0;
let skippedVariables = 0;
let variableErrors = 0;
// Step 1: Collect all instance nodes
figma.ui.postMessage({ type: "status", message: "Searching for rogue instances..." });
const instanceNodes = [];
const nodesWithVariables = [];
function collectNodesForUpdate(node) {
try {
if (!node.visible) return;
// Check if it's a component instance
if (node.type === "INSTANCE") {
instanceNodes.push(node);
}
// Check if the node has variable bindings
if (node.boundVariables && Object.keys(node.boundVariables).length > 0) {
nodesWithVariables.push(node);
}
// Recursively check children
if ("children" in node) {
for (const child of node.children) {
if (!child.locked) {
collectNodesForUpdate(child);
}
}
}
} catch (error) {
console.error("Error collecting nodes:", error);
}
}
// Collect all instances and variable-bound nodes from the selection
try {
for (const node of selection) {
if (shouldCancelUpdate) return;
collectNodesForUpdate(node);
}
} catch (error) {
console.error("Error in selection processing:", error);
figma.ui.postMessage({
type: "error",
message: "Error processing selection: " + error.message
});
return;
}
totalComponents = instanceNodes.length;
totalVariables = nodesWithVariables.length;
const totalItems = totalComponents + totalVariables;
if (totalItems === 0) {
figma.ui.postMessage({
type: "complete",
total: 0,
updated: 0,
skipped: 0,
errors: 0
});
return;
}
// Start the update process
figma.ui.postMessage({
type: "start-update",
total: totalItems
});
// Process components one by one
for (let i = 0; i < instanceNodes.length; i++) {
if (shouldCancelUpdate) return;
const node = instanceNodes[i];
try {
// Check if this is a component that can be updated
let isRemoteComponent = false;
let componentKey = null;
let mainComponent = null;
// Try to get the main component using the async method
try {
mainComponent = await node.getMainComponentAsync();
if (mainComponent && mainComponent.remote) {
isRemoteComponent = true;
componentKey = mainComponent.key;
}
} catch (error) {
console.log("Error getting main component:", error);
}
// If it's a remote component, try to update it
if (isRemoteComponent && componentKey) {
try {
// Try to get the latest version
const latestVersion = await figma.importComponentByKeyAsync(componentKey);
if (latestVersion && latestVersion !== mainComponent) {
// Swap to the latest version
node.swapComponent(latestVersion);
updatedComponents++;
} else {
skippedComponents++;
}
} catch (error) {
console.log("Error importing component:", error);
skippedComponents++;
}
} else {
skippedComponents++;
}
} catch (error) {
console.error("Error processing component:", error);
errors++;
}
// Update progress
figma.ui.postMessage({
type: "progress",
current: i + 1,
total: totalItems,
updated: updatedComponents + updatedVariables
});
// Add a small delay to prevent memory issues
await new Promise(resolve => setTimeout(resolve, 50));
}
// Process variables one by one
for (let i = 0; i < nodesWithVariables.length; i++) {
if (shouldCancelUpdate) return;
const node = nodesWithVariables[i];
try {
// Get the variable bindings for this node
const boundVariables = node.boundVariables;
if (boundVariables) {
let nodeUpdated = false;
// Check each variable binding
for (const [property, binding] of Object.entries(boundVariables)) {
// For direct variable bindings
if (binding.type === 'VARIABLE') {
const variable = binding.id;
try {
// Check if this is a remote variable that can be updated
if (variable.remote) {
const variableKey = variable.key;
// Try to get the latest version
const latestVariable = await figma.variables.importVariableByKeyAsync(variableKey);
if (latestVariable && latestVariable !== variable) {
// Update the binding to use the latest variable
node.setBoundVariable(property, latestVariable);
nodeUpdated = true;
}
}
} catch (error) {
console.log(`Error updating variable binding for ${property}:`, error);
}
}
// For variable alias bindings
else if (binding.type === 'VARIABLE_ALIAS') {
try {
const aliasVariable = binding.id;
if (aliasVariable.remote) {
const variableKey = aliasVariable.key;
// Try to get the latest version
const latestVariable = await figma.variables.importVariableByKeyAsync(variableKey);
if (latestVariable && latestVariable !== aliasVariable) {
// Update the binding to use the latest variable
node.setBoundVariable(property, {
type: 'VARIABLE_ALIAS',
id: latestVariable
});
nodeUpdated = true;
}
}
} catch (error) {
console.log(`Error updating variable alias binding for ${property}:`, error);
}
}
}
if (nodeUpdated) {
updatedVariables++;
} else {
skippedVariables++;
}
} else {
skippedVariables++;
}
} catch (error) {
console.error("Error processing variable bindings:", error);
variableErrors++;
}
// Update progress
figma.ui.postMessage({
type: "progress",
current: instanceNodes.length + i + 1,
total: totalItems,
updated: updatedComponents + updatedVariables
});
// Add a small delay to prevent memory issues
await new Promise(resolve => setTimeout(resolve, 50));
}
// Only send complete message if we didn't cancel
if (!shouldCancelUpdate) {
// Report the results
figma.ui.postMessage({
type: "complete",
total: totalComponents + totalVariables,
updated: updatedComponents + updatedVariables,
skipped: skippedComponents + skippedVariables,
errors: errors + variableErrors
});
}
}