forked from thomas-lowry/themer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
code.ts
750 lines (654 loc) · 23.1 KB
/
code.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
// VARS
// API credentials
var apiSecret:string;
var apiURL:string;
// THEME DATA VARS
// this is the latest data from JSON Bin,
// we will append this to the cleaned data
var jsonBinData = [];
// this is all of the raw styles data we collect when creating a new theme
// it may contain duplicates, and themes using prefixed names have not been split up
var collectedStyleData = [];
// clean data, this is an array of all of the processed new data
var cleanedStyleData = [];
// this is the assembled clean data that is ready
// to be sent back to the UI to push to JSON bin
var newJsonBinData = [];
// settings
var usePrefixes:boolean;
var newThemeName:string;
var newThemeCount = 0;
var existingThemeCount:number;
//vars for applying
var selectedTheme:string;
// show the UI
figma.showUI(__html__, {width: 240, height: 312 });
//INITIALIZE PLUGIN
//Check to see if credentials exist in client storage
//run on plugin initilization
(async () => {
try {
apiURL = await figma.clientStorage.getAsync('apiURL');
apiSecret = await figma.clientStorage.getAsync('apiSecret');
if (apiURL && apiSecret) {
//send a message to the UI with the credentials storred in the client
figma.ui.postMessage({
'type': 'apiCredentials',
'status': true,
'url': apiURL,
'secret': apiSecret
});
} else {
//send a message to the UI that says there are no credentials storred in the client
figma.ui.postMessage({
'type': 'apiCredentials',
'status': false
});
}
} catch (err) {
figma.closePlugin('There was an error.');
return;
}
})();
//MESSAGING TO PLUGIN UI
figma.ui.onmessage = async (msg) => {
switch (msg.type) {
case 'notify':
figma.notify(msg.msg, {timeout: 1500 });
break;
case 'initialThemerData':
updateCredentials(msg.secret, msg.url);
figma.notify(msg.msg, {timeout: 1000 });
break;
case 'applyTheme':
selectedTheme = msg.themeName;
applyTheme(msg.applyTo);
break;
case 'createTheme':
updatedDataFromAPI(msg.apiData);
createTheme(msg);
break;
case 'deleteTheme':
updatedDataFromAPI(msg.themeData);
figma.notify(msg.msg, {timeout: 1000 });
break;
case 'updateThemes':
updatedDataFromAPI(msg.themeData);
break;
case 'reset':
resetThemer();
break;
}
}
//RESET THEMER
function resetThemer() {
(async () => {
try {
await figma.clientStorage.setAsync('apiSecret', '');
await figma.clientStorage.setAsync('apiURL', '');
} catch (err) {
figma.notify('There was an issue saving your credentials. Please try again.');
}
})();
figma.notify('Themer reset successfully');
}
// CREATE THEMES
function createTheme(data) {
// set prefixes setting
if (data.usePrefixes === true) {
usePrefixes = true;
} else {
usePrefixes = false;
}
//determine name
if (data.themeName) {
newThemeName = data.themeName;
}
clearStyleData();
// use the correct method to collect styles
// based on user selection
switch (data.source) {
case 'local':
//get styles
if (data.colorStyles) { getLocalStyles('color'); }
if (data.textStyles) { getLocalStyles('text'); }
if (data.effectStyles) { getLocalStyles('effect'); }
break;
case 'selection':
// get styles from selection
let selection = Array.from(figma.currentPage.selection);
if (selection) {
//get styles
if (data.colorStyles) {
selection.forEach(node => {
collectColorStyles(node);
})
}
if (data.textStyles) {
selection.forEach(node => {
collectTextStyles(node);
})
}
if (data.effectStyles) {
selection.forEach(node => {
collectEffectStyles(node);
})
}
} else {
figma.notify('Please make a selection');
}
break;
case 'page':
//get nodes from entire page
let pageNodes = Array.from(figma.currentPage.children);
if (pageNodes) {
//get styles
if (data.colorStyles) {
pageNodes.forEach(node => {
collectColorStyles(node);
})
}
if (data.textStyles) {
pageNodes.forEach(node => {
collectTextStyles(node);
})
}
if (data.effectStyles) {
pageNodes.forEach(node => {
collectEffectStyles(node);
})
}
} else {
figma.notify('There is nothing on this page');
}
break;
}
// merge with existing data
mergeNewThemesWithExisting();
// count number of themes being added
// in most cases it will be 1
// unless the user is creating multiple themes at once
// by splitting them at prefixes
countNewThemes();
// send data back to UI to post to JSON bin
sendNewThemeDataToUI();
}
//collect styles from local styles
function getLocalStyles(type) {
if (type === 'color') {
let colorStyles = figma.getLocalPaintStyles();
if (colorStyles) {
colorStyles.forEach(color => {
let style = {
'name': styleName(color.name),
'key': color.key,
'theme': themeName(color.name),
'type': 'PAINT'
}
if (style.name && style.key && style.theme && style.type) {
collectedStyleData.push(style);
} else {
figma.notify('Error adding theme');
throw new Error("Error adding theme");
}
});
} else {
figma.notify('There are no color styles in the document');
}
} else if (type === 'text') {
let textStyles = figma.getLocalTextStyles();
if (textStyles) {
textStyles.forEach(text => {
let style = {
'name': styleName(text.name),
'key': text.key,
'theme': themeName(text.name),
'type': 'TEXT'
}
if (style.name && style.key && style.theme && style.type) {
collectedStyleData.push(style);
} else {
figma.notify('Error adding theme');
throw new Error("Error adding theme");
}
});
} else {
figma.notify('There are no text styles in the document');
}
} else if (type === 'effect') {
let effectStyles = figma.getLocalEffectStyles();
if (effectStyles) {
effectStyles.forEach(effect => {
let style = {
'name': styleName(effect.name),
'key': effect.key,
'theme': themeName(effect.name),
'type': 'EFFECT'
}
if (style.name && style.key && style.theme && style.type) {
collectedStyleData.push(style);
} else {
figma.notify('Error adding theme');
throw new Error("Error adding theme");
}
});
} else {
figma.notify('There are no effect styles in the document');
}
}
}
// grab color styles
function collectColorStyles(node) {
// check for children on note, if they exist, run them through this function
// this will help us walk the tree to the bottom most level
if (node.children) {
node.children.forEach(child => {
collectColorStyles(child);
});
}
//here is where we grab all of the styles if they exist on the node
if (node.type === 'COMPONENT'||'INSTANCE'||'FRAME'||'GROUP') {
if (node.backgroundStyleId) {
let objectStyle = figma.getStyleById(node.backgroundStyleId);
// key will only be available for remote styles
if (objectStyle.key) {
let style = {
'name': styleName(objectStyle.name),
'key': objectStyle.key,
'theme': themeName(objectStyle.name),
'type': 'PAINT'
}
if (style.name && style.key && style.theme && style.type) {
collectedStyleData.push(style);
} else {
figma.notify('Error adding theme');
throw new Error("Error adding theme");
}
}
}
}
if (node.type === 'RECTANGLE'||'POLYGON'||'ELLIPSE'||'STAR'||'TEXT'||'VECTOR'||'BOOLEAN_OPERATION'||'LINE') {
if (node.fillStyleId) {
let objectStyle = figma.getStyleById(node.fillStyleId);
// key will only be available for remote styles
if (objectStyle.key) {
let style = {
'name': styleName(objectStyle.name),
'key': objectStyle.key,
'theme': themeName(objectStyle.name),
'type': 'PAINT'
}
if (style.name && style.key && style.theme && style.type) {
collectedStyleData.push(style);
} else {
figma.notify('Error adding theme');
throw new Error("Error adding theme");
}
}
}
if (node.strokeStyleId) {
let objectStyle = figma.getStyleById(node.strokeStyleId);
// key will only be available for remote styles
if (objectStyle.key) {
let style = {
'name': styleName(objectStyle.name),
'key': objectStyle.key,
'theme': themeName(objectStyle.name),
'type': 'PAINT'
}
if (style.name && style.key && style.theme && style.type) {
collectedStyleData.push(style);
} else {
figma.notify('Error adding theme');
return;
}
}
}
}
}
// grab text styles
function collectTextStyles(node) {
// check for children on note, if they exist, run them through this function
// this will help us walk the tree to the bottom most level
if (node.children) {
node.children.forEach(child => {
collectTextStyles(child);
});
}
if (node.type === 'TEXT' && node.textStyleId != 'MIXED' && node.textStyleId) {
let objectStyle = figma.getStyleById(node.textStyleId);
// key will only be available for remote styles
if (objectStyle.key) {
let style = {
'name': styleName(objectStyle.name),
'key': objectStyle.key,
'theme': themeName(objectStyle.name),
'type': 'TEXT'
}
if (style.name && style.key && style.theme && style.type) {
collectedStyleData.push(style);
} else {
figma.notify('Error adding theme');
throw new Error("Error adding theme");
}
}
}
}
// grab effect styles
function collectEffectStyles(node) {
if (node.children) {
node.children.forEach(child => {
collectEffectStyles(child);
});
}
if (node.effectStyleId) {
let objectStyle = figma.getStyleById(node.effectStyleId);
// key will only be available for remote styles
if (objectStyle.key) {
let style = {
'name': styleName(objectStyle.name),
'key': objectStyle.key,
'theme': themeName(objectStyle.name),
'type': 'TEXT'
}
if (style.name && style.key && style.theme && style.type) {
collectedStyleData.push(style);
} else {
figma.notify('Error adding theme');
throw new Error("Error adding theme");
}
}
}
}
// data passback to UI for posting to JSON Bin
function sendNewThemeDataToUI() {
if (cleanedStyleData) {
figma.ui.postMessage({
'type': 'addNewTheme',
'themeCount': newThemeCount,
'themeData': JSON.stringify(newJsonBinData)
});
} else {
figma.notify('There are no styles to create a theme from');
return;
}
}
// get theme name
function themeName(name) {
if (usePrefixes) {
if (name.includes('/')) {
let prefix = name.split('/');
return prefix[0];
} else {
figma.notify('Styles names must be prefixed. Ex: themeName/colorName');
}
} else {
return newThemeName;
}
}
function styleName(name) {
if (usePrefixes) {
if (name.includes('/')) {
let styleName = name.split('/').slice(1).join('.');
return styleName;
} else {
figma.notify('Styles names must be prefixed. Ex: themeName/colorName');
}
} else {
return name;
}
}
// count number of themes being added
function countNewThemes() {
let themes = [...new Set(cleanedStyleData.map(style => style.theme))];
newThemeCount = themes.length;
}
// clean existing data from style creation process to make sure arrays are empty
function clearStyleData() {
collectedStyleData = [];
cleanedStyleData = [];
newJsonBinData = [];
}
// merge theme data
// this function will merge the collected data
// with the existing theme data
function mergeNewThemesWithExisting() {
cleanedStyleData = removeDuplicatesBy(style => style.key, collectedStyleData);
if (cleanedStyleData) {
if (existingThemeCount === 0) {
cleanedStyleData.forEach(style => {
newJsonBinData.push(style);
});
} else {
jsonBinData.forEach(style => {
newJsonBinData.push(style);
});
cleanedStyleData.forEach(style => {
newJsonBinData.push(style);
});
}
} else {
figma.notify('Something went wrong while processing your theme data');
}
}
// APPLY THEME
function applyTheme(applyTo) {
let nodes;
if (applyTo === 'selection') {
if (figma.currentPage.selection) {
nodes = figma.currentPage.selection;
} else {
figma.notify('Please make a selection');
}
} else {
if (figma.currentPage.children) {
nodes = figma.currentPage.children;
} else {
figma.notify('Please make a selection');
}
}
if (nodes) {
figma.notify('Applying theme...', {timeout: 1000 });
let colorStyles = [...new Set(jsonBinData.map(style => style.theme === selectedTheme && style.type === 'PAINT'))];
let textStyles = [...new Set(jsonBinData.map(style => style.theme === selectedTheme && style.type === 'TEXT'))];
let effectStyles = [...new Set(jsonBinData.map(style => style.theme === selectedTheme && style.type === 'EFFECT'))];
//if the theme contains color styles
//iterate through all nodes to find color styles that match
if (colorStyles) {
nodes.forEach(node => {
applyColor(node);
});
}
//if the theme contains text styles
//iterate through all nodes to find text styles that match
if (textStyles) {
nodes.forEach(node => {
applyText(node);
});
}
//if the theme contains effect styles
//iterate through all nodes to find effect styles that match
if (effectStyles) {
nodes.forEach(node => {
applyEffect(node);
});
}
} else {
figma.notify('There is nothing to apply styles to');
}
}
// this function will loop through every node and apply a matching color style if found
// it will ignore any layer without a fill, background, or stroke style applied
function applyColor(node) {
//iterate through children if the node has them
if (node.children) {
node.children.forEach(child => {
applyColor(child);
})
}
//handle background fills
if (node.type === 'COMPONENT'||'INSTANCE'||'FRAME'||'GROUP') {
if (node.backgroundStyleId) {
(async function() {
let style = figma.getStyleById(node.backgroundStyleId) as PaintStyle;
if (style.key) {
let newStyleKey = findMatchInSelectedTheme(style.key);
if (newStyleKey) {
let newStyle = await figma.importStyleByKeyAsync(newStyleKey) as PaintStyle;
if (newStyle) {
node.backgroundStyleId = newStyle.id;
}
}
}
})()
}
}
//handle fills + strokes
if (node.type === 'RECTANGLE'||'POLYGON'||'ELLIPSE'||'STAR'||'TEXT'||'VECTOR'||'BOOLEAN_OPERATION'||'LINE') {
//fills
if (node.fillStyleId) {
(async function() {
let style = figma.getStyleById(node.fillStyleId) as PaintStyle;
if (style.key) {
let newStyleKey = findMatchInSelectedTheme(style.key);
if (newStyleKey) {
let newStyle = await figma.importStyleByKeyAsync(newStyleKey) as PaintStyle;
if (newStyle) {
node.fillStyleId = newStyle.id;
}
}
}
})()
}
//strokes
if (node.strokeStyleId) {
(async function() {
let style = figma.getStyleById(node.strokeStyleId) as PaintStyle;
if (style.key) {
let newStyleKey = findMatchInSelectedTheme(style.key);
if (newStyleKey) {
let newStyle = await figma.importStyleByKeyAsync(newStyleKey) as PaintStyle;
if (newStyle) {
node.strokeStyleId = newStyle.id;
}
}
}
})()
}
}
}
//apply text styles
function applyText(node) {
//iterate through children if the node has them
if (node.children) {
node.children.forEach(child => {
applyText(child);
})
}
// apply text styles
if (node.type === 'TEXT') {
if (node.textStyleId) {
if (typeof node.textStyleId !== 'symbol') {
(async function() {
let style = figma.getStyleById(node.textStyleId) as TextStyle;
if (style.key) {
let newStyleKey = findMatchInSelectedTheme(style.key);
if (newStyleKey) {
let newStyle = await figma.importStyleByKeyAsync(newStyleKey) as TextStyle;
let fontFamily = newStyle.fontName.family;
let fontStyle = newStyle.fontName.style;
await figma.loadFontAsync({
'family': fontFamily,
'style': fontStyle
});
if (newStyle) {
node.textStyleId = newStyle.id;
}
}
}
})()
} else {
figma.notify('Note: Themer currently skips text objects with multiple text styles applied.')
}
}
}
}
//apply effect styles
function applyEffect(node) {
//iterate through children if the node has them
if (node.children) {
node.children.forEach(child => {
applyEffect(child);
})
}
//apply effects
if (node.type === 'COMPONENT'||'INSTANCE'||'FRAME'||'GROUP'||'RECTANGLE'||'POLYGON'||'ELLIPSE'||'STAR'||'TEXT'||'VECTOR'||'BOOLEAN_OPERATION'||'LINE') {
if (node.effectStyleId) {
(async function() {
let style = figma.getStyleById(node.effectStyleId) as EffectStyle;
if (style.key) {
let newStyleKey = findMatchInSelectedTheme(style.key);
if (newStyleKey) {
let newStyle = await figma.importStyleByKeyAsync(newStyleKey);
if (newStyle) {
node.effectStyleId = newStyle.id;
}
}
}
})()
}
}
}
// HELPER FUNCTIONS
//find matching styles based
function findMatchInSelectedTheme(styleKey) {
// this gets item in the array which matches the current style applied
let currentStyle = jsonBinData.find(style => style.key === styleKey);
// if we find a matching style execute this
if (currentStyle) {
//this gets the name of the current style
//we need the name of the current style so we can search the jsonbin array
//for matches with the selected theme
let name = currentStyle.name;
let matchedStyle = jsonBinData.find(style => style.name === name && style.theme === selectedTheme);
if (matchedStyle) {
//if we find a match in the selected theme, we will return the style key
// so that we can import the style into the doc
return matchedStyle.key;
}
}
}
// populate latest data from API
function updatedDataFromAPI(data) {
clearStyleData();
//this passes the data sent from API -> UI -> jsonBinData var
jsonBinData = JSON.parse(data);
// here we want to see if there is at least one existing theme
// if there is, we will append subsequent themes to the data
// if its the first theme, we want to overwrite the same content
// that was required to to create an empty bin
console.log(jsonBinData);
if (jsonBinData[0].theme === undefined) {
existingThemeCount = 0;
}
}
// update credentials
function updateCredentials(secret, url) {
(async () => {
try {
await figma.clientStorage.setAsync('apiSecret', secret);
await figma.clientStorage.setAsync('apiURL', url);
} catch (err) {
figma.notify('There was an issue saving your credentials. Please try again.')
}
})();
}
//remove styles with duplicate keys from themes
function removeDuplicatesBy(keyFn, array) {
var mySet = new Set();
return array.filter(function(x) {
var key = keyFn(x), isNew = !mySet.has(key);
if (isNew) mySet.add(key);
return isNew;
});
}