-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcode.js
59 lines (59 loc) · 1.89 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
figma.showUI(__html__, { width: 400, height: 260 });
figma.ui.onmessage = msg => {
if (msg.type === "populateShow") {
const layerMap = msg.data;
handleText(layerMap, figma.currentPage.selection[0]);
}
else if (msg.type === "populateImage") {
const { imageBytes, key } = msg.data;
handleImage(imageBytes, key, figma.currentPage.selection[0]);
}
else if (msg.type === "cancel") {
figma.closePlugin();
}
};
const valueForCaseInsensitiveKey = (object, caseInsensitiveKey) => {
return object[Object.keys(object)
.find(k => k.toLowerCase() === caseInsensitiveKey.toLowerCase())];
};
const handleText = (layerMap, node) => {
// if node has children, iterate and call this method again
// otherwise see if it's a text field
if ("children" in node) {
for (const child of node.children) {
handleText(layerMap, child);
}
}
else {
// check if node is text
if ("characters" in node) {
// match name to layerMap
const value = valueForCaseInsensitiveKey(layerMap, node.name);
if (value) {
const fontName = node.fontName;
figma.loadFontAsync(fontName).then(() => {
node.characters = value;
});
}
}
}
};
const handleImage = (imageBytes, key, node) => {
if ("children" in node) {
for (const child of node.children) {
handleImage(imageBytes, key, child);
}
}
else {
if ("fills" in node && node.name.toLowerCase() === key.toLowerCase()) {
const imageRectangleNode = node;
const image = figma.createImage(imageBytes);
imageRectangleNode.fills = [{
type: 'IMAGE',
scaleMode: 'FILL',
imageHash: image.hash
}
];
}
}
};