-
Notifications
You must be signed in to change notification settings - Fork 3
/
code.js
75 lines (75 loc) · 2.38 KB
/
code.js
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
figma.showUI(__html__, { width: 240, height: 230 });
figma.on('selectionchange', update);
update();
function update() {
let selection = figma.currentPage.selection;
if (selection.length > 0) {
if (selection.every(layer => layer.type === 'TEXT')) {
figma.ui.postMessage({
type: 'text',
count: selection.length
});
}
else if (selection.every(layer => layer.type !== 'TEXT' && layer.fills !== undefined)) {
figma.ui.postMessage({
type: 'image',
count: selection.length
});
}
else {
figma.ui.postMessage({
type: 'message',
text: 'Only support text and shape layer, but don\'t select both of them.'
});
}
}
else {
figma.ui.postMessage({
type: 'message',
text: 'Select at least 1 text or shape layer.'
});
}
}
figma.ui.onmessage = msg => {
let selection = figma.currentPage.selection;
if (msg.type === 'text') {
const selectedTextNodes = selection.map(item => item);
const fontNames = getFontNamesFromLayers(selectedTextNodes);
const loadFontTasks = fontNames.map(item => figma.loadFontAsync(item));
Promise.all(loadFontTasks).then(() => {
selectedTextNodes.forEach((node, index) => {
node.characters = msg.data[index];
});
});
}
if (msg.type === 'image') {
let images = msg.data;
selection.forEach((node, index) => {
const paint = {
type: 'IMAGE',
scaleMode: 'FILL',
imageHash: figma.createImage(images[index]).hash
};
node.fills = [paint];
});
}
if (msg.type === 'error') {
figma.notify(msg.data);
}
};
function getFontNamesFromLayers(layers) {
let fontNames = [];
let _temp = [];
layers.forEach(function (layer) {
let len = layer.characters.length;
for (let i = 0; i < len; i++) {
let fontName = layer.getRangeFontName(i, i + 1);
let fontNameString = fontName.family + ' ' + fontName.style;
if (_temp.indexOf(fontNameString) === -1) {
fontNames.push(fontName);
_temp.push(fontNameString);
}
}
});
return fontNames;
}