-
Notifications
You must be signed in to change notification settings - Fork 0
/
code.ts
91 lines (75 loc) · 2.39 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
figma.showUI(__html__, { themeColors: true, width: 435, height: 500 });
let lastAppendedIcon: SceneNode | null = null; // Track the last appended icon on the page
// In plugin code
figma.ui.onmessage = async (msg) => {
if (msg.type === "create-icon") {
const svg = msg.svg;
const name = msg.name;
const node = await figma.createNodeFromSvg(svg);
node.name = name;
node.constrainProportions = true;
if (figma.editorType === "figjam") {
node.resize(64, 64);
}
const selection = figma.currentPage.selection;
if (
selection.find((node) => node === lastAppendedIcon) &&
lastAppendedIcon
) {
appendToParentOrPage(node, lastAppendedIcon);
} else if (selection.length > 0) {
const selectedNode = selection[selection.length - 1];
appendToParentOrPage(node, selectedNode);
} else {
appendToPage(node);
}
figma.currentPage.selection = [node];
}
};
function appendToPage(node: SceneNode) {
figma.currentPage.appendChild(node);
positionNodeToTheRight(node, null); // Pass null as the reference node
}
function appendToParentOrPage(node: SceneNode, referenceNode: SceneNode) {
const parent =
referenceNode.parent && referenceNode.parent.type === "FRAME"
? referenceNode.parent
: figma.currentPage;
parent.appendChild(node);
positionNodeToTheRight(node, referenceNode);
}
function positionNodeToTheRight(
node: SceneNode,
referenceNode: SceneNode | null,
) {
if (referenceNode && "x" in referenceNode) {
node.x = referenceNode.x + referenceNode.width + 10; // 10 is the gap between icons
node.y = referenceNode.y;
} else {
node.x = Math.round(figma.viewport.center.x);
node.y = Math.round(figma.viewport.center.y);
}
lastAppendedIcon = node;
}
figma.on("selectionchange", () => {
const currentSelection = figma.currentPage.selection;
if (
lastAppendedIcon &&
!currentSelection.some((node) => node === lastAppendedIcon)
) {
lastAppendedIcon = null;
}
});
// In plugin code
figma.on("drop", (event: DropEvent) => {
const { items, dropMetadata } = event;
if (items.length > 0 && items[0].type === "image/svg+xml") {
const data = items[0].data;
const newNode = figma.createNodeFromSvg(data);
newNode.x = event.absoluteX;
newNode.y = event.absoluteY;
newNode.name = dropMetadata.name;
figma.currentPage.selection = [newNode];
}
return false;
});