-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcode.ts
84 lines (77 loc) · 2.53 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
figma.showUI(__html__, { width: 240, height: 230 });
figma.on('selectionchange', update);
update();
function update(): void {
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' && (<GeometryMixin> 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;
// Text
if (msg.type === 'text') {
const selectedTextNodes = selection.map(item => (<TextNode> 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];
});
});
}
// Image
if (msg.type === 'image') {
let images = msg.data;
selection.forEach((node, index) => {
const paint: ImagePaint = {
type: 'IMAGE',
scaleMode: 'FILL',
imageHash: figma.createImage(images[index]).hash
};
(<GeometryMixin> node).fills = [paint];
});
}
// Error
if (msg.type === 'error') {
figma.notify(msg.data);
}
};
function getFontNamesFromLayers(layers: TextNode []): FontName [] {
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> fontName).family + ' ' + (<FontName> fontName).style;
if (_temp.indexOf(fontNameString) === -1) {
fontNames.push(fontName);
_temp.push(fontNameString);
}
}
});
return fontNames;
}