-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcode.js
393 lines (393 loc) · 12.9 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
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
const SPACING = 20;
const requests = {};
const imageCache = {};
// console.log('selection', figma.currentPage.selection)
// console.log(this, figma)
figma.showUI(__html__, {
width: 400,
height: 300,
});
figma.ui.onmessage = (msg) => __awaiter(this, void 0, void 0, function* () {
const { data } = tryParse(msg);
if (msg.type === 'notify') {
return figma.notify(msg.data);
}
if (requests[msg.id]) {
requests[msg.id].resolve(data);
return;
}
if (msg.type === 'request:selection') {
for (var i = 0; i < 10; ++i) {
const selection = getOriginalSelection();
if (selection) {
return responseMessage(msg, [fromSelection(selection)]);
}
yield delay(1000);
}
const selection = getOriginalSelection();
if (selection) {
return responseMessage(msg, [fromSelection(selection)]);
}
return responseMessage(msg, []);
}
if (msg.type === 'request:texts') {
// responseMessage(msg, getTexts([getOriginalSelection()]))
// return
return figma.notify('deprecated');
}
if (msg.type === 'request:saveAirtableLink') {
figma.notify('link saved');
setPluginJSON('airtableLink', data || '');
responseMessage(msg, 'ok');
return;
}
if (msg.type === 'request:saveAirtableData') {
setPluginJSON('airtableData', data || []);
responseMessage(msg, 'ok');
return;
}
if (msg.type === 'request:renderAirtable') {
const { airtableRows, airtableConfig } = data;
const { mapping, images } = airtableConfig;
const limit = airtableConfig.limit || 100;
const spacing = parseInt(airtableConfig.spacing) || 20;
const grid = ['columns', 'grid'].includes(airtableConfig.grid)
? airtableConfig.grid
: 'rows';
const columnCount = airtableConfig.grid === 'grid'
? parseInt(airtableConfig.columns) || 3
: airtableConfig.grid === 'columns'
? 100
: 1;
const rowCount = Math.ceil(limit / columnCount) || 1;
const original = getOriginalSelection();
if (!original) {
responseMessage(msg, 'sync:selection');
console.log('selection', figma.currentPage.selection);
return figma.notify('No frame selected');
}
setPluginJSON('airtableConfig', airtableConfig);
const instance = getFrame(original);
if (!instance) {
responseMessage(msg, 'sync:selection');
console.log('selection', figma.currentPage.selection);
return figma.notify('No frame selected');
}
if (!airtableRows) {
console.warn('no rows', airtableRows);
responseMessage(msg, 'error');
return figma.notify('No rows from Airtable');
}
if (!mapping.find(col => col.airtableField)) {
console.warn('no fields mapped', mapping);
responseMessage(msg, 'error');
return figma.notify('No fields mapped');
}
const textLookup = getArrayMapping(original, mapping);
const imageLookup = getArrayMapping(original, images);
yield loadFonts(mapping);
// console.log('lo', textLookup)
const instanceId = instance.id;
instance.setPluginData('clonedFrom', instanceId);
const parent = instance.parent;
const focus = [];
focus.push(instance);
let y = instance.y;
let x = instance.x;
let height = instance.height;
let width = instance.width;
let first = true;
let i = 0;
for (let r = 0; r < rowCount; r++) {
for (let c = 0; c < columnCount && i < airtableRows.length && i < limit; c++) {
const rowData = airtableRows[i];
const clone = first
? instance
: instance.type === 'COMPONENT'
? fromComponent(instance)
: instance.clone();
first = false;
const subs = clone.findAll(() => true);
// console.log('subs', subs)
subs.forEach((sub, i) => interpolateText(sub, rowData[textLookup[i]]));
subs.forEach((sub, i) => interpolateImage(sub, rowData[imageLookup[i]]));
parent.appendChild(clone);
clone.y = y + (height + spacing) * r;
clone.x = x + (width + spacing) * c;
clone.setPluginData('clonedFrom', instanceId);
// clone.locked = true
focus.push(clone);
i++;
}
}
// TODO: saved
// Update selection
figma.currentPage.selection = focus;
// figma.viewport.scrollAndZoomIntoView(focus)
responseMessage(msg, 'ok');
return;
}
// Make sure to close the plugin when you're done. Otherwise the plugin will
// keep running, which shows the cancel button at the bottom of the screen.
figma.closePlugin();
});
function loadFonts(mapping) {
return Promise.all(mapping.map(node => figma.getNodeById(node.id)).map(loadFont));
}
function loadFont(node) {
return node.type === 'TEXT' && figma.loadFontAsync(node.fontName);
}
function getArrayMapping(instance, mapping) {
return instance
.findAll(() => true)
.map(node => mapping.find(n => n.id === node.id))
.map(f => f && f.airtableField);
}
function interpolateText(node, value) {
if (value) {
const { name } = node;
node.characters = String(value);
if (node.name === node.characters) {
node.name = name;
}
return;
}
// if (node.type === 'TEXT') {
// node.characters = templateHash(node.characters, row)
// }
}
function interpolateImage(node, value) {
return __awaiter(this, void 0, void 0, function* () {
if (value && value[0] && value[0].largeThumbUrl) {
const image = yield downloadImage(value[0].largeThumbUrl);
const paint = JSON.parse(JSON.stringify(node.fills[0]));
paint.imageHash = figma.createImage(new Uint8Array(image)).hash;
node.fills = [paint].concat(node.fills.slice(1));
return;
}
});
}
function downloadImage(url) {
if (!imageCache[url]) {
imageCache[url] = requestMessage('downloadImage', url);
}
return imageCache[url];
}
function templateHash(text, data) {
if (data) {
Object.keys(data).forEach(key => {
text = text.replace('#' + key, data[key]);
});
}
return text;
}
function getOriginalSelection() {
const instance = figma.currentPage.selection[0];
if (!instance) {
return instance;
}
if (instance.type !== 'INSTANCE' &&
instance.type !== 'FRAME' &&
instance.type !== 'COMPONENT') {
return null;
}
const id = instance.getPluginData('clonedFrom');
return (id && figma.getNodeById(id)) || instance;
}
function getFrame(instance) {
if (!instance) {
return console.warn('no selection');
}
// console.log('clonedfrm', instance, instance.getPluginData('clonedFrom'))
// Start from cloned node
// {
// const id = instance.getPluginData('clonedFrom')
// const node = figma.getNodeById(id)
// if (node && id && id !== instance.id) {
// console.log('indirect instance')
// instance = node
// } else if (id && !node) {
// console.log('old clone')
// instance.setPluginData('clonedFrom', null)
// }
// }
// Start from component
if (instance.type === 'COMPONENT') {
// const parent = instance
// instance = instance.createInstance()
// // To the right
// instance.x = parent.x + parent.width + SPACING
// instance.y = parent.y
// figma.currentPage.selection = [instance]
// figma.viewport.scrollAndZoomIntoView(focus)
}
// Start from frame
if (instance.type === 'FRAME') {
// Use frame as is
// const parent = instance
// instance = instance.clone()
// // To the right
// instance.x = parent.x + parent.width + SPACING
// instance.y = parent.y
}
// Start from cloned node
const id = instance.getPluginData('clonedFrom');
const node = figma.getNodeById(id);
if (node && id && id !== instance.id) {
console.log('indirect instance');
instance = node;
}
else if (id && !node) {
console.log('old clone');
instance.setPluginData('clonedFrom', null);
}
if (node) {
const toRemove = [];
const id = instance.id;
traverse(figma.currentPage, node => {
if (node.getPluginData('clonedFrom') === id && node.id !== id) {
toRemove.push(node);
}
});
toRemove.forEach(node => node.remove());
// console.log('toremo', toRemove.length)
}
if (!instance ||
(instance.type !== 'INSTANCE' &&
instance.type !== 'FRAME' &&
instance.type !== 'COMPONENT')) {
return console.warn('no instance');
}
return instance;
}
function fromComponent(parent) {
const instance = parent.createInstance();
// To the right
instance.x = parent.x + parent.width + SPACING;
instance.y = parent.y;
return instance;
}
function getTexts(layer) {
if (!layer)
return [];
const texts = [];
traverse(layer, layer => {
if (layer.type === 'TEXT') {
texts.push({
id: layer.id,
name: layer.name,
characters: layer.characters,
});
}
});
return texts;
}
function getImages(layer) {
if (!layer)
return [];
const images = [];
traverse(layer, layer => {
if (layer.fills && layer.fills[0] && layer.fills[0].type === 'IMAGE') {
images.push({
id: layer.id,
name: layer.name,
imageHash: layer.fills[0].imageHash,
});
}
});
console.log('getImages', images);
return images;
}
function traverse(node, func) {
if (Array.isArray(node)) {
return node.map(n => traverse(n, func));
}
func(node);
if ('children' in node) {
for (const child of node.children) {
traverse(child, func);
}
}
}
function detectConfig() {
// To implement
// Read selection metadata
// post metadata to plugin
}
function requestMessage(type, data) {
// Store all requests in one object and handle in global onmessage
const id = Math.random().toString(36);
return new Promise(resolve => {
console.log('requestmessage', type, data);
requests[id] = { resolve };
figma.ui.postMessage({
id,
type: 'request:' + type,
data: JSON.stringify(data),
});
});
}
// function requestMessage(msg, data) {
// figma.ui.postMessage({
// id: msg.id,
// type: msg.type.replace('request:', 'response:'),
// data: JSON.stringify(data),
// })
// }
function responseMessage(msg, data) {
figma.ui.postMessage({
id: msg.id,
type: msg.type.replace('request:', 'response:'),
data: JSON.stringify(data),
});
}
function fromSelection(node) {
return {
id: node.id,
type: node.type,
airtableLink: getPluginJSON(node, 'airtableLink'),
airtableData: getPluginJSON(node, 'airtableData'),
airtableConfig: getPluginJSON(node, 'airtableConfig'),
texts: getTexts(node),
images: getImages(node),
};
}
function getPluginJSON(node, key) {
const data = node.getPluginData(key);
try {
return JSON.parse(data);
}
catch (e) { }
return data;
}
function setPluginJSON(key, data) {
;
[]
.concat(figma.currentPage.selection, getOriginalSelection())
.filter(Boolean)
.map(node => {
node.setPluginData(key, JSON.stringify(data));
});
}
function tryParse(msg) {
try {
return {
type: msg.type,
data: JSON.parse(msg.data),
};
}
catch (e) { }
return msg || {};
}
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}