-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcode.ts
More file actions
227 lines (197 loc) Β· 6.81 KB
/
code.ts
File metadata and controls
227 lines (197 loc) Β· 6.81 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
// This plugin will open a window to prompt the user to enter a number, and
// it will then create that many rectangles on the screen.
// This file holds the main code for plugins. Code in this file has access to
// the *figma document* via the figma global object.
// You can access browser APIs in the <script> tag inside "ui.html" which has a
// full browser environment (See https://www.figma.com/plugin-docs/how-plugins-run).
// Uncomment the following to use this for local dev mode.
// figma.showUI(__html__, {
// width: 480,
// height: 800,
// });
// IMPORTANT: Update the URL to your own hosted service, and then add the domain to the allowlist on corsfix.
figma.showUI(
`<script>window.location.href="https://<YOUR_REPO_NAME>.github.io/figma-plugin?${Math.random()}";</script>`,
{
width: 480,
height: 800,
}
);
// Notify UI of initial selection
figma.ui.postMessage({
type: "selection-changed",
hasValidFrame:
figma.currentPage.selection.length === 1 &&
figma.currentPage.selection[0].type === "FRAME",
});
async function getBase64Images(selection: readonly SceneNode[]) {
const base64Images = [];
for (const node of selection) {
// Convert frame to base64
const image = await node.exportAsync({
format: "JPG",
constraint: { type: "SCALE", value: 1 },
});
const base64 = figma.base64Encode(image);
base64Images.push(`data:image/jpeg;base64,${base64}`);
}
return base64Images;
}
// Listen for selection changes
figma.on("selectionchange", async () => {
const selection = figma.currentPage.selection;
if (selection.length === 0) {
figma.ui.postMessage({
type: "selection-changed",
hasValidFrame: false,
error: "Please select a frame",
});
return;
}
if (selection.length > 3) {
figma.ui.postMessage({
type: "selection-changed",
hasValidFrame: false,
error: "Please select not more than 3 frames",
});
return;
}
if (selection.find((node) => node.type !== "FRAME")) {
figma.ui.postMessage({
type: "selection-changed",
hasValidFrame: false,
error: "Please select only frames",
});
return;
}
const base64Images = await getBase64Images(selection);
figma.ui.postMessage({
type: "selection-changed",
imageData: base64Images,
hasValidFrame: true,
});
});
// Register drop event handler
figma.on("drop", ((event: DropEvent): boolean => {
const { items } = event;
if (items.length > 0) {
// Look for image data in the dropped items
const imageItem = items.find((item) => item.type === "text/uri-list");
if (!imageItem) return false;
// Create image from the URL
fetch(imageItem.data)
.then((response) => response.arrayBuffer())
.then((imageData) => {
const image = figma.createImage(new Uint8Array(imageData));
// Create a rectangle to hold the image
const rect = figma.createRectangle();
rect.fills = [
{
type: "IMAGE",
scaleMode: "FILL",
imageHash: image.hash,
},
];
// Set size based on image dimensions
image.getSizeAsync().then(({ width, height }) => {
rect.resize(width, height);
// Position the rectangle at the drop coordinates
rect.x = event.x;
rect.y = event.y;
// Select the new rectangle
figma.currentPage.selection = [rect];
figma.notify("Image added to canvas! π");
});
})
.catch((error) => {
figma.notify("Failed to create image: " + error.message, {
error: true,
});
});
return true; // Return true to indicate we handled the drop
}
return false;
}) as (event: DropEvent) => boolean);
// Handle messages from UI
figma.ui.onmessage = async (msg) => {
if (msg.type === "save-api-key") {
await figma.clientStorage.setAsync("runway-api-key", msg.apiKey);
figma.ui.postMessage({ type: "api-key-saved" });
} else if (msg.type === "get-api-key") {
const apiKey = await figma.clientStorage.getAsync("runway-api-key");
figma.ui.postMessage({ type: "api-key-loaded", apiKey });
} else if (msg.type === "create-image") {
try {
// Create image from the URL
const response = await fetch(msg.imageUrl);
const imageData = await response.arrayBuffer();
const image = figma.createImage(new Uint8Array(imageData));
// Create a rectangle to hold the image
const rect = figma.createRectangle();
rect.fills = [
{
type: "IMAGE",
scaleMode: "FILL",
imageHash: image.hash,
},
];
// Set size based on image dimensions
const { width, height } = await image.getSizeAsync();
rect.resize(width, height);
// Position the rectangle at the center of the viewport
const viewport = figma.viewport.center;
rect.x = viewport.x - width / 2;
rect.y = viewport.y - height / 2;
// Select the new rectangle
figma.currentPage.selection = [rect];
figma.viewport.scrollAndZoomIntoView([rect]);
figma.notify("Image added to canvas! π");
} catch (error: Error | unknown) {
const errorMessage =
error instanceof Error ? error.message : String(error);
figma.notify("Failed to create image: " + errorMessage, { error: true });
}
} else if (msg.type === "generate-video") {
const selection = figma.currentPage.selection;
if (selection.length !== 1) {
figma.ui.postMessage({
type: "error",
error: "Please select exactly one frame",
});
return;
}
const node = selection[0];
if (node.type !== "FRAME") {
figma.ui.postMessage({
type: "error",
error: "Please select a frame",
});
return;
}
const isLandscape = node.width > node.height;
const isSquare = node.width === node.height;
// Convert frame to base64
const image = await node.exportAsync({
format: "JPG",
constraint: { type: "SCALE", value: 1 },
});
const base64 = figma.base64Encode(image);
figma.ui.postMessage({
type: "start-video-generation",
imageData: `data:image/jpeg;base64,${base64}`,
aspectRatio: isSquare ? "960:960" : isLandscape ? "1280:720" : "720:1280",
});
} else if (msg.type === "video-ready") {
figma.notify("Video generated! π");
} else if (msg.type === "generate-image") {
const selection = figma.currentPage.selection;
const base64Images = await getBase64Images(selection);
// check aspect ratio of base64Images and make sure they are between 0.5 and 2. If not, resize them to the closest aspect ratio proportional to the original size
figma.ui.postMessage({
type: "start-image-generation",
imageData: base64Images,
});
} else if (msg.type === "image-ready") {
figma.notify("Image generated! π");
}
};