-
Notifications
You must be signed in to change notification settings - Fork 123
/
controller.ts
1732 lines (1486 loc) · 52.9 KB
/
controller.ts
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
checkRadius,
newCheckStrokes,
checkType,
newCheckFills,
newCheckEffects,
determineFill,
gradientToCSS
// customCheckTextFills,
// uncomment this as an example of a custom lint function ^
} from "./lintingFunctions";
import { fetchRemoteStyles, groupLibrary } from "./remoteStyleFunctions";
const {
getLocalPaintStyles,
getLocalTextStyles,
getLocalEffectStyles
} = require("./styles");
figma.showUI(__html__, { width: 360, height: 580 });
let borderRadiusArray = [0, 2, 4, 8, 16, 24, 32];
let originalNodeTree: readonly any[] = [];
let lintVectors = false;
let localStylesLibrary = {};
// Styles used in our page
let usedRemoteStyles = {
name: "Remote Styles",
fills: [],
strokes: [],
text: [],
effects: []
};
// Variables object we'll use for storing all the variables
// found in our page.
let variablesInUse = {
name: "Variables",
variables: []
};
let colorVariables;
let numbervariables;
let variablesWithGroupedConsumers;
figma.skipInvisibleInstanceChildren = true;
// Function to generate a UUID
// This way we can store ignored errors per document rather than
// sharing ignored errors across all documents.
function generateUUID() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
var r = (Math.random() * 16) | 0,
v = c === "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
function getDocumentUUID() {
// Try to get the UUID from the document's plugin data
let uuid = figma.root.getPluginData("documentUUID");
// If the UUID does not exist (empty string), generate a new one and store it
if (!uuid) {
uuid = generateUUID();
figma.root.setPluginData("documentUUID", uuid);
}
return uuid;
}
// Set the unique ID we use for client storage.
const documentUUID = getDocumentUUID();
figma.on("documentchange", _event => {
// When a change happens in the document
// send a message to the plugin to look for changes.'
figma.ui.postMessage({
type: "change"
});
});
figma.ui.onmessage = msg => {
if (msg.type === "close") {
figma.closePlugin();
}
if (msg.type === "step-2") {
let layer = figma.getNodeById(msg.id);
let layerArray = [];
// Using figma UI selection and scroll to viewport requires an array.
layerArray.push(layer);
// Moves the layer into focus and selects so the user can update it.
// uncomment the line below if you want to notify something has been selected.
// figma.notify(`Layer ${layer.name} selected`, { timeout: 750 });
figma.currentPage.selection = layerArray;
figma.viewport.scrollAndZoomIntoView(layerArray);
let layerData = JSON.stringify(layer, [
"id",
"name",
"description",
"fills",
"key",
"type",
"remote",
"paints",
"fontName",
"fontSize",
"font"
]);
figma.ui.postMessage({
type: "step-2-complete",
message: layerData
});
}
// Fetch a specific node by ID.
if (msg.type === "fetch-layer-data") {
let layer = figma.getNodeById(msg.id);
let layerArray = [];
// Using figma UI selection and scroll to viewport requires an array.
layerArray.push(layer);
// Moves the layer into focus and selects so the user can update it.
// uncomment the line below if you want to notify something has been selected.
// figma.notify(`Layer ${layer.name} selected`, { timeout: 750 });
figma.currentPage.selection = layerArray;
figma.viewport.scrollAndZoomIntoView(layerArray);
let layerData = JSON.stringify(layer, [
"id",
"name",
"description",
"fills",
"key",
"type",
"remote",
"paints",
"fontName",
"fontSize",
"font"
]);
figma.ui.postMessage({
type: "fetched layer",
message: layerData
});
}
// Called when an update in the Figma file happens
// so we can check what changed.
if (msg.type === "update-errors") {
figma.ui.postMessage({
type: "updated errors",
errors: lint(originalNodeTree, msg.libraries)
});
}
// Used only to update the styles page when its selected.
async function handleUpdateStylesPage() {
const resetRemoteStyles = {
name: "Remote Styles",
fills: [],
strokes: [],
text: [],
effects: []
};
await fetchRemoteStyles(resetRemoteStyles);
const libraryWithGroupedConsumers = groupLibrary(resetRemoteStyles);
libraryWithGroupedConsumers.fills.sort((a, b) =>
a.name.localeCompare(b.name)
);
libraryWithGroupedConsumers.text.sort((a, b) =>
a.name.localeCompare(b.name)
);
libraryWithGroupedConsumers.strokes.sort((a, b) =>
a.name.localeCompare(b.name)
);
libraryWithGroupedConsumers.effects.sort((a, b) =>
a.name.localeCompare(b.name)
);
figma.ui.postMessage({
type: "remote-styles-imported",
message: libraryWithGroupedConsumers
});
}
// Updates all the styles listed on the styles page.
if (msg.type === "update-styles-page") {
handleUpdateStylesPage();
}
// Notify the user of an issue.
if (msg.type === "notify-user") {
figma.notify(msg.message, { timeout: 1000 });
}
// Updates client storage with a new ignored error
// when the user selects "ignore" from the context menu
if (msg.type === "update-storage") {
let arrayToBeStored = JSON.stringify(msg.storageArray);
figma.clientStorage.setAsync(documentUUID, arrayToBeStored);
}
// Clears all ignored errors
// invoked from the settings menu
if (msg.type === "update-storage-from-settings") {
let arrayToBeStored = JSON.stringify(msg.storageArray);
figma.clientStorage.setAsync(documentUUID, arrayToBeStored);
figma.ui.postMessage({
type: "reset storage",
storage: arrayToBeStored
});
figma.notify("Cleared ignored errors", { timeout: 1000 });
}
// Remembers the last tab selected in the UI and sets it
// to be active (layers vs error by category view)
if (msg.type === "update-active-page-in-settings") {
let pageToBeStored = JSON.stringify(msg.page);
figma.clientStorage.setAsync("storedActivePage", pageToBeStored);
}
// Changes the linting rules, invoked from the settings menu
if (msg.type === "update-lint-rules-from-settings") {
lintVectors = msg.boolean;
}
// For when the user updates the border radius values to lint from the settings menu.
if (msg.type === "update-border-radius") {
let newRadiusArray = null;
if (typeof msg.radiusValues === "string") {
let newString = msg.radiusValues.replace(/\s+/g, "");
newRadiusArray = newString.split(",");
newRadiusArray = newRadiusArray
.filter(x => x.trim().length && !isNaN(x))
.map(Number);
// Most users won't add 0 to the array of border radius so let's add it in for them.
if (newRadiusArray.indexOf(0) === -1) {
newRadiusArray.unshift(0);
}
} else {
newRadiusArray = msg.radiusValues;
}
// Update the array we pass into checkRadius for linting.
newRadiusArray = newRadiusArray.sort((a, b) => a - b);
borderRadiusArray = newRadiusArray;
// Save this value in client storage.
let radiusToBeStored = JSON.stringify(borderRadiusArray);
figma.clientStorage.setAsync("storedRadiusValues", radiusToBeStored);
figma.ui.postMessage({
type: "fetched border radius",
storage: JSON.stringify(borderRadiusArray)
});
figma.notify("Saved border radius, this can be changed in settings", {
timeout: 1500
});
}
if (msg.type === "reset-border-radius") {
borderRadiusArray = [0, 2, 4, 8, 16, 24, 32];
figma.clientStorage.setAsync("storedRadiusValues", []);
figma.ui.postMessage({
type: "fetched border radius",
storage: JSON.stringify(borderRadiusArray)
});
figma.notify("Reset border radius value", { timeout: 1000 });
}
// Function to check if a style key exists locally for text layers.
function isStyleKeyLocal(styleKey) {
const localStyles = figma.getLocalTextStyles();
for (const style of localStyles) {
if (style.key === styleKey) {
return true;
}
}
return false;
}
// Check if a style key exists in use, like local styles but checks remote styles too.
function isStyleInUse(styleId) {
const style = figma.getStyleById(styleId);
return style !== null;
}
// If a style is local, we can apply it
function applyLocalStyle(node, styleId) {
// const localStyles = figma.getLocalTextStyles();
// const style = localStyles.find(style => style.key === styleKey);
node.textStyleId = styleId;
}
// Some styles are remote so we need to import them first.
async function applyRemoteStyle(node, importedStyle) {
try {
node.textStyleId = importedStyle.id;
} catch (error) {
console.error("Error applying remote style:", error);
}
}
// Called from BulkErrorList when updating matching styles
// or applying suggestion styles.
if (msg.type === "apply-styles") {
function applyLocalFillStyle(node, styleId) {
node.fillStyleId = styleId;
}
function applyLocalStrokeStyle(node, styleId) {
node.strokeStyleId = styleId;
}
function applyLocalEffectStyle(node, styleId) {
node.effectStyleId = styleId;
}
async function applyStylesToNodes(field, index) {
const styleKey = msg.error[field][index].key;
const styleId = msg.error[field][index].id;
if (
(msg.error.type === "text" && isStyleInUse(styleId)) ||
(msg.error.type === "text" && isStyleKeyLocal(styleKey))
) {
for (const nodeId of msg.error.nodes) {
const node = figma.getNodeById(nodeId);
if (node && node.type === "TEXT") {
applyLocalStyle(node, styleId);
}
}
} else if (
(msg.error.type === "fill" && isStyleInUse(styleId)) ||
(msg.error.type === "fill" && isStyleKeyLocal(styleKey))
) {
for (const nodeId of msg.error.nodes) {
const node = figma.getNodeById(nodeId);
if (node) {
applyLocalFillStyle(node, styleId);
}
}
} else if (
(msg.error.type === "stroke" && isStyleInUse(styleId)) ||
(msg.error.type === "stroke" && isStyleKeyLocal(styleKey))
) {
for (const nodeId of msg.error.nodes) {
const node = figma.getNodeById(nodeId);
if (node) {
applyLocalStrokeStyle(node, styleId);
}
}
} else if (
(msg.error.type === "effects" && isStyleInUse(styleId)) ||
(msg.error.type === "effects" && isStyleKeyLocal(styleKey))
) {
for (const nodeId of msg.error.nodes) {
const node = figma.getNodeById(nodeId);
if (node) {
applyLocalEffectStyle(node, styleId);
}
}
} else {
// Import the remote style
let importedStyle;
try {
importedStyle = await figma.importStyleByKeyAsync(styleKey);
} catch (error) {
if (!error.message.includes("Cannot find style")) {
console.error("Error importing style:", error);
}
}
// Apply the imported style to all layers
if (importedStyle) {
const batchSize = 10;
for (let i = 0; i < msg.error.nodes.length; i += batchSize) {
const batch = msg.error.nodes.slice(i, i + batchSize);
for (const nodeId of batch) {
const node = figma.getNodeById(nodeId);
if (node && node.type === "TEXT" && msg.error.type === "text") {
await applyRemoteStyle(node, importedStyle);
} else if (node && msg.error.type === "fill") {
node.fillStyleId = importedStyle.id;
} else if (node && msg.error.type === "stroke") {
node.strokeStyleId = importedStyle.id;
}
}
await delay(3);
}
}
}
}
``;
// we pass in suggestions or messages as fields
// index is which of the multiple styles they chose from in the suggestions array.
applyStylesToNodes(msg.field, msg.index);
figma.notify(`Fixed ${msg.count} missing ${msg.error.type} styles`, {
timeout: 500
});
}
if (msg.type === "select-multiple-layers") {
const layerArray = msg.nodeArray;
let nodesToBeSelected = [];
layerArray.forEach(item => {
let layer = figma.getNodeById(item);
// Using selection and viewport requires an array.
nodesToBeSelected.push(layer);
});
// Moves the layer into focus and selects so the user can update it.
figma.currentPage.selection = nodesToBeSelected;
figma.viewport.scrollAndZoomIntoView(nodesToBeSelected);
figma.notify(`${nodesToBeSelected.length} layers selected`, {
timeout: 750
});
}
function createPaintStyleFromNode(node, nodeArray, title) {
// Check if the node has at least one fill
if (node.fills && node.fills.length > 0) {
// Get the first fill of the node
const fill = node.fills[0];
let currentFill = determineFill(node.fills);
// Create a new paint style based on the fill properties of the node
const newPaintStyle = figma.createPaintStyle();
// Set the name and paint of the new paint style
if (title !== "") {
newPaintStyle.name = title;
} else {
newPaintStyle.name = `New Fill - ${currentFill}`;
}
newPaintStyle.paints = [fill];
// Apply the new style to all of the layers the error exists on
for (const node of nodeArray) {
const layer = figma.getNodeById(node);
layer.fillStyleId = newPaintStyle.id;
}
// Notify the user that the paint style has been created and applied
figma.notify(
`Fill style created and applied to ${nodeArray.length} layers`
);
}
}
function roundToDecimalPlaces(value, decimalPlaces) {
const multiplier = Math.pow(10, decimalPlaces);
return Math.round(value * multiplier) / multiplier;
}
function createStrokeStyleFromNode(node, nodeArray, title) {
if (node.strokes && node.strokes.length > 0) {
const stroke = node.strokes[0];
const newStrokeStyle = figma.createPaintStyle();
newStrokeStyle.name = "New Stroke Style";
if (title !== "") {
newStrokeStyle.name = title;
} else {
newStrokeStyle.name = "New Stroke Style";
}
newStrokeStyle.paints = [stroke];
// Apply the new style to all of the layers the error exists on
for (const node of nodeArray) {
const layer = figma.getNodeById(node);
layer.strokeStyleId = newStrokeStyle.id;
}
figma.notify(
`Stroke style created and applied to ${nodeArray.length} layers`
);
}
}
function createEffectStyleFromNode(node, nodeArray, title) {
// Check if the node has at least one effect
if (node.effects && node.effects.length > 0) {
// Get the effects of the node
const effects = node.effects;
let effectType = node.effects[0].type;
if (effectType === "DROP_SHADOW") {
effectType = "Drop Shadow";
} else if (effectType === "INNER_SHADOW") {
effectType = "Inner Shadow";
} else if (effectType === "LAYER_BLUR") {
effectType = "Layer Blur";
} else {
effectType = "Background Blur";
}
const effectRadius = node.effects[0].radius;
const roundedRadius = roundToDecimalPlaces(effectRadius, 1);
// Create a new effect style based on the effect properties of the node
const newEffectStyle = figma.createEffectStyle();
if (title !== "") {
newEffectStyle.name = title;
} else {
newEffectStyle.name = `${effectType} - Radius: ${roundedRadius}`;
}
newEffectStyle.effects = effects;
// Apply the new style to all of the layers the error exists on
for (const node of nodeArray) {
const layer = figma.getNodeById(node);
layer.effectStyleId = newEffectStyle.id;
}
// Notify the user that the effect style has been created and applied
figma.notify(
`Effect style created and applied to ${nodeArray.length} layers`
);
}
}
// Utility for creating new text styles from the select menu
async function createTextStyleFromNode(node, nodeArray, title) {
if (node.type === "TEXT") {
// // Load the font used in the text node
// await figma.loadFontAsync(node.fontName);
try {
await figma.loadFontAsync(node.fontName);
} catch (error) {
figma.notify(
`Couldn't create a style because the following font isn't available: ${node.fontName.family}`
);
return;
}
// Get the properties of the text node
const textStyle = {
fontFamily: node.fontName.family,
fontStyle: node.fontName.style,
fontSize: node.fontSize,
letterSpacing: node.letterSpacing,
lineHeight: node.lineHeight,
paragraphIndent: node.paragraphIndent,
paragraphSpacing: node.paragraphSpacing,
textCase: node.textCase,
textDecoration: node.textDecoration
};
// Create a new text style based on the properties of the text node
const newTextStyle = figma.createTextStyle();
if (title !== "") {
newTextStyle.name = title;
} else {
newTextStyle.name = `${textStyle.fontFamily} ${textStyle.fontStyle}`;
}
newTextStyle.fontName = {
family: textStyle.fontFamily,
style: textStyle.fontStyle
};
newTextStyle.fontSize = textStyle.fontSize;
newTextStyle.letterSpacing = textStyle.letterSpacing;
newTextStyle.lineHeight = textStyle.lineHeight;
newTextStyle.paragraphIndent = textStyle.paragraphIndent;
newTextStyle.paragraphSpacing = textStyle.paragraphSpacing;
newTextStyle.textCase = textStyle.textCase;
newTextStyle.textDecoration = textStyle.textDecoration;
// Apply the new style to all of the layers the error exists on
for (const textNode of nodeArray) {
const layer = figma.getNodeById(textNode);
if (layer.type === "TEXT") {
layer.textStyleId = newTextStyle.id;
}
}
figma.notify(
`Text style created and applied to ${nodeArray.length} layers`
);
}
}
if (msg.type === "create-style") {
// Grab a node to use so we have properties to create a style
const node = figma.getNodeById(msg.error.nodes[0]);
if (msg.error.type === "text") {
createTextStyleFromNode(node, msg.error.nodes, msg.title);
} else if (msg.error.type === "fill") {
createPaintStyleFromNode(node, msg.error.nodes, msg.title);
} else if (msg.error.type === "effects") {
createEffectStyleFromNode(node, msg.error.nodes, msg.title);
} else if (msg.error.type === "stroke") {
createStrokeStyleFromNode(node, msg.error.nodes, msg.title);
}
}
// Serialize nodes to pass back to the UI.
function serializeNodes(nodes) {
let serializedNodes = JSON.stringify(nodes, [
"name",
"type",
"children",
"id"
]);
return serializedNodes;
}
function lint(nodes, libraries, lockedParentNode = false) {
let errorArray = [];
// Use a for loop instead of forEach
for (const node of nodes) {
// Determine if the layer or its parent is locked.
const isLayerLocked = lockedParentNode || node.locked;
const nodeChildren = node.children;
// Create a new object.
const newObject = {
id: node.id,
errors: isLayerLocked ? [] : determineType(node, libraries),
children: []
};
// Check if the node has children.
if (nodeChildren) {
// Recursively run this function to flatten out children and grandchildren nodes.
newObject.children = node.children.map(childNode => childNode.id);
errorArray.push(...lint(node.children, libraries, isLayerLocked));
}
errorArray.push(newObject);
}
return errorArray;
}
function delay(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
// Counter to keep track of the total number of processed nodes
let nodeCounter = 0;
async function* lintAsync(nodes, libraries, lockedParentNode = false) {
let errorArray = [];
for (const node of nodes) {
// Determine if the layer or its parent is locked.
const isLayerLocked = lockedParentNode || node.locked;
// Create a new object.
const newObject = {
id: node.id,
errors: isLayerLocked ? [] : determineType(node, libraries),
children: []
};
// Check if the node has children.
if (node.children) {
// Recursively run this function to flatten out children and grandchildren nodes.
newObject.children = node.children.map(childNode => childNode.id);
for await (const result of lintAsync(
node.children,
libraries,
isLayerLocked
)) {
errorArray.push(...result);
}
}
errorArray.push(newObject);
// Increment the node counter, this is our number of layers total.
nodeCounter++;
// console.log(nodeCounter);
// Yield the result after processing a certain number of nodes
if (nodeCounter % 1000 === 0) {
yield errorArray;
errorArray = [];
await delay(5);
}
}
// Yield any remaining results
if (errorArray.length > 0) {
yield errorArray;
}
}
if (msg.type === "step-3") {
// Use an async function to handle the asynchronous generator
async function processLint() {
const finalResult = [];
for await (const result of lintAsync(originalNodeTree, msg.libraries)) {
finalResult.push(...result);
}
// Pass the final result back to the UI to be displayed.
figma.ui.postMessage({
type: "step-3-complete",
errors: finalResult,
message: serializeNodes(originalNodeTree)
});
}
// Start the lint process
figma.notify(`Design Lint is running and automatically detect changes`, {
timeout: 1500
});
processLint();
}
// Import local styles to use as recommendations
// This function doesn't save the styles, that's "save-library"
if (msg.type === "find-local-styles") {
(async function() {
const paintStylesData = await getLocalPaintStyles();
const textStylesData = await getLocalTextStyles();
const effectStylesData = await getLocalEffectStyles();
const fileName = figma.root.name;
const totalStyles =
effectStylesData.length +
textStylesData.length +
paintStylesData.length;
const localStyles = {
name: fileName,
effects: effectStylesData,
fills: paintStylesData,
text: textStylesData,
styles: totalStyles
};
// Send the updated libraries array to the UI layer
figma.ui.postMessage({
type: "local-styles-imported",
message: localStyles
});
})();
}
// Saves local styles as a library to use in every file.
if (msg.type === "save-library") {
(async function() {
const paintStylesData = await getLocalPaintStyles();
const textStylesData = await getLocalTextStyles();
const effectStylesData = await getLocalEffectStyles();
const fileName = figma.root.name;
const totalStyles =
effectStylesData.length +
textStylesData.length +
paintStylesData.length;
const key = "libraryKey";
const library = {
name: fileName,
effects: effectStylesData,
fills: paintStylesData,
text: textStylesData,
styles: totalStyles
};
// Fetch the stored libraries from client storage
const storedLibraries = (await figma.clientStorage.getAsync(key)) || [];
// Check if a library with the same name already exists in the libraries array
const existingLibraryIndex = storedLibraries.findIndex(
storedLibrary => storedLibrary.name === library.name
);
if (existingLibraryIndex !== -1) {
// If the library exists, update the existing library
storedLibraries[existingLibraryIndex] = library;
} else {
// If the library doesn't exist, add it to the libraries array
storedLibraries.push(library);
}
// Save the updated libraries array to client storage
await figma.clientStorage.setAsync(key, storedLibraries);
// Send the updated libraries array to the UI layer
figma.ui.postMessage({
type: "library-imported",
message: storedLibraries
});
})();
}
if (msg.type === "remove-library") {
figma.clientStorage.setAsync("libraryKey", msg.storageArray);
}
// Initialize the app
if (msg.type === "run-app") {
if (figma.currentPage.selection.length === 0 && msg.selection === "user") {
figma.notify(`Select some layers, then try running again!`, {
timeout: 2000
});
// If the user hasn't selected anything, show the empty state.
figma.ui.postMessage({
type: "show-empty-state"
});
return;
} else {
let nodes = null;
let firstNode = [];
// Determine whether we scan the page for the user,
// or use their selection
if (msg.selection === "user") {
nodes = figma.currentPage.selection;
firstNode.push(figma.currentPage.selection[0]);
} else if (msg.selection === "page") {
nodes = figma.currentPage.children;
firstNode.push(nodes[0]);
}
// Maintain the original tree structure so we can enable
// refreshing the tree and live updating errors.
originalNodeTree = nodes;
// Show the preloader until we're ready to render content.
figma.ui.postMessage({
type: "show-preloader"
});
// Fetch the ignored errors and libraries from client storage
const ignoredErrorsPromise = figma.clientStorage.getAsync(documentUUID);
const librariesPromise = figma.clientStorage.getAsync("libraryKey");
Promise.all([ignoredErrorsPromise, librariesPromise]).then(
async ([ignoredErrors, libraries]) => {
if (ignoredErrors && ignoredErrors.length) {
figma.ui.postMessage({
type: "fetched storage",
storage: ignoredErrors
});
}
if (libraries && libraries.length) {
figma.ui.postMessage({
type: "library-imported-from-storage",
message: libraries
});
}
async function findRemoteStyles() {
const currentPage = figma.currentPage;
const nodes = currentPage
.findAllWithCriteria({
types: [
"TEXT",
"FRAME",
"COMPONENT",
"RECTANGLE",
"ELLIPSE",
"INSTANCE",
"VECTOR",
"LINE"
]
})
.filter(node => {
// Check for remote styles
return (
node.fillStyleId ||
node.strokeStyleId ||
(node.type === "TEXT" && node.textStyleId) ||
node.effectStyleId
);
});
for (const node of nodes) {
if (node.fillStyleId) {
const styleId = node.fillStyleId;
if (typeof styleId !== "symbol") {
// Check if the style with the given styleId already exists in the usedRemoteStyles.fills array
const existingStyle = usedRemoteStyles.fills.find(
style => style.id === styleId
);
if (existingStyle) {
// If the style exists, update the count and consumers properties
existingStyle.count += 1;
existingStyle.consumers.push(node);
} else {
// If the style does not exist, create a new style object and push it to the usedRemoteStyles.fills array
const style = figma.getStyleById(styleId);
// Prevents against broken image fills.
if (style === null) {
return;
}
let currentFill = determineFill(node.fills);
let nodeFillType = node.fills[0].type;
let cssSyntax = null;
if (nodeFillType === "SOLID") {
cssSyntax = currentFill;
} else if (
nodeFillType !== "SOLID" &&
nodeFillType !== "VIDEO" &&
nodeFillType !== "IMAGE"
) {
cssSyntax = gradientToCSS(node.fills[0]);
}
usedRemoteStyles.fills.push({
id: node.fillStyleId,
type: "fill",
paint: style.paints[0],
name: style.name,
count: 1,
consumers: [node],
fillColor: cssSyntax
});
}
}
}
if (node.strokeStyleId) {
const styleId = node.strokeStyleId;
if (typeof styleId !== "symbol") {
// Check if the stroke style with the given styleId already exists in the usedRemoteStyles.strokes array
const existingStyle = usedRemoteStyles.strokes.find(
style => style.id === styleId
);
if (existingStyle) {
// If the stroke style exists, update the count and consumers properties
existingStyle.count += 1;
existingStyle.consumers.push(node);
} else {
// If the stroke style does not exist, create a new style object and push it to the usedRemoteStyles.strokes array
const style = figma.getStyleById(styleId);
let nodeFillType = style.paints[0].type;
let cssSyntax = null;
if (nodeFillType === "SOLID") {
cssSyntax = determineFill(style.paints);
} else if (
nodeFillType !== "IMAGE" &&
nodeFillType !== "VIDEO"
) {
cssSyntax = gradientToCSS(node.strokes[0]);
}
usedRemoteStyles.strokes.push({
id: node.strokeStyleId,