Repository navigation
Expand file tree
/
Copy pathcode.js
More file actions
452 lines (452 loc) · 16.7 KB
/
Copy pathcode.js
File metadata and controls
452 lines (452 loc) · 16.7 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
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
"use strict";
/**
* HTML → Figma — main thread
*
* The UI renders the HTML in a real browser and sends a tree of boxes, text
* runs, paints and SVG markup measured from that render (page coordinates).
* This side only rebuilds it: nested Frames with parent-relative positions,
* rich Text, native gradients/images/vectors.
*/
figma.showUI(__html__, { width: 360, height: 600, themeColors: true });
figma.ui.onmessage = async (msg) => {
if (msg.type === 'load-settings') {
figma.ui.postMessage({ type: 'settings', settings: await figma.clientStorage.getAsync('settings') });
return;
}
if (msg.type === 'save-settings') {
await figma.clientStorage.setAsync('settings', msg.settings);
return;
}
if (msg.type !== 'convert' || !msg.tree)
return;
try {
const [images, fonts] = await Promise.all([loadImages(msg.tree, msg.images || {}), loadFonts(msg.tree)]);
const ctx = { images, font: fonts.get };
let root = build(msg.tree, null, ctx);
const size = msg.viewportHeight ? `${msg.viewportWidth}×${msg.viewportHeight}px` : `${msg.viewportWidth}px`;
const suffix = msg.viewportWidth ? ` · ${size}` : '';
root.name = (msg.sourceName || 'HTML Import') + suffix;
const center = figma.viewport.center;
root.x = Math.round(center.x - root.width / 2);
root.y = Math.round(center.y - root.height / 2);
figma.currentPage.appendChild(root);
if (msg.asComponent) {
root = figma.createComponentFromNode(root);
root.name = (msg.sourceName || 'HTML Component') + suffix;
}
const styles = await linkColorStyles(root);
figma.currentPage.selection = [root];
figma.viewport.scrollAndZoomIntoView([root]);
figma.ui.postMessage({ type: 'done', count: countNodes(root), styles, missingFonts: fonts.missing });
}
catch (err) {
figma.ui.postMessage({ type: 'error', message: err instanceof Error ? err.message : String(err) });
}
};
// ---------------------------------------------------------------------------
// Node building
// ---------------------------------------------------------------------------
function build(n, parent, ctx) {
const relX = parent ? n.x - parent.x : 0;
const relY = parent ? n.y - parent.y : 0;
let node;
if (n.type === 'text') {
const t = buildText(n, ctx);
const slack = t.textAutoResize === 'WIDTH_AND_HEIGHT' ? n.w - t.width : 0; // browser − Figma width
const anchor = n.anchor || n.align;
t.x = relX + (anchor === 'CENTER' ? slack / 2 : anchor === 'RIGHT' ? slack : 0);
t.y = relY;
node = t;
}
else if (n.type === 'svg') {
node = buildSvg(n);
node.x = relX;
node.y = relY;
}
else {
const kids = n.children || [];
const box = kids.length || !parent ? figma.createFrame() : figma.createRectangle();
if (n.name)
box.name = n.name;
box.resize(Math.max(n.w, 0.01), Math.max(n.h, 0.01));
box.x = relX;
box.y = relY;
box.fills = paints(n.fills, ctx);
applyStroke(box, n);
applyRadius(box, n.radius);
if (box.type === 'FRAME') {
box.clipsContent = !!n.clip;
for (const child of kids)
box.appendChild(build(child, n, ctx));
}
node = box;
}
if (n.effects && n.effects.length && 'effects' in node)
setEffects(node, n.effects);
if (n.opacity !== undefined && n.opacity < 1)
node.opacity = Math.max(0, n.opacity);
if (n.blend)
node.blendMode = n.blend;
if (n.transform)
applyTransform(node, n, relX, relY);
return node;
}
function buildText(n, ctx) {
const t = figma.createText();
const runs = n.runs || [];
t.fontName = ctx.font(runs[0]);
t.characters = runs.map((r) => r.text).join('');
let i = 0;
for (const r of runs) {
const end = i + r.text.length;
if (end > i) {
t.setRangeFontName(i, end, ctx.font(r));
t.setRangeFontSize(i, end, Math.max(r.size, 1));
t.setRangeLineHeight(i, end, { unit: 'PIXELS', value: Math.max(r.lineHeight, 0) });
if (r.letterSpacing)
t.setRangeLetterSpacing(i, end, { unit: 'PIXELS', value: r.letterSpacing });
t.setRangeFills(i, end, r.fills ? paints(r.fills, ctx) : [solid(r.color)]);
if (r.decoration)
t.setRangeTextDecoration(i, end, r.decoration);
if (r.textCase)
t.setRangeTextCase(i, end, r.textCase);
if (r.href) {
try {
t.setRangeHyperlink(i, end, { type: 'URL', value: r.href });
}
catch (e) {
// not a URL Figma accepts; keep the text
}
}
}
i = end;
}
t.textAlignHorizontal = n.align || 'LEFT';
if (n.autoWidth) {
t.textAutoResize = 'WIDTH_AND_HEIGHT';
}
else {
t.resize(Math.max(n.w, 1), Math.max(n.h, 1));
t.textAutoResize = 'HEIGHT';
const line = Math.min(...runs.map((r) => r.lineHeight)) || 1;
if (n.breaks && n.breaks.length && n.align !== 'JUSTIFIED' && Math.abs(t.height - n.h) > line / 2) {
// Figma's copy of the font wraps differently: keep the browser's lines (soft breaks).
for (const at of n.breaks.slice().sort((a, b) => b - a)) {
let pos = Math.min(at, t.characters.length);
if (t.characters[pos - 1] === ' ') {
t.deleteCharacters(pos - 1, pos); // the space the browser wrapped at
pos--;
}
t.insertCharacters(pos, '\u2028', pos > 0 ? 'BEFORE' : 'AFTER');
}
t.textAutoResize = 'WIDTH_AND_HEIGHT';
}
}
if (n.maxLines) {
t.textTruncation = 'ENDING';
t.maxLines = n.maxLines;
}
return t;
}
function buildSvg(n) {
let f;
try {
f = figma.createNodeFromSvg(n.svg || '');
}
catch (e) {
f = figma.createFrame();
f.fills = [];
f.name = 'svg (could not import)';
}
if (n.name)
f.name = n.name;
f.resize(Math.max(n.w, 0.01), Math.max(n.h, 0.01));
f.clipsContent = !!n.clip;
return f;
}
/** CSS transform (rotation + uniform scale) around transform-origin. */
function applyTransform(node, n, relX, relY) {
const [a, b, c, d, e, f] = n.transform.m;
const s = Math.hypot(a, b);
if (Math.abs(s - 1) > 0.001 && 'rescale' in node)
node.rescale(s);
const ra = a / s, rb = b / s, rc = c / s, rd = d / s;
const { ox, oy } = n.transform;
node.relativeTransform = [
[ra, rc, relX + ox - s * (ra * ox + rc * oy) + e],
[rb, rd, relY + oy - s * (rb * ox + rd * oy) + f],
];
}
// ---------------------------------------------------------------------------
// Paints / strokes / effects
// ---------------------------------------------------------------------------
function solid(c) {
return { type: 'SOLID', color: { r: c.r, g: c.g, b: c.b }, opacity: c.a };
}
function paints(specs, ctx) {
const out = [];
for (const p of specs || []) {
if (p.type === 'SOLID')
out.push(solid(p.color));
else if (p.type === 'IMAGE') {
const hash = ctx.images.get(p.imageRef || p.url || '');
if (hash)
out.push({ type: 'IMAGE', scaleMode: p.scaleMode, imageHash: hash });
}
else
out.push(p);
}
return out;
}
function applyStroke(node, n) {
const s = n.stroke;
if (!s)
return;
node.strokes = [solid(s.color)];
node.strokeAlign = 'INSIDE';
if (s.t === s.r && s.r === s.b && s.b === s.l)
node.strokeWeight = s.t;
else {
node.strokeTopWeight = s.t;
node.strokeRightWeight = s.r;
node.strokeBottomWeight = s.b;
node.strokeLeftWeight = s.l;
}
if (s.dash)
node.dashPattern = s.dash;
}
function applyRadius(node, r) {
if (!r)
return;
if (r[0] === r[1] && r[1] === r[2] && r[2] === r[3])
node.cornerRadius = r[0];
else {
node.topLeftRadius = r[0];
node.topRightRadius = r[1];
node.bottomRightRadius = r[2];
node.bottomLeftRadius = r[3];
}
}
function setEffects(node, effects) {
try {
node.effects = effects;
}
catch (e) {
// Figma only accepts shadow spread on filled, clipping frames; drop it elsewhere.
node.effects = effects.map((fx) => fx.type === 'DROP_SHADOW' || fx.type === 'INNER_SHADOW' ? Object.assign({}, fx, { spread: 0 }) : fx);
}
}
// ---------------------------------------------------------------------------
// Images / fonts (resolved once, up front)
// ---------------------------------------------------------------------------
function walk(n, fn) {
fn(n);
for (const c of n.children || [])
walk(c, fn);
}
async function loadImages(tree, b64) {
const hashes = new Map();
for (const id of Object.keys(b64)) {
try {
hashes.set(id, figma.createImage(figma.base64Decode(b64[id])).hash);
}
catch (e) {
console.warn('Failed to create image', id, e);
}
}
// Images the UI couldn't read (no CORS): let Figma fetch them itself.
const urls = new Set();
walk(tree, (n) => {
const all = (n.fills || []).concat(...(n.runs || []).map((r) => r.fills || []));
for (const p of all)
if (p.type === 'IMAGE' && p.url)
urls.add(p.url);
});
await Promise.all(Array.from(urls).map((url) => figma
.createImageAsync(url)
.then((img) => hashes.set(url, img.hash))
.catch(() => console.warn('Could not fetch image', url))));
return hashes;
}
const INTER = { family: 'Inter', style: 'Regular' };
let fontIndex = null;
// Generic / system families → what to look for in Figma, in order.
const SYSTEM_SANS = ['SF Pro', 'SF Pro Text', 'Inter'];
const FONT_ALIASES = {
'system-ui': SYSTEM_SANS,
'-apple-system': SYSTEM_SANS,
blinkmacsystemfont: SYSTEM_SANS,
'ui-sans-serif': SYSTEM_SANS,
'sans-serif': ['Helvetica', 'Arial', 'Inter'],
serif: ['Times New Roman', 'Times', 'Georgia', 'Noto Serif'],
'ui-serif': ['New York', 'Times New Roman', 'Georgia'],
monospace: ['Menlo', 'Courier New', 'Roboto Mono'],
'ui-monospace': ['SF Mono', 'Menlo', 'Roboto Mono'],
sfmono: ['SF Mono', 'Menlo', 'Roboto Mono'],
'sfmono-regular': ['SF Mono', 'Menlo', 'Roboto Mono'],
cursive: ['Comic Sans MS'],
};
const GENERIC = /^(serif|sans-serif|monospace|cursive|fantasy|system-ui|ui-\w+|-apple-system|blinkmacsystemfont|emoji|math)$/i;
const EMOJI = /emoji|symbol/i;
async function loadFonts(tree) {
if (!fontIndex) {
fontIndex = new Map();
for (const f of await figma.listAvailableFontsAsync()) {
const key = f.fontName.family.toLowerCase();
const list = fontIndex.get(key);
if (list)
list.push(f.fontName);
else
fontIndex.set(key, [f.fontName]);
}
}
const index = fontIndex;
const runKey = (r) => r.families.join(',') + '|' + r.weight + '|' + r.italic;
const chosen = new Map();
const missing = new Set();
walk(tree, (n) => {
for (const r of n.runs || []) {
const key = runKey(r);
if (chosen.has(key))
continue;
let styles;
for (const fam of r.families) {
if (EMOJI.test(fam))
continue;
for (const cand of FONT_ALIASES[fam.toLowerCase()] || [fam]) {
styles = index.get(cand.toLowerCase());
if (styles)
break;
}
if (styles)
break;
if (!GENERIC.test(fam))
missing.add(fam);
}
chosen.set(key, pickStyle(styles || index.get('inter') || [INTER], r.weight, r.italic));
}
});
const failed = new Set();
const unique = new Map();
chosen.forEach((f) => unique.set(f.family + '::' + f.style, f));
unique.set('Inter::Regular', INTER);
await Promise.all(Array.from(unique.entries()).map(([k, f]) => figma.loadFontAsync(f).catch(() => failed.add(k))));
return {
get: (r) => {
const f = r && chosen.get(runKey(r));
return f && !failed.has(f.family + '::' + f.style) ? f : INTER;
},
missing: Array.from(missing),
};
}
function styleWeight(style) {
const s = style.toLowerCase().replace(/[\s_-]/g, '');
if (/thin|hairline/.test(s))
return 100;
if (/(extra|ultra)light/.test(s))
return 200;
if (/light/.test(s))
return 300;
if (/medium/.test(s))
return 500;
if (/(semi|demi)bold/.test(s))
return 600;
if (/(extra|ultra)bold/.test(s))
return 800;
if (/black|heavy/.test(s))
return 900;
if (/bold/.test(s))
return 700;
return 400;
}
/** Closest weight, matching italic; plain styles beat Condensed/Display/etc. */
function pickStyle(styles, weight, italic) {
let best = styles[0];
let bestScore = Infinity;
for (const f of styles) {
const isItalic = /italic|oblique/i.test(f.style);
const extra = f.style
.replace(/italic|oblique|regular|normal|book|roman|thin|hairline|extra|ultra|semi|demi|light|medium|bold|black|heavy/gi, '')
.trim();
const score = Math.abs(styleWeight(f.style) - weight) + (isItalic !== italic ? 1000 : 0) + (extra ? 50 : 0);
if (score < bestScore) {
best = f;
bestScore = score;
}
}
return best;
}
/**
* Turns the import's most-used solid colors into `HTML/` paint styles and links every
* layer (fill, stroke or text run) with that color to its style, so editing one style
* recolors the whole import.
*/
async function linkColorStyles(root) {
const uses = new Map();
const note = (p, link) => {
// Gradients, images and stacked paints keep their own fills: a style would replace all of them.
if (p === figma.mixed || p.length !== 1)
return;
const s = p[0];
const a = s.opacity === undefined ? 1 : s.opacity;
if (s.type !== 'SOLID' || s.visible === false || (s.blendMode || 'NORMAL') !== 'NORMAL' || a < 0.05)
return;
const key = colorKey(s.color, a);
const use = uses.get(key) || { color: s.color, opacity: a, links: [] };
use.links.push(link);
uses.set(key, use);
};
const nodes = 'findAll' in root ? [root, ...root.findAll()] : [root];
for (const n of nodes) {
if (n.type === 'TEXT') {
for (const seg of n.getStyledTextSegments(['fills']))
note(seg.fills, (id) => n.setRangeFillStyleIdAsync(seg.start, seg.end, id));
}
else if ('fills' in n)
note(n.fills, (id) => n.setFillStyleIdAsync(id));
if ('strokes' in n)
note(n.strokes, (id) => n.setStrokeStyleIdAsync(id));
}
// Reuse an earlier import's style only while it still holds the exact color, so a
// style the user has since recolored never changes this import.
const existing = new Map();
for (const s of await figma.getLocalPaintStylesAsync()) {
const p = s.paints[0];
if (s.name.startsWith('HTML/') && s.paints.length === 1 && p.type === 'SOLID')
existing.set(colorKey(p.color, p.opacity === undefined ? 1 : p.opacity), s.id);
}
// Most-used first, capped so imports don't flood the file with near-duplicate styles.
const top = Array.from(uses.entries())
.sort((x, y) => y[1].links.length - x[1].links.length)
.slice(0, 40);
const pending = [];
for (const [key, use] of top) {
let id = existing.get(key);
if (!id) {
const style = figma.createPaintStyle();
style.name = 'HTML/' + rgbToHex(use.color) + (use.opacity < 0.999 ? ` @${Math.round(use.opacity * 100)}%` : '');
style.paints = [{ type: 'SOLID', color: use.color, opacity: use.opacity }];
id = style.id;
}
for (const link of use.links)
pending.push(link(id));
}
await Promise.all(pending);
return top.length;
}
function colorKey(c, a) {
return [Math.round(c.r * 255), Math.round(c.g * 255), Math.round(c.b * 255), Math.round(a * 100)].join(',');
}
function rgbToHex(c) {
const h = (n) => Math.round(n * 255)
.toString(16)
.padStart(2, '0');
return ('#' + h(c.r) + h(c.g) + h(c.b)).toUpperCase();
}
function countNodes(node) {
let n = 1;
if ('children' in node)
for (const child of node.children)
n += countNodes(child);
return n;
}