forked from figma/plugin-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
code.js
82 lines (77 loc) · 2.42 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
76
77
78
79
80
81
82
const PLUGIN_DATA_KEY = "snippets";
if (figma.mode === "codegen") {
figma.codegen.on("preferenceschange", (event) => {
if (event.propertyName === "editor") {
figma.showUI(__html__, { width: 400, height: 450 });
}
});
figma.ui.on("message", (event) => {
if (event.type === "INITIALIZE") {
handleCurrentSelection();
} else if (event.type === "SAVE") {
figma.currentPage.selection[0].setPluginData(PLUGIN_DATA_KEY, event.data);
} else {
console.log("UNKNOWN EVENT", event);
}
});
figma.on("selectionchange", () => {
handleCurrentSelection();
});
figma.codegen.on("generate", async () => {
handleCurrentSelection();
const pluginDataArray = findPluginDataArrayForSelection();
const snippets = [];
pluginDataArray.forEach((pluginData) =>
JSON.parse(pluginData).forEach((a) => snippets.push(a))
);
if (!snippets.length) {
snippets.push({
title: "Snippets",
code: "No snippets found. Add snippets with the Snippet Editor in the Plugin's Inspect settings!",
language: "PLAINTEXT",
});
}
return snippets;
});
}
function findPluginDataArrayForSelection() {
const data = [];
function pluginDataForNode(node) {
const pluginData = node.getPluginData(PLUGIN_DATA_KEY);
// skipping duplicates. why?
// component instances have same pluginData as mainComponent, unless they have override pluginData.
if (pluginData && data.indexOf(pluginData) === -1) {
data.push(pluginData);
}
}
const currentNode = figma.currentPage.selection[0];
pluginDataForNode(currentNode);
if (currentNode.type === "INSTANCE") {
pluginDataForNode(currentNode.mainComponent);
if (currentNode.mainComponent.parent.type === "COMPONENT_SET") {
pluginDataForNode(currentNode.mainComponent.parent);
}
} else if (currentNode.type === "COMPONENT") {
if (currentNode.parent.type === "COMPONENT_SET") {
pluginDataForNode(currentNode.parent);
}
}
return data;
}
function handleCurrentSelection() {
const node = figma.currentPage.selection[0];
try {
const nodePluginData = node ? node.getPluginData(PLUGIN_DATA_KEY) : null;
const nodeId = node ? node.id : null;
const nodeType = node ? node.type : null;
figma.ui.postMessage({
type: "SELECTION",
nodeId,
nodeType,
nodePluginData,
});
return nodePluginData;
} catch (e) {
// no ui open. ignore this.
}
}