openfig-mcp 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -18
- package/bin/openfig-mcp.mjs +71 -71
- package/package.json +1 -1
- package/src/convert.mjs +484 -484
- package/src/html.mjs +110 -110
- package/src/index.mjs +8 -8
- package/src/render.mjs +85 -85
- package/src/server.mjs +246 -246
- package/src/tokens.mjs +157 -157
- package/src/vendor/svg-builder.mjs +1661 -1661
|
@@ -1,1661 +1,1661 @@
|
|
|
1
|
-
// Vendored from openfig-cli 0.6.0 (lib/rasterizer/svg-builder.mjs), MIT License — see LICENSE-openfig-cli.
|
|
2
|
-
// https://github.com/OpenFig-org/openfig-cli
|
|
3
|
-
// Local changes: helper imports inlined; image fills are read from the in-memory archive
|
|
4
|
-
// (deck.readImage) instead of an extracted images directory.
|
|
5
|
-
/**
|
|
6
|
-
* svg-builder.mjs — Convert a Figma node tree to an SVG string.
|
|
7
|
-
*
|
|
8
|
-
* Architecture: dispatcher pattern — each Figma node type maps to a render
|
|
9
|
-
* function. Unknown types emit a magenta placeholder rect so renders never
|
|
10
|
-
* crash. Add handlers incrementally as coverage grows.
|
|
11
|
-
*
|
|
12
|
-
* Parameter naming — two entry points, one shared engine:
|
|
13
|
-
*
|
|
14
|
-
* slideToSvg(deck, slideNode) — Slides entry point (.deck files)
|
|
15
|
-
* "deck" = a parsed .deck file. Expects SLIDE nodes, 1920×1080 viewport.
|
|
16
|
-
*
|
|
17
|
-
* frameToSvg(fig, node) — Design entry point (.fig files)
|
|
18
|
-
* "fig" = a parsed .fig file. Uses the node's own size as viewport.
|
|
19
|
-
*
|
|
20
|
-
* Internal render functions all accept "deck" for historical reasons,
|
|
21
|
-
* but they are format-agnostic — they work on any Figma node tree
|
|
22
|
-
* regardless of whether it came from a .deck or .fig file.
|
|
23
|
-
* Both formats share the same binary codec (canvas.fig inside a ZIP).
|
|
24
|
-
*/
|
|
25
|
-
|
|
26
|
-
import { readFileSync } from 'fs';
|
|
27
|
-
import { join } from 'path';
|
|
28
|
-
import { extractRenderableGradientFill, parseVectorNetworkBlob, resolveGradientGeometry } from 'openfig-core';
|
|
29
|
-
const hashToHex = arr => Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
|
|
30
|
-
import { nodeId as nid } from 'openfig-core';
|
|
31
|
-
|
|
32
|
-
export const SLIDE_W = 1920;
|
|
33
|
-
export const SLIDE_H = 1080;
|
|
34
|
-
|
|
35
|
-
// Per-slide ID counter — reset at the start of each slideToSvg call so IDs are unique within each SVG doc
|
|
36
|
-
let _svgIdSeq = 0;
|
|
37
|
-
|
|
38
|
-
// Depth counter for SYMBOL rendering context. When > 0 we're inside a component
|
|
39
|
-
// tree and frame clipping is suppressed — Figma doesn't enforce child frame clips
|
|
40
|
-
// inside components whose root allows overflow (frameMaskDisabled=true).
|
|
41
|
-
let _symbolDepth = 0;
|
|
42
|
-
|
|
43
|
-
// ── Color helpers ─────────────────────────────────────────────────────────────
|
|
44
|
-
|
|
45
|
-
function cssColor(color, opacity = 1) {
|
|
46
|
-
const r = Math.round((color.r ?? 0) * 255);
|
|
47
|
-
const g = Math.round((color.g ?? 0) * 255);
|
|
48
|
-
const b = Math.round((color.b ?? 0) * 255);
|
|
49
|
-
const a = ((color.a ?? 1) * opacity).toFixed(4);
|
|
50
|
-
return `rgba(${r},${g},${b},${a})`;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
function resolveFill(fillPaints) {
|
|
54
|
-
if (!fillPaints?.length) return null;
|
|
55
|
-
const p = fillPaints.find(p => p.visible !== false && p.type === 'SOLID');
|
|
56
|
-
if (!p) return null;
|
|
57
|
-
return cssColor(p.color ?? {}, p.opacity ?? 1);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/** Generate an SVG gradient definition for a GRADIENT_LINEAR or GRADIENT_RADIAL paint.
|
|
61
|
-
* w, h = element dimensions in pixels (needed for userSpaceOnUse coordinates).
|
|
62
|
-
* Returns { defs: string, fill: string } where fill is 'url(#grad-N)'. */
|
|
63
|
-
function resolveGradientSvg(paint, w, h) {
|
|
64
|
-
const gradient = extractRenderableGradientFill([paint]);
|
|
65
|
-
if (!gradient) return null;
|
|
66
|
-
const geometry = resolveGradientGeometry(gradient, w, h);
|
|
67
|
-
if (!geometry) return null;
|
|
68
|
-
|
|
69
|
-
const id = `grad-${++_svgIdSeq}`;
|
|
70
|
-
const stops = gradient.stops.map(s => {
|
|
71
|
-
const color = cssColor(s.color ?? {});
|
|
72
|
-
return `<stop offset="${s.position}" stop-color="${color}"/>`;
|
|
73
|
-
}).join('');
|
|
74
|
-
const opacityAttr = gradient.opacity !== 1 ? ` opacity="${gradient.opacity}"` : '';
|
|
75
|
-
const f = v => +v.toFixed(2);
|
|
76
|
-
|
|
77
|
-
if (geometry.type === 'linear') {
|
|
78
|
-
return {
|
|
79
|
-
defs: `<linearGradient id="${id}" x1="${f(geometry.start.x)}" y1="${f(geometry.start.y)}" x2="${f(geometry.end.x)}" y2="${f(geometry.end.y)}" gradientUnits="userSpaceOnUse">${stops}</linearGradient>`,
|
|
80
|
-
fill: `url(#${id})`,
|
|
81
|
-
opacityAttr,
|
|
82
|
-
};
|
|
83
|
-
}
|
|
84
|
-
const cx = f(geometry.center.x), cy = f(geometry.center.y);
|
|
85
|
-
const rx = f(geometry.radiusX), ry = f(geometry.radiusY);
|
|
86
|
-
const angle = f(geometry.angle * 180 / Math.PI);
|
|
87
|
-
return {
|
|
88
|
-
defs: `<radialGradient id="${id}" cx="${cx}" cy="${cy}" rx="${rx}" ry="${ry}" gradientUnits="userSpaceOnUse" gradientTransform="rotate(${angle},${cx},${cy})">${stops}</radialGradient>`,
|
|
89
|
-
fill: `url(#${id})`,
|
|
90
|
-
opacityAttr,
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
function appendDefs(defs, extra) {
|
|
95
|
-
if (!extra) return defs;
|
|
96
|
-
return defs
|
|
97
|
-
? defs.replace('</defs>', `${extra}</defs>`)
|
|
98
|
-
: `<defs>${extra}</defs>`;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/** Get effective fillPaints for any node type. */
|
|
102
|
-
function getFillPaints(node) {
|
|
103
|
-
if (node.fillPaints?.length) return node.fillPaints;
|
|
104
|
-
// SHAPE_WITH_TEXT stores fill in nodeGenerationData.overrides[0].fillPaints
|
|
105
|
-
return node.nodeGenerationData?.overrides?.[0]?.fillPaints ?? null;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
function strokeSpec(node) {
|
|
109
|
-
if (!node.strokeWeight || node.strokeWeight === 0) return null;
|
|
110
|
-
const color = resolveFill(node.strokePaints) ?? 'none';
|
|
111
|
-
if (color === 'none') return null;
|
|
112
|
-
return {
|
|
113
|
-
color,
|
|
114
|
-
width: node.strokeWeight,
|
|
115
|
-
align: node.strokeAlign ?? 'CENTER',
|
|
116
|
-
};
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
/** Render strokeGeometry blobs as filled <path> elements (Figma's pre-expanded stroke outlines).
|
|
120
|
-
* Returns SVG string or '' if no strokeGeometry is available. */
|
|
121
|
-
function strokeGeometrySvg(deck, node) {
|
|
122
|
-
const strokeColor = resolveFill(node.strokePaints);
|
|
123
|
-
const sw = node.strokeWeight ?? 0;
|
|
124
|
-
const blobs = deck.message?.blobs;
|
|
125
|
-
if (!strokeColor || sw <= 0 || !node.strokeGeometry?.length || !blobs) return '';
|
|
126
|
-
const segments = [];
|
|
127
|
-
let hasEvenOdd = false;
|
|
128
|
-
for (const geo of node.strokeGeometry) {
|
|
129
|
-
const d = decodeCmdBlob(blobs, geo.commandsBlob);
|
|
130
|
-
if (d) segments.push(d);
|
|
131
|
-
if (geo.windingRule === 'EVENODD') hasEvenOdd = true;
|
|
132
|
-
}
|
|
133
|
-
if (!segments.length) return '';
|
|
134
|
-
const rule = (segments.length > 1 || hasEvenOdd) ? ' fill-rule="evenodd"' : '';
|
|
135
|
-
return `<path d="${segments.join('')}" fill="${strokeColor}"${rule}/>`;
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
function rectStrokeSvg(x, y, w, h, rx, stroke) {
|
|
139
|
-
if (!stroke) return '';
|
|
140
|
-
let sx = x;
|
|
141
|
-
let sy = y;
|
|
142
|
-
let sw = w;
|
|
143
|
-
let sh = h;
|
|
144
|
-
let srx = Math.min(rx, w / 2, h / 2);
|
|
145
|
-
|
|
146
|
-
if (stroke.align === 'INSIDE') {
|
|
147
|
-
sx += stroke.width / 2;
|
|
148
|
-
sy += stroke.width / 2;
|
|
149
|
-
sw -= stroke.width;
|
|
150
|
-
sh -= stroke.width;
|
|
151
|
-
srx = Math.max(0, srx - stroke.width / 2);
|
|
152
|
-
} else if (stroke.align === 'OUTSIDE') {
|
|
153
|
-
sx -= stroke.width / 2;
|
|
154
|
-
sy -= stroke.width / 2;
|
|
155
|
-
sw += stroke.width;
|
|
156
|
-
sh += stroke.width;
|
|
157
|
-
srx += stroke.width / 2;
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
if (sw <= 0 || sh <= 0) return '';
|
|
161
|
-
return `<rect x="${sx}" y="${sy}" width="${sw}" height="${sh}" rx="${srx}" ry="${srx}" fill="none" stroke="${stroke.color}" stroke-width="${stroke.width}"/>`;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
function ellipseStrokeSvg(cx, cy, rx, ry, stroke) {
|
|
165
|
-
if (!stroke) return '';
|
|
166
|
-
let srx = rx;
|
|
167
|
-
let sry = ry;
|
|
168
|
-
|
|
169
|
-
if (stroke.align === 'INSIDE') {
|
|
170
|
-
srx -= stroke.width / 2;
|
|
171
|
-
sry -= stroke.width / 2;
|
|
172
|
-
} else if (stroke.align === 'OUTSIDE') {
|
|
173
|
-
srx += stroke.width / 2;
|
|
174
|
-
sry += stroke.width / 2;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
if (srx <= 0 || sry <= 0) return '';
|
|
178
|
-
return `<ellipse cx="${cx}" cy="${cy}" rx="${srx}" ry="${sry}" fill="none" stroke="${stroke.color}" stroke-width="${stroke.width}"/>`;
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
// ── Transform helpers ─────────────────────────────────────────────────────────
|
|
182
|
-
|
|
183
|
-
/** Return the full SVG transform attribute value for a node.
|
|
184
|
-
* Uses `translate(x,y)` for pure translations, `matrix(a,b,c,d,e,f)` when
|
|
185
|
-
* rotation or scale is present. */
|
|
186
|
-
function svgTransform(node) {
|
|
187
|
-
const t = node.transform;
|
|
188
|
-
if (!t) return 'translate(0,0)';
|
|
189
|
-
const m00 = t.m00 ?? 1, m01 = t.m01 ?? 0, m02 = t.m02 ?? 0;
|
|
190
|
-
const m10 = t.m10 ?? 0, m11 = t.m11 ?? 1, m12 = t.m12 ?? 0;
|
|
191
|
-
// Pure translation — no rotation or scale
|
|
192
|
-
if (Math.abs(m00 - 1) < 1e-6 && Math.abs(m01) < 1e-6 &&
|
|
193
|
-
Math.abs(m10) < 1e-6 && Math.abs(m11 - 1) < 1e-6) {
|
|
194
|
-
return `translate(${m02},${m12})`;
|
|
195
|
-
}
|
|
196
|
-
// Use high precision for rotation/scale — 2dp on a 2000px element = ~8px error
|
|
197
|
-
const h = v => +v.toFixed(6);
|
|
198
|
-
return `matrix(${h(m00)},${h(m10)},${h(m01)},${h(m11)},${f(m02)},${f(m12)})`;
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
function size(node) {
|
|
202
|
-
return { w: node.size?.x ?? 0, h: node.size?.y ?? 0 };
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
// ── Node renderers ────────────────────────────────────────────────────────────
|
|
206
|
-
|
|
207
|
-
function renderRect(deck, node) {
|
|
208
|
-
const { w, h } = size(node);
|
|
209
|
-
const rx = Math.min(node.cornerRadius ?? 0, w / 2, h / 2);
|
|
210
|
-
const { defs, bg } = renderRoundedRectFillStack(deck, getFillPaints(node), w, h, rx);
|
|
211
|
-
const fillSvg = bg ? `${[defs, bg].filter(Boolean).join('\n')}` : '';
|
|
212
|
-
// Prefer strokeGeometry (Figma's pre-computed outline) for matching anti-aliasing.
|
|
213
|
-
// strokeGeometry is CENTER-aligned — render underneath fill so fill covers inner half.
|
|
214
|
-
const geoStroke = strokeGeometrySvg(deck, node);
|
|
215
|
-
const strokeSvg = geoStroke || rectStrokeSvg(0, 0, w, h, rx, strokeSpec(node));
|
|
216
|
-
// Stroke underneath, fill on top (hides inner half for OUTSIDE strokes)
|
|
217
|
-
const inner = geoStroke
|
|
218
|
-
? [strokeSvg, fillSvg].filter(Boolean).join('\n')
|
|
219
|
-
: [fillSvg, strokeSvg].filter(Boolean).join('\n');
|
|
220
|
-
if (!inner) return '';
|
|
221
|
-
return `<g transform="${svgTransform(node)}">\n${inner}\n</g>`;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
function renderEllipse(deck, node) {
|
|
225
|
-
const { w, h } = size(node);
|
|
226
|
-
const fill = resolveFill(getFillPaints(node)) ?? 'none';
|
|
227
|
-
// Local coordinates — svgTransform handles position + rotation
|
|
228
|
-
const cx = w / 2;
|
|
229
|
-
const cy = h / 2;
|
|
230
|
-
const rx = w / 2;
|
|
231
|
-
const ry = h / 2;
|
|
232
|
-
const fillSvg = `<ellipse cx="${cx}" cy="${cy}" rx="${rx}" ry="${ry}" fill="${fill}"/>`;
|
|
233
|
-
// Prefer strokeGeometry (Figma's pre-computed outline) for matching anti-aliasing.
|
|
234
|
-
// strokeGeometry is CENTER-aligned — render underneath fill so fill covers inner half.
|
|
235
|
-
const geoStroke = strokeGeometrySvg(deck, node);
|
|
236
|
-
const strokeSvg = geoStroke || ellipseStrokeSvg(cx, cy, rx, ry, strokeSpec(node));
|
|
237
|
-
// Stroke underneath, fill on top (hides inner half for OUTSIDE strokes)
|
|
238
|
-
const inner = geoStroke
|
|
239
|
-
? [strokeSvg, fillSvg].filter(Boolean).join('\n')
|
|
240
|
-
: [fillSvg, strokeSvg].filter(Boolean).join('\n');
|
|
241
|
-
return `<g transform="${svgTransform(node)}">\n${inner}\n</g>`;
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
function resolveLineHeight(lh, fontSize) {
|
|
245
|
-
if (!lh) return fontSize * 1.2;
|
|
246
|
-
switch (lh.units) {
|
|
247
|
-
case 'RAW': return lh.value * fontSize;
|
|
248
|
-
case 'PERCENT': return (lh.value / 100) * fontSize;
|
|
249
|
-
case 'PIXELS': return lh.value;
|
|
250
|
-
default: return fontSize * 1.2;
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
// ── Text width approximation (Inter-like proportional metrics) ──────────────
|
|
255
|
-
//
|
|
256
|
-
// Used only when wrapping text in the fallback layout path (no derivedTextData,
|
|
257
|
-
// e.g. programmatically-generated text). Values are expressed as a fraction of
|
|
258
|
-
// fontSize and tuned for Inter Regular — close enough for word-wrap decisions.
|
|
259
|
-
const _NARROW = new Set('iIlt.,:;!|\'`"()[]{}/\\'.split(''));
|
|
260
|
-
const _WIDE = new Set('ABCDEFGHJKLNOPQRSTUVXYZmw'.split(''));
|
|
261
|
-
const _XWIDE = new Set('MW@%'.split(''));
|
|
262
|
-
function approxCharWidth(ch, fontSize) {
|
|
263
|
-
if (ch === ' ') return fontSize * 0.28;
|
|
264
|
-
if (_NARROW.has(ch)) return fontSize * 0.28;
|
|
265
|
-
if (_XWIDE.has(ch)) return fontSize * 0.85;
|
|
266
|
-
if (_WIDE.has(ch)) return fontSize * 0.66;
|
|
267
|
-
return fontSize * 0.52; // default for lowercase + digits + punctuation
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
function approxTextWidth(str, fontSize, letterSpacingPx = 0) {
|
|
271
|
-
let w = 0;
|
|
272
|
-
for (let i = 0; i < str.length; i++) w += approxCharWidth(str[i], fontSize);
|
|
273
|
-
if (str.length > 1) w += letterSpacingPx * (str.length - 1);
|
|
274
|
-
return w;
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
/**
|
|
278
|
-
* Word-wrap a single line into multiple lines that each fit within maxWidth.
|
|
279
|
-
* Breaks on ASCII spaces only. If a single "word" overflows maxWidth it is
|
|
280
|
-
* placed on its own line (no mid-word break).
|
|
281
|
-
* @param {string} line
|
|
282
|
-
* @param {number} fontSize
|
|
283
|
-
* @param {number} maxWidth
|
|
284
|
-
* @param {number} letterSpacingPx
|
|
285
|
-
* @returns {string[]}
|
|
286
|
-
*/
|
|
287
|
-
function wrapLineByWidth(line, fontSize, maxWidth, letterSpacingPx = 0) {
|
|
288
|
-
if (!line) return [line];
|
|
289
|
-
if (!(maxWidth > 0)) return [line];
|
|
290
|
-
if (approxTextWidth(line, fontSize, letterSpacingPx) <= maxWidth) return [line];
|
|
291
|
-
const words = line.split(' ');
|
|
292
|
-
const out = [];
|
|
293
|
-
let cur = '';
|
|
294
|
-
for (const word of words) {
|
|
295
|
-
const candidate = cur ? cur + ' ' + word : word;
|
|
296
|
-
if (approxTextWidth(candidate, fontSize, letterSpacingPx) <= maxWidth || !cur) {
|
|
297
|
-
cur = candidate;
|
|
298
|
-
} else {
|
|
299
|
-
out.push(cur);
|
|
300
|
-
cur = word;
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
if (cur) out.push(cur);
|
|
304
|
-
return out;
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
function esc(s) {
|
|
308
|
-
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
/**
|
|
312
|
-
* Detect stale derivedTextData: text was edited outside Figma but glyph layout
|
|
313
|
-
* wasn't recomputed. Returns true when the layout clearly doesn't match the text.
|
|
314
|
-
*/
|
|
315
|
-
function isStaleLayout(chars, baselines, glyphs) {
|
|
316
|
-
if (!chars) return false;
|
|
317
|
-
// No derivedTextData at all (e.g. programmatically created text)
|
|
318
|
-
if (!baselines?.length && !glyphs?.length) return true;
|
|
319
|
-
const len = chars.length;
|
|
320
|
-
|
|
321
|
-
if (baselines?.length) {
|
|
322
|
-
const lastEnd = baselines[baselines.length - 1]?.endCharacter;
|
|
323
|
-
// baselines endCharacter should match chars length (±1 for trailing newline)
|
|
324
|
-
if (lastEnd != null && Math.abs(lastEnd - len) > 1) return true;
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
if (glyphs?.length) {
|
|
328
|
-
const maxFirstChar = glyphs.reduce((max, g) =>
|
|
329
|
-
Math.max(max, g.firstCharacter ?? 0), 0);
|
|
330
|
-
if (maxFirstChar >= len) return true; // glyphs point beyond new text
|
|
331
|
-
if (len > maxFirstChar + 3) return true; // new text much longer than glyph coverage
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
return false;
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
/**
|
|
338
|
-
* Fallback text layout for stale derivedTextData.
|
|
339
|
-
* Emits line-level <tspan> elements and lets resvg handle per-glyph layout.
|
|
340
|
-
* Uses original baseline metrics (line height, ascent, position) where available
|
|
341
|
-
* since those are style-dependent, not content-dependent.
|
|
342
|
-
* Auto-scales font size down when new text is longer than the original.
|
|
343
|
-
* Returns { tspans, fontSize } so the caller can use the adjusted size.
|
|
344
|
-
*/
|
|
345
|
-
function fallbackTextTspans(dispChars, fontSize, node, letterSpacingPx = 0) {
|
|
346
|
-
const baselines = node.derivedTextData?.baselines;
|
|
347
|
-
const rawLines = dispChars.split('\n');
|
|
348
|
-
// Drop trailing empty line from trailing newline
|
|
349
|
-
if (rawLines.length > 1 && !rawLines[rawLines.length - 1]) rawLines.pop();
|
|
350
|
-
|
|
351
|
-
// Use original baseline metrics for spacing (style property, still valid).
|
|
352
|
-
// When baselines are absent (programmatically-generated text), honour the
|
|
353
|
-
// node's own lineHeight (RAW/PERCENT/PIXELS) rather than falling back to
|
|
354
|
-
// a hard-coded 1.2× multiplier, so hand-authored lineHeight values render
|
|
355
|
-
// correctly. Ultimate default 1.25× per spec.
|
|
356
|
-
const lhFromNode = node.lineHeight ? resolveLineHeight(node.lineHeight, fontSize) : null;
|
|
357
|
-
let lineHeightPx = baselines?.[0]?.lineHeight ?? lhFromNode ?? fontSize * 1.25;
|
|
358
|
-
let lineAscent = baselines?.[0]?.lineAscent ?? fontSize * 0.8;
|
|
359
|
-
|
|
360
|
-
// Auto-fit: scale font size down when new text is longer than original.
|
|
361
|
-
// Uses character count ratio per line as a proxy for width ratio.
|
|
362
|
-
const nodeW = node.size?.x ?? 1920;
|
|
363
|
-
const nodeH = node.size?.y ?? 0;
|
|
364
|
-
let scale = 1;
|
|
365
|
-
if (baselines?.length) {
|
|
366
|
-
const maxOrigCharsPerLine = Math.max(...baselines.map(b =>
|
|
367
|
-
Math.max(0, (b.endCharacter ?? 0) - (b.firstCharacter ?? 0))));
|
|
368
|
-
const maxNewCharsPerLine = Math.max(...rawLines.map(l => l.length));
|
|
369
|
-
|
|
370
|
-
// Scale down if widest new line has more chars than widest original line
|
|
371
|
-
if (maxNewCharsPerLine > maxOrigCharsPerLine && maxOrigCharsPerLine > 0) {
|
|
372
|
-
scale = Math.min(scale, maxOrigCharsPerLine / maxNewCharsPerLine);
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
// Also scale down if more lines than original (would overflow vertically)
|
|
376
|
-
if (rawLines.length > baselines.length && nodeH > 0) {
|
|
377
|
-
scale = Math.min(scale, baselines.length / rawLines.length);
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
scale = Math.max(scale, 0.15); // don't shrink below 15%
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
const adjFontSize = fontSize * scale;
|
|
384
|
-
const adjLineHeight = lineHeightPx * scale;
|
|
385
|
-
const adjLineAscent = lineAscent * scale;
|
|
386
|
-
const adjLetterSpacingPx = letterSpacingPx * scale;
|
|
387
|
-
|
|
388
|
-
// Horizontal alignment → text-anchor + x position
|
|
389
|
-
const align = node.textAlignHorizontal ?? 'LEFT';
|
|
390
|
-
const anchor = align === 'CENTER' ? 'middle' : align === 'RIGHT' ? 'end' : 'start';
|
|
391
|
-
const anchorX = align === 'CENTER' ? nodeW / 2 : align === 'RIGHT' ? nodeW : 0;
|
|
392
|
-
|
|
393
|
-
// Use first baseline position if available (preserves Figma's padding/offset),
|
|
394
|
-
// otherwise compute from vertical alignment
|
|
395
|
-
let startX, startY;
|
|
396
|
-
if (baselines?.[0]?.position) {
|
|
397
|
-
startX = align === 'LEFT' ? baselines[0].position.x : anchorX;
|
|
398
|
-
// Scale startY relative to the baseline position for auto-fit
|
|
399
|
-
startY = baselines[0].position.y * scale;
|
|
400
|
-
} else {
|
|
401
|
-
startX = anchorX;
|
|
402
|
-
const vAlign = node.textAlignVertical ?? 'TOP';
|
|
403
|
-
// Placeholder; recomputed below once we know the wrapped line count.
|
|
404
|
-
startY = adjLineAscent;
|
|
405
|
-
// Mark that we need to recompute after word-wrap based on final line count
|
|
406
|
-
// (kept here for readability — actual recompute below).
|
|
407
|
-
if (vAlign !== 'TOP') startY = null;
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
// Word-wrap each hard-newline-delimited line to fit within the node's width.
|
|
411
|
-
// Only wrap when the node has an explicit size.x and ≥1 hard line overflows.
|
|
412
|
-
// Preserves alignment via the outer text-anchor/startX logic.
|
|
413
|
-
const lineType0 = null;
|
|
414
|
-
const linesMeta = node.textData?.lines ?? [];
|
|
415
|
-
// Interpret each rawLine and wrap — track (text, metaIndex) for each output line
|
|
416
|
-
const wrapped = []; // array of { text, metaIndex }
|
|
417
|
-
for (let i = 0; i < rawLines.length; i++) {
|
|
418
|
-
const rawLine = rawLines[i];
|
|
419
|
-
// Reserve horizontal space consumed by list marker + indent on this meta line
|
|
420
|
-
const meta = linesMeta[i];
|
|
421
|
-
const indent = (meta?.indentationLevel ?? 0) * adjFontSize * 0.8;
|
|
422
|
-
const effectiveMaxW = Math.max(0, nodeW - indent);
|
|
423
|
-
const pieces = wrapLineByWidth(rawLine, adjFontSize, effectiveMaxW, adjLetterSpacingPx);
|
|
424
|
-
for (const piece of pieces) wrapped.push({ text: piece, metaIndex: i });
|
|
425
|
-
}
|
|
426
|
-
|
|
427
|
-
// Recompute startY for non-TOP vertical alignment now that we know final line count
|
|
428
|
-
if (startY === null) {
|
|
429
|
-
const totalH = wrapped.length * adjLineHeight;
|
|
430
|
-
const nodeHH = node.size?.y ?? totalH;
|
|
431
|
-
const vAlign = node.textAlignVertical ?? 'TOP';
|
|
432
|
-
startY = vAlign === 'CENTER' ? (nodeHH - totalH) / 2 + adjLineAscent
|
|
433
|
-
: vAlign === 'BOTTOM' ? nodeHH - totalH + adjLineAscent
|
|
434
|
-
: adjLineAscent;
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
// List marker support: read lineType from textData.lines. Only apply marker
|
|
438
|
-
// to the first visual line of a wrapped paragraph.
|
|
439
|
-
let orderedCounter = 0;
|
|
440
|
-
let lastMetaIdx = -1;
|
|
441
|
-
|
|
442
|
-
const tspans = wrapped.map(({ text, metaIndex }, i) => {
|
|
443
|
-
const y = startY + i * adjLineHeight;
|
|
444
|
-
const meta = linesMeta[metaIndex];
|
|
445
|
-
const lineType = meta?.lineType;
|
|
446
|
-
const indent = (meta?.indentationLevel ?? 0) * adjFontSize * 0.8;
|
|
447
|
-
let prefix = '';
|
|
448
|
-
const isFirstVisualOfMeta = metaIndex !== lastMetaIdx;
|
|
449
|
-
if (isFirstVisualOfMeta) {
|
|
450
|
-
if (lineType === 'UNORDERED_LIST') {
|
|
451
|
-
prefix = '\u2022 '; // bullet •
|
|
452
|
-
orderedCounter = 0;
|
|
453
|
-
} else if (lineType === 'ORDERED_LIST') {
|
|
454
|
-
orderedCounter++;
|
|
455
|
-
prefix = `${orderedCounter}. `;
|
|
456
|
-
} else {
|
|
457
|
-
orderedCounter = 0;
|
|
458
|
-
}
|
|
459
|
-
lastMetaIdx = metaIndex;
|
|
460
|
-
}
|
|
461
|
-
const x = startX + indent;
|
|
462
|
-
return `<tspan x="${x.toFixed(2)}" y="${y.toFixed(2)}" text-anchor="${anchor}">${esc(prefix + text) || ' '}</tspan>`;
|
|
463
|
-
}).join('');
|
|
464
|
-
|
|
465
|
-
return { tspans, fontSize: adjFontSize };
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
function styleAttrsFromFontName(fontName, derivedFontWeight) {
|
|
469
|
-
const style = fontName?.style ?? 'Regular';
|
|
470
|
-
const weight = derivedFontWeight
|
|
471
|
-
? String(derivedFontWeight)
|
|
472
|
-
: /semibold/i.test(style) ? '600'
|
|
473
|
-
: /bold/i.test(style) ? '700'
|
|
474
|
-
: /medium/i.test(style) ? '500'
|
|
475
|
-
: '400';
|
|
476
|
-
const italic = /italic/i.test(style) ? 'italic' : 'normal';
|
|
477
|
-
return { weight, italic };
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
function glyphSlice(chars, glyphs, index) {
|
|
481
|
-
const g = glyphs[index];
|
|
482
|
-
if (g.firstCharacter == null) {
|
|
483
|
-
throw new Error('Unexpected glyph without firstCharacter');
|
|
484
|
-
}
|
|
485
|
-
let nextChar = null;
|
|
486
|
-
for (let j = index + 1; j < glyphs.length; j++) {
|
|
487
|
-
const fc = glyphs[j].firstCharacter;
|
|
488
|
-
if (fc != null && fc > g.firstCharacter) {
|
|
489
|
-
nextChar = fc;
|
|
490
|
-
break;
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
|
-
return chars.slice(g.firstCharacter, nextChar ?? (g.firstCharacter + 1));
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
function renderText(deck, node) {
|
|
497
|
-
const chars = node.textData?.characters ?? '';
|
|
498
|
-
if (!chars.trim()) return '';
|
|
499
|
-
const dispChars = node.textCase === 'UPPER' ? chars.toUpperCase()
|
|
500
|
-
: node.textCase === 'LOWER' ? chars.toLowerCase()
|
|
501
|
-
: chars;
|
|
502
|
-
|
|
503
|
-
let fontSize = node.derivedTextData?.glyphs?.[0]?.fontSize ?? node.fontSize ?? 24;
|
|
504
|
-
const fontFamily = node.fontName?.family ?? 'Inter';
|
|
505
|
-
const fill = resolveFill(getFillPaints(node)) ?? '#000000';
|
|
506
|
-
// Letter spacing: PERCENT is % of fontSize, PIXELS is absolute
|
|
507
|
-
const ls = node.letterSpacing;
|
|
508
|
-
let letterSpacingPx = !ls ? 0
|
|
509
|
-
: ls.units === 'PERCENT' ? (ls.value / 100) * fontSize
|
|
510
|
-
: ls.units === 'PIXELS' ? ls.value
|
|
511
|
-
: 0;
|
|
512
|
-
const baselines = node.derivedTextData?.baselines;
|
|
513
|
-
const glyphs = node.derivedTextData?.glyphs;
|
|
514
|
-
const styleIds = node.textData?.characterStyleIDs;
|
|
515
|
-
const styleTable = node.textData?.styleOverrideTable;
|
|
516
|
-
const stale = isStaleLayout(chars, baselines, glyphs);
|
|
517
|
-
if (!glyphs?.length && !stale) {
|
|
518
|
-
throw new Error(`TEXT ${node.name ?? nid(node)} is missing derived glyph layout`);
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
// Build styleID → {weight, italic, decoration, family} map
|
|
522
|
-
const styleMap = {};
|
|
523
|
-
if (styleIds && styleTable) {
|
|
524
|
-
for (const ov of styleTable) {
|
|
525
|
-
// Only override weight/italic/family if fontName is explicitly set in this style run
|
|
526
|
-
const hasFontName = ov.fontName?.family || ov.fontName?.style;
|
|
527
|
-
const { weight, italic } = hasFontName ? styleAttrsFromFontName(ov.fontName, null) : {};
|
|
528
|
-
styleMap[ov.styleID] = {
|
|
529
|
-
family: hasFontName ? (ov.fontName?.family ?? fontFamily) : null,
|
|
530
|
-
weight: hasFontName ? weight : null, // null → fall through to defWeight
|
|
531
|
-
italic: hasFontName ? italic : null, // null → fall through to defItalic
|
|
532
|
-
decoration: ov.textDecoration === 'UNDERLINE' ? 'underline' : 'none',
|
|
533
|
-
};
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
// Node-level defaults
|
|
538
|
-
const { weight: defWeight, italic: defItalic } = styleAttrsFromFontName(
|
|
539
|
-
node.fontName, node.derivedTextData?.fontMetaData?.[0]?.fontWeight
|
|
540
|
-
);
|
|
541
|
-
|
|
542
|
-
// Per-glyph positioning with ligature merging: each character gets its own
|
|
543
|
-
// <tspan> with Figma's x,y, EXCEPT known ligature sequences (fi, fl, ff,
|
|
544
|
-
// ffi, ffl) which are merged into a single <tspan> positioned at the first
|
|
545
|
-
// glyph so the font engine can substitute the ligature glyph.
|
|
546
|
-
const LIGATURES = ['ffl', 'ffi', 'ff', 'fi', 'fl'];
|
|
547
|
-
|
|
548
|
-
/** Check if a ligature starts at position i in the display string.
|
|
549
|
-
* Returns the ligature length or 0. */
|
|
550
|
-
function ligatureAt(i) {
|
|
551
|
-
for (const lig of LIGATURES) {
|
|
552
|
-
if (dispChars.slice(i, i + lig.length) === lig) return lig.length;
|
|
553
|
-
}
|
|
554
|
-
return 0;
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
let tspans = '';
|
|
558
|
-
if (stale || !glyphs?.length) {
|
|
559
|
-
// Fallback: derivedTextData is stale (text was edited outside Figma).
|
|
560
|
-
// Emit line-level tspans and let resvg handle per-glyph layout.
|
|
561
|
-
const origFontSize = fontSize;
|
|
562
|
-
const fb = fallbackTextTspans(dispChars, fontSize, node, letterSpacingPx);
|
|
563
|
-
tspans = fb.tspans;
|
|
564
|
-
fontSize = fb.fontSize; // auto-fit may have scaled down
|
|
565
|
-
if (origFontSize > 0) letterSpacingPx *= fontSize / origFontSize;
|
|
566
|
-
} else if (baselines?.length && glyphs?.length && styleIds?.length) {
|
|
567
|
-
// Mixed-style: group consecutive glyphs by styleID, emit per-glyph with ligature merge
|
|
568
|
-
for (const b of baselines) {
|
|
569
|
-
const lineGlyphs = glyphs.filter(g => g.firstCharacter >= b.firstCharacter && g.firstCharacter < b.endCharacter);
|
|
570
|
-
if (!lineGlyphs.length) continue;
|
|
571
|
-
|
|
572
|
-
const runs = [];
|
|
573
|
-
let curRun = null;
|
|
574
|
-
for (const g of lineGlyphs) {
|
|
575
|
-
const sid = styleIds[g.firstCharacter] ?? 0;
|
|
576
|
-
if (!curRun || sid !== curRun.sid) {
|
|
577
|
-
curRun = { sid, glyphs: [] };
|
|
578
|
-
runs.push(curRun);
|
|
579
|
-
}
|
|
580
|
-
curRun.glyphs.push(g);
|
|
581
|
-
}
|
|
582
|
-
|
|
583
|
-
for (const run of runs) {
|
|
584
|
-
const st = styleMap[run.sid] ?? {};
|
|
585
|
-
const w = st.weight ?? defWeight;
|
|
586
|
-
const it = st.italic ?? defItalic;
|
|
587
|
-
const fam = st.family ?? fontFamily;
|
|
588
|
-
for (let gi = 0; gi < run.glyphs.length; gi++) {
|
|
589
|
-
const g = run.glyphs[gi];
|
|
590
|
-
const ligLen = ligatureAt(g.firstCharacter);
|
|
591
|
-
const span = ligLen > 1 ? ligLen : 1;
|
|
592
|
-
const endIdx = gi + span < run.glyphs.length
|
|
593
|
-
? run.glyphs[gi + span].firstCharacter
|
|
594
|
-
: Math.min((run.glyphs[run.glyphs.length - 1].firstCharacter + 1), b.endCharacter);
|
|
595
|
-
const slice = dispChars.slice(g.firstCharacter, endIdx).replace(/\n$/, '');
|
|
596
|
-
if (!slice || /^\s+$/.test(slice)) continue;
|
|
597
|
-
tspans += `<tspan x="${g.position.x}" y="${g.position.y}" font-family="${fam}, sans-serif" font-weight="${w}" font-style="${it}">${esc(slice)}</tspan>`;
|
|
598
|
-
if (span > 1) gi += span - 1; // skip merged glyphs
|
|
599
|
-
}
|
|
600
|
-
}
|
|
601
|
-
}
|
|
602
|
-
} else if (glyphs?.length) {
|
|
603
|
-
// Per-glyph positioning with ligature merging
|
|
604
|
-
for (let i = 0; i < glyphs.length; i++) {
|
|
605
|
-
const g = glyphs[i];
|
|
606
|
-
const ligLen = ligatureAt(g.firstCharacter);
|
|
607
|
-
const span = ligLen > 1 ? ligLen : 1;
|
|
608
|
-
const endIdx = i + span < glyphs.length
|
|
609
|
-
? glyphs[i + span].firstCharacter
|
|
610
|
-
: chars.length;
|
|
611
|
-
const slice = dispChars.slice(g.firstCharacter, endIdx).replace(/\n$/, '');
|
|
612
|
-
if (!slice || /^\s+$/.test(slice)) { continue; }
|
|
613
|
-
tspans += `<tspan x="${g.position.x}" y="${g.position.y}">${esc(slice)}</tspan>`;
|
|
614
|
-
if (span > 1) i += span - 1; // skip merged glyphs
|
|
615
|
-
}
|
|
616
|
-
} else if (baselines?.length) {
|
|
617
|
-
tspans = baselines.map(b => {
|
|
618
|
-
const slice = dispChars.slice(b.firstCharacter, b.endCharacter).replace(/\n$/, '');
|
|
619
|
-
return `<tspan x="${b.position.x}" y="${b.position.y}">${esc(slice) || ' '}</tspan>`;
|
|
620
|
-
}).join('');
|
|
621
|
-
} else {
|
|
622
|
-
throw new Error(`TEXT ${node.name ?? nid(node)} is missing derived baselines`);
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
const lsAttr = letterSpacingPx === 0 ? '' : ` letter-spacing="${letterSpacingPx.toFixed(3)}"`;
|
|
626
|
-
|
|
627
|
-
const textEl = [
|
|
628
|
-
`<text font-size="${fontSize}" font-family="${fontFamily}, sans-serif"`,
|
|
629
|
-
` font-weight="${defWeight}" font-style="${defItalic}" fill="${fill}"${lsAttr}`,
|
|
630
|
-
` text-rendering="geometricPrecision">${tspans}</text>`,
|
|
631
|
-
].join('\n');
|
|
632
|
-
|
|
633
|
-
// Use Figma's pre-computed decoration rectangles (underline/strikethrough).
|
|
634
|
-
// derivedTextData.decorations[].rects are relative to the node's local origin.
|
|
635
|
-
const decorations = node.derivedTextData?.decorations ?? [];
|
|
636
|
-
if (!decorations.length) return `<g transform="${svgTransform(node)}">\n${textEl}\n</g>`;
|
|
637
|
-
const decorationRects = decorations.flatMap(d =>
|
|
638
|
-
(d.rects ?? []).map(r =>
|
|
639
|
-
`<rect x="${r.x.toFixed(2)}" y="${r.y.toFixed(2)}" width="${r.w.toFixed(2)}" height="${r.h.toFixed(2)}" fill="${fill}"/>`
|
|
640
|
-
)
|
|
641
|
-
);
|
|
642
|
-
const inner = decorationRects.length ? textEl + '\n' + decorationRects.join('\n') : textEl;
|
|
643
|
-
return `<g transform="${svgTransform(node)}">\n${inner}\n</g>`;
|
|
644
|
-
}
|
|
645
|
-
|
|
646
|
-
/**
|
|
647
|
-
* Resolve an IMAGE-type fillPaint to inline SVG defs + bg element.
|
|
648
|
-
* Supports FILL (cover), FIT (contain), and TILE scale modes.
|
|
649
|
-
* Throws if the image file cannot be read.
|
|
650
|
-
*/
|
|
651
|
-
function resolveImageFillSvg(deck, imgFill, w, h, rx) {
|
|
652
|
-
const hashBytes = imgFill.image?.hash;
|
|
653
|
-
const hash = hashBytes?.length ? hashToHex(hashBytes) : imgFill.image?.name;
|
|
654
|
-
if (!hash) throw new Error('Visible IMAGE fill is missing its asset hash');
|
|
655
|
-
const buf = deck.readImage(hash);
|
|
656
|
-
if (!buf) throw new Error(`Missing image fill asset ${hash}`);
|
|
657
|
-
|
|
658
|
-
const mime = (buf[0] === 0xFF && buf[1] === 0xD8) ? 'image/jpeg' : 'image/png';
|
|
659
|
-
const dataUri = `data:${mime};base64,${buf.toString('base64')}`;
|
|
660
|
-
const id = ++_svgIdSeq;
|
|
661
|
-
const clipId = `img-clip-${id}`;
|
|
662
|
-
const clipDef = `<clipPath id="${clipId}"><rect width="${w}" height="${h}" rx="${rx}" ry="${rx}"/></clipPath>`;
|
|
663
|
-
const mode = imgFill.imageScaleMode ?? 'FILL';
|
|
664
|
-
const opacityAttr = (imgFill.opacity ?? 1) !== 1 ? ` opacity="${imgFill.opacity}"` : '';
|
|
665
|
-
|
|
666
|
-
if (mode === 'TILE') {
|
|
667
|
-
const tw = (imgFill.originalImageWidth ?? 100) * (imgFill.scale ?? 1);
|
|
668
|
-
const th = (imgFill.originalImageHeight ?? 100) * (imgFill.scale ?? 1);
|
|
669
|
-
const patId = `img-pat-${id}`;
|
|
670
|
-
return {
|
|
671
|
-
defs: `${clipDef}<pattern id="${patId}" x="0" y="0" width="${tw}" height="${th}" patternUnits="userSpaceOnUse"><image href="${dataUri}" width="${tw}" height="${th}"${opacityAttr}/></pattern>`,
|
|
672
|
-
bg: `<rect x="0" y="0" width="${w}" height="${h}" rx="${rx}" ry="${rx}" fill="url(#${patId})" clip-path="url(#${clipId})"/>`,
|
|
673
|
-
};
|
|
674
|
-
}
|
|
675
|
-
|
|
676
|
-
if (mode === 'STRETCH') {
|
|
677
|
-
const t = imgFill.transform;
|
|
678
|
-
const ow = imgFill.originalImageWidth ?? 0;
|
|
679
|
-
const oh = imgFill.originalImageHeight ?? 0;
|
|
680
|
-
const axisAligned = t
|
|
681
|
-
&& Math.abs(t.m01 ?? 0) < 1e-9
|
|
682
|
-
&& Math.abs(t.m10 ?? 0) < 1e-9
|
|
683
|
-
&& t.m00 > 0
|
|
684
|
-
&& t.m11 > 0
|
|
685
|
-
&& ow > 0
|
|
686
|
-
&& oh > 0;
|
|
687
|
-
if (axisAligned) {
|
|
688
|
-
const cropX = t.m02 * ow;
|
|
689
|
-
const cropY = t.m12 * oh;
|
|
690
|
-
const cropW = t.m00 * ow;
|
|
691
|
-
const cropH = t.m11 * oh;
|
|
692
|
-
const scaleX = w / cropW;
|
|
693
|
-
const scaleY = h / cropH;
|
|
694
|
-
return {
|
|
695
|
-
defs: clipDef,
|
|
696
|
-
bg: `<image href="${dataUri}" x="${-cropX * scaleX}" y="${-cropY * scaleY}" `
|
|
697
|
-
+ `width="${ow * scaleX}" height="${oh * scaleY}" preserveAspectRatio="none" `
|
|
698
|
-
+ `clip-path="url(#${clipId})"${opacityAttr}/>`,
|
|
699
|
-
};
|
|
700
|
-
}
|
|
701
|
-
}
|
|
702
|
-
|
|
703
|
-
// FILL (cover) or FIT (contain), plus a safe fallback for an unsupported
|
|
704
|
-
// rotated/skewed STRETCH (plugin API: CROP) transform.
|
|
705
|
-
const par = mode === 'FIT' ? 'xMidYMid meet' : 'xMidYMid slice';
|
|
706
|
-
return {
|
|
707
|
-
defs: clipDef,
|
|
708
|
-
bg: `<image href="${dataUri}" x="0" y="0" width="${w}" height="${h}" preserveAspectRatio="${par}" clip-path="url(#${clipId})"${opacityAttr}/>`,
|
|
709
|
-
};
|
|
710
|
-
}
|
|
711
|
-
|
|
712
|
-
function renderRoundedRectFillStack(deck, fillPaints, w, h, rx) {
|
|
713
|
-
const visibleFills = fillPaints?.filter(p => p.visible !== false) ?? [];
|
|
714
|
-
let defs = '';
|
|
715
|
-
const bgParts = [];
|
|
716
|
-
|
|
717
|
-
for (const fill of visibleFills) {
|
|
718
|
-
if (fill.type === 'SOLID') {
|
|
719
|
-
bgParts.push(`<rect x="0" y="0" width="${w}" height="${h}" rx="${rx}" ry="${rx}" fill="${cssColor(fill.color ?? {}, fill.opacity ?? 1)}"/>`);
|
|
720
|
-
continue;
|
|
721
|
-
}
|
|
722
|
-
if (fill.type === 'IMAGE') {
|
|
723
|
-
const result = resolveImageFillSvg(deck, fill, w, h, rx);
|
|
724
|
-
defs = appendDefs(defs, result.defs);
|
|
725
|
-
bgParts.push(result.bg);
|
|
726
|
-
continue;
|
|
727
|
-
}
|
|
728
|
-
if (fill.type === 'GRADIENT_LINEAR' || fill.type === 'GRADIENT_RADIAL') {
|
|
729
|
-
const grad = resolveGradientSvg(fill, w, h);
|
|
730
|
-
if (grad) {
|
|
731
|
-
defs = appendDefs(defs, grad.defs);
|
|
732
|
-
bgParts.push(`<rect x="0" y="0" width="${w}" height="${h}" rx="${rx}" ry="${rx}" fill="${grad.fill}"${grad.opacityAttr}/>`);
|
|
733
|
-
}
|
|
734
|
-
}
|
|
735
|
-
}
|
|
736
|
-
|
|
737
|
-
return { defs, bg: bgParts.join('\n') };
|
|
738
|
-
}
|
|
739
|
-
|
|
740
|
-
function renderFrame(deck, node) {
|
|
741
|
-
const { w, h } = size(node);
|
|
742
|
-
const rx = Math.min(node.cornerRadius ?? 0, w / 2, h / 2);
|
|
743
|
-
const stroke = strokeSpec(node);
|
|
744
|
-
const inner = childrenSvg(deck, node);
|
|
745
|
-
let { defs, bg } = renderRoundedRectFillStack(deck, getFillPaints(node), w, h, rx);
|
|
746
|
-
|
|
747
|
-
// Frame clipping: Figma frames clip children when "Clip content" is ON,
|
|
748
|
-
// stored as frameMaskDisabled === false (explicit). Clipping is suppressed:
|
|
749
|
-
// - inside SYMBOL trees (Figma doesn't enforce child frame clips in components)
|
|
750
|
-
// - on frames with no visible fill (grouping containers, not visual viewports)
|
|
751
|
-
const hasFill = getFillPaints(node)?.some(p => p.visible !== false);
|
|
752
|
-
let clippedInner = inner;
|
|
753
|
-
if (inner && node.frameMaskDisabled === false && _symbolDepth === 0 && hasFill) {
|
|
754
|
-
const clipId = `frame-clip-${++_svgIdSeq}`;
|
|
755
|
-
defs += `<clipPath id="${clipId}"><rect width="${w}" height="${h}" rx="${rx}" ry="${rx}"/></clipPath>`;
|
|
756
|
-
clippedInner = `<g clip-path="url(#${clipId})">${inner}</g>`;
|
|
757
|
-
}
|
|
758
|
-
|
|
759
|
-
const strokeSvg = rectStrokeSvg(0, 0, w, h, rx, stroke);
|
|
760
|
-
|
|
761
|
-
const parts = [defs, bg, clippedInner, strokeSvg].filter(Boolean).join('\n');
|
|
762
|
-
if (!parts) return '';
|
|
763
|
-
return `<g transform="${svgTransform(node)}">\n${parts}\n</g>`;
|
|
764
|
-
}
|
|
765
|
-
|
|
766
|
-
function renderGroup(deck, node) {
|
|
767
|
-
const inner = childrenSvg(deck, node);
|
|
768
|
-
if (!inner) return '';
|
|
769
|
-
return `<g transform="${svgTransform(node)}">\n${inner}\n</g>`;
|
|
770
|
-
}
|
|
771
|
-
|
|
772
|
-
/**
|
|
773
|
-
* SHAPE_WITH_TEXT: pill/badge nodes — styling and text stored in nodeGenerationData.overrides.
|
|
774
|
-
* overrides[0] = shape (fill, stroke, cornerRadius)
|
|
775
|
-
* overrides[1] = text (textData.characters, fontName, fontSize, textCase)
|
|
776
|
-
* Text position comes from derivedImmutableFrameData.overrides[1].
|
|
777
|
-
*/
|
|
778
|
-
function renderShapeWithText(deck, node) {
|
|
779
|
-
const { w, h } = size(node);
|
|
780
|
-
const genOvs = node.nodeGenerationData?.overrides ?? [];
|
|
781
|
-
const shapeOv = genOvs[0] ?? {};
|
|
782
|
-
const textOv = genOvs[1] ?? {};
|
|
783
|
-
|
|
784
|
-
// Shape styling
|
|
785
|
-
const rawRx = shapeOv.cornerRadius ?? 0;
|
|
786
|
-
const rx = Math.min(rawRx, w / 2, h / 2); // 1000000 → pill
|
|
787
|
-
const fill = resolveFill(shapeOv.fillPaints) ?? 'none';
|
|
788
|
-
|
|
789
|
-
// Prefer strokeGeometry (pre-computed filled outlines) over manual SVG strokes
|
|
790
|
-
const geoStroke = strokeGeometrySvg(deck, node);
|
|
791
|
-
let strokeAttr = '';
|
|
792
|
-
if (!geoStroke) {
|
|
793
|
-
const sw = shapeOv.strokeWeight ?? 0;
|
|
794
|
-
const stroke = sw > 0 ? resolveFill(shapeOv.strokePaints) ?? 'none' : 'none';
|
|
795
|
-
strokeAttr = sw > 0 && stroke !== 'none' ? `stroke="${stroke}" stroke-width="${sw}"` : '';
|
|
796
|
-
}
|
|
797
|
-
|
|
798
|
-
const fillSvg = `<rect x="0" y="0" width="${w}" height="${h}" rx="${rx}" ry="${rx}" fill="${fill}" ${strokeAttr}/>`;
|
|
799
|
-
// Stroke-under-fill compositing: strokeGeometry underneath, fill on top
|
|
800
|
-
const rectSvg = geoStroke ? `${geoStroke}\n${fillSvg}` : fillSvg;
|
|
801
|
-
|
|
802
|
-
// Text
|
|
803
|
-
const chars = textOv.textData?.characters ?? '';
|
|
804
|
-
if (!chars.trim()) return `<g transform="${svgTransform(node)}">${rectSvg}</g>`;
|
|
805
|
-
|
|
806
|
-
const textCase = textOv.textCase ?? 'ORIGINAL';
|
|
807
|
-
const dispChars = textCase === 'UPPER' ? chars.toUpperCase()
|
|
808
|
-
: textCase === 'LOWER' ? chars.toLowerCase()
|
|
809
|
-
: chars;
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
// Text offset + authoritative font metrics from derivedImmutableFrameData
|
|
813
|
-
const derivedOvs = node.derivedImmutableFrameData?.overrides ?? [];
|
|
814
|
-
const textDerived = derivedOvs.find(o => o.derivedTextData) ?? {};
|
|
815
|
-
const textBoxX = textDerived.transform?.m02 ?? 0;
|
|
816
|
-
const textBoxY = textDerived.transform?.m12 ?? 0;
|
|
817
|
-
const derivedText = textDerived.derivedTextData ?? {};
|
|
818
|
-
const glyphs = derivedText.glyphs;
|
|
819
|
-
const truncationStartIndex = derivedText.truncationStartIndex >= 0
|
|
820
|
-
? derivedText.truncationStartIndex
|
|
821
|
-
: null;
|
|
822
|
-
const swtStale = isStaleLayout(chars, derivedText.baselines, glyphs);
|
|
823
|
-
if (!glyphs?.length && !swtStale) {
|
|
824
|
-
throw new Error(`SHAPE_WITH_TEXT ${node.name ?? nid(node)} is missing derived glyph layout`);
|
|
825
|
-
}
|
|
826
|
-
|
|
827
|
-
// derivedTextData is authoritative — nodeGenerationData can have stale/wrong values
|
|
828
|
-
const derivedFont = textDerived.derivedTextData?.fontMetaData?.[0]?.key;
|
|
829
|
-
const fontSize = textDerived.derivedTextData?.glyphs?.[0]?.fontSize ?? textOv.fontSize ?? 24;
|
|
830
|
-
const fontFamily = derivedFont?.family ?? textOv.fontName?.family ?? 'Inter';
|
|
831
|
-
const fontStyle = derivedFont?.style ?? textOv.fontName?.style ?? 'Regular';
|
|
832
|
-
const fontWeight = /semibold|bold/i.test(fontStyle) ? 'bold'
|
|
833
|
-
: /medium/i.test(fontStyle) ? '500' : 'normal';
|
|
834
|
-
const fontItalic = /italic/i.test(fontStyle) ? 'italic' : 'normal';
|
|
835
|
-
const textFill = resolveFill(textOv.fillPaints) ?? '#000000';
|
|
836
|
-
|
|
837
|
-
let tspan;
|
|
838
|
-
|
|
839
|
-
if (swtStale || !glyphs?.length) {
|
|
840
|
-
// Fallback: stale layout — center text in shape using textBox offset
|
|
841
|
-
const swtBaselines = derivedText.baselines;
|
|
842
|
-
const lineHeightPx = swtBaselines?.[0]?.lineHeight ?? fontSize * 1.2;
|
|
843
|
-
const lineAscent = swtBaselines?.[0]?.lineAscent ?? fontSize * 0.8;
|
|
844
|
-
const lines = dispChars.split('\n').filter((l, i, a) => i < a.length - 1 || l);
|
|
845
|
-
const totalH = lines.length * lineHeightPx;
|
|
846
|
-
// Center vertically in the text box area
|
|
847
|
-
const textBoxH = textDerived.size?.y ?? h;
|
|
848
|
-
const startY = textBoxY + (textBoxH - totalH) / 2 + lineAscent;
|
|
849
|
-
const textBoxW = textDerived.size?.x ?? w;
|
|
850
|
-
const cx = textBoxX + textBoxW / 2;
|
|
851
|
-
tspan = lines.map((line, i) => {
|
|
852
|
-
const y = startY + i * lineHeightPx;
|
|
853
|
-
return `<tspan x="${cx}" y="${y.toFixed(2)}" text-anchor="middle">${esc(line) || ' '}</tspan>`;
|
|
854
|
-
}).join('');
|
|
855
|
-
} else {
|
|
856
|
-
const spans = [];
|
|
857
|
-
for (let i = 0; i < glyphs.length; i++) {
|
|
858
|
-
const g = glyphs[i];
|
|
859
|
-
if (truncationStartIndex != null && g.firstCharacter != null && g.firstCharacter >= truncationStartIndex) continue;
|
|
860
|
-
|
|
861
|
-
let slice = '';
|
|
862
|
-
let stopAfter = false;
|
|
863
|
-
if (g.firstCharacter == null) {
|
|
864
|
-
if (truncationStartIndex == null) continue;
|
|
865
|
-
slice = '…';
|
|
866
|
-
stopAfter = true;
|
|
867
|
-
} else {
|
|
868
|
-
let nextChar = null;
|
|
869
|
-
for (let j = i + 1; j < glyphs.length; j++) {
|
|
870
|
-
const fc = glyphs[j].firstCharacter;
|
|
871
|
-
if (fc != null && fc > g.firstCharacter) {
|
|
872
|
-
nextChar = fc;
|
|
873
|
-
break;
|
|
874
|
-
}
|
|
875
|
-
}
|
|
876
|
-
slice = dispChars.slice(g.firstCharacter, nextChar ?? (g.firstCharacter + 1));
|
|
877
|
-
}
|
|
878
|
-
|
|
879
|
-
if (!slice) continue;
|
|
880
|
-
spans.push(`<tspan x="${textBoxX + g.position.x}" y="${textBoxY + g.position.y}">${esc(slice)}</tspan>`);
|
|
881
|
-
if (stopAfter) break;
|
|
882
|
-
}
|
|
883
|
-
tspan = spans.join('');
|
|
884
|
-
}
|
|
885
|
-
|
|
886
|
-
const textSvg = [
|
|
887
|
-
`<text font-size="${fontSize}" font-family="${fontFamily}, sans-serif"`,
|
|
888
|
-
` font-weight="${fontWeight}" font-style="${fontItalic}" fill="${textFill}"`,
|
|
889
|
-
` text-rendering="geometricPrecision">${tspan}</text>`,
|
|
890
|
-
].join('\n');
|
|
891
|
-
|
|
892
|
-
return `<g transform="${svgTransform(node)}">\n${rectSvg}\n${textSvg}\n</g>`;
|
|
893
|
-
}
|
|
894
|
-
|
|
895
|
-
function renderLine(deck, node) {
|
|
896
|
-
// Prefer strokeGeometry (filled path outline) — gives better anti-aliasing
|
|
897
|
-
// than SVG <line> for near-horizontal/vertical angled lines.
|
|
898
|
-
const geoSvg = strokeGeometrySvg(deck, node);
|
|
899
|
-
if (geoSvg) {
|
|
900
|
-
return `<g transform="${svgTransform(node)}">\n${geoSvg}\n</g>`;
|
|
901
|
-
}
|
|
902
|
-
// Fallback: LINE uses full transform matrix: direction = (m00, m10), origin = (m02, m12)
|
|
903
|
-
const x1 = node.transform?.m02 ?? 0;
|
|
904
|
-
const y1 = node.transform?.m12 ?? 0;
|
|
905
|
-
const m00 = node.transform?.m00 ?? 1;
|
|
906
|
-
const m10 = node.transform?.m10 ?? 0;
|
|
907
|
-
const len = node.size?.x ?? 0;
|
|
908
|
-
const x2 = x1 + len * m00;
|
|
909
|
-
const y2 = y1 + len * m10;
|
|
910
|
-
const stroke = resolveFill(node.strokePaints) ?? '#000000';
|
|
911
|
-
const sw = node.strokeWeight ?? 1;
|
|
912
|
-
return `<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="${stroke}" stroke-width="${sw}"/>`;
|
|
913
|
-
}
|
|
914
|
-
|
|
915
|
-
/**
|
|
916
|
-
* VECTOR — decode fillGeometry/strokeGeometry commandsBlob binary to SVG paths.
|
|
917
|
-
*
|
|
918
|
-
* Blob format: [cmdByte][float32LE params...]
|
|
919
|
-
* 0x01 = moveTo (x, y)
|
|
920
|
-
* 0x02 = lineTo (x, y)
|
|
921
|
-
* 0x04 = cubicTo (c1x, c1y, c2x, c2y, x, y)
|
|
922
|
-
* 0x00 = close
|
|
923
|
-
*
|
|
924
|
-
* Coordinates are in node-size space. The full affine transform matrix is used
|
|
925
|
-
* to position, scale, and rotate the vector in the slide.
|
|
926
|
-
*/
|
|
927
|
-
function renderVector(deck, node) {
|
|
928
|
-
const t = node.transform ?? {};
|
|
929
|
-
const m00 = t.m00 ?? 1, m01 = t.m01 ?? 0, m02 = t.m02 ?? 0;
|
|
930
|
-
const m10 = t.m10 ?? 0, m11 = t.m11 ?? 1, m12 = t.m12 ?? 0;
|
|
931
|
-
const blobs = deck.message?.blobs;
|
|
932
|
-
const parts = [];
|
|
933
|
-
|
|
934
|
-
// Collect fill paths — each fillGeometry entry is an independent fill region.
|
|
935
|
-
// Sub-paths *within* one entry interact via fill-rule (e.g. QR codes, letter cutouts),
|
|
936
|
-
// but entries are never combined — otherwise nesting causes evenodd to cut holes.
|
|
937
|
-
const fillColor = resolveFill(getFillPaints(node));
|
|
938
|
-
const fillEntries = []; // { d, color, rule }
|
|
939
|
-
if (node.fillGeometry?.length && blobs) {
|
|
940
|
-
// Build styleID → fill color map from per-path overrides
|
|
941
|
-
const styleMap = new Map();
|
|
942
|
-
if (node.vectorData?.styleOverrideTable?.length) {
|
|
943
|
-
for (const s of node.vectorData.styleOverrideTable) {
|
|
944
|
-
if (s.styleID != null && s.fillPaints) {
|
|
945
|
-
styleMap.set(s.styleID, resolveFill(s.fillPaints));
|
|
946
|
-
}
|
|
947
|
-
}
|
|
948
|
-
}
|
|
949
|
-
|
|
950
|
-
for (const geo of node.fillGeometry) {
|
|
951
|
-
const color = (geo.styleID && styleMap.has(geo.styleID))
|
|
952
|
-
? styleMap.get(geo.styleID)
|
|
953
|
-
: fillColor;
|
|
954
|
-
if (!color) continue;
|
|
955
|
-
const d = decodeCmdBlob(blobs, geo.commandsBlob);
|
|
956
|
-
if (!d) continue;
|
|
957
|
-
const rule = geo.windingRule === 'EVENODD' ? ' fill-rule="evenodd"' : '';
|
|
958
|
-
fillEntries.push({ d, color, rule });
|
|
959
|
-
}
|
|
960
|
-
}
|
|
961
|
-
|
|
962
|
-
// Stroke handling — depends on strokeAlign:
|
|
963
|
-
// OUTSIDE: strokeGeometry is always CENTER-aligned in the blob data, regardless of
|
|
964
|
-
// the node's strokeAlign setting. For OUTSIDE, we use SVG native strokes at
|
|
965
|
-
// 2× width underneath the fill — the fill covers the inner half, leaving
|
|
966
|
-
// only the outer portion visible.
|
|
967
|
-
// CENTER: strokeGeometry blobs are pre-expanded filled outlines (correct as-is).
|
|
968
|
-
// INSIDE: strokeGeometry + clip (TODO — falls back to CENTER for now).
|
|
969
|
-
const strokeColor = resolveFill(node.strokePaints);
|
|
970
|
-
const sw = node.strokeWeight ?? 0;
|
|
971
|
-
const strokeAlign = node.strokeAlign ?? 'CENTER';
|
|
972
|
-
const dashAttr = Array.isArray(node.dashPattern) && node.dashPattern.length
|
|
973
|
-
? ` stroke-dasharray="${node.dashPattern.join(' ')}"`
|
|
974
|
-
: '';
|
|
975
|
-
const lineCap = node.strokeCap === 'ROUND'
|
|
976
|
-
? 'round'
|
|
977
|
-
: node.strokeCap === 'SQUARE'
|
|
978
|
-
? 'square'
|
|
979
|
-
: 'butt';
|
|
980
|
-
const lineJoin = node.strokeJoin === 'ROUND'
|
|
981
|
-
? 'round'
|
|
982
|
-
: node.strokeJoin === 'BEVEL'
|
|
983
|
-
? 'bevel'
|
|
984
|
-
: 'miter';
|
|
985
|
-
|
|
986
|
-
if (strokeAlign === 'OUTSIDE' && strokeColor && sw > 0 && fillEntries.length) {
|
|
987
|
-
// Stroke layer underneath (2× width, centered = sw outside + sw inside)
|
|
988
|
-
for (const { d, rule } of fillEntries) {
|
|
989
|
-
parts.push(
|
|
990
|
-
`<path d="${d}" fill="none" stroke="${strokeColor}" stroke-width="${sw * 2}" ` +
|
|
991
|
-
`stroke-linecap="${lineCap}" stroke-linejoin="${lineJoin}"${dashAttr}${rule}/>`
|
|
992
|
-
);
|
|
993
|
-
}
|
|
994
|
-
// Fill layer on top — covers inner half of stroke
|
|
995
|
-
for (const { d, color, rule } of fillEntries) {
|
|
996
|
-
parts.push(`<path d="${d}" fill="${color}"${rule}/>`);
|
|
997
|
-
}
|
|
998
|
-
} else {
|
|
999
|
-
// Emit fill paths
|
|
1000
|
-
for (const { d, color, rule } of fillEntries) {
|
|
1001
|
-
parts.push(`<path d="${d}" fill="${color}"${rule}/>`);
|
|
1002
|
-
}
|
|
1003
|
-
// CENTER/INSIDE: use pre-computed strokeGeometry outlines as filled paths
|
|
1004
|
-
if (strokeColor && sw > 0 && node.strokeGeometry?.length && blobs) {
|
|
1005
|
-
const segments = [];
|
|
1006
|
-
let hasEvenOdd = false;
|
|
1007
|
-
for (const geo of node.strokeGeometry) {
|
|
1008
|
-
const d = decodeCmdBlob(blobs, geo.commandsBlob);
|
|
1009
|
-
if (d) segments.push(d);
|
|
1010
|
-
if (geo.windingRule === 'EVENODD') hasEvenOdd = true;
|
|
1011
|
-
}
|
|
1012
|
-
if (segments.length) {
|
|
1013
|
-
const rule = (segments.length > 1 || hasEvenOdd) ? ' fill-rule="evenodd"' : '';
|
|
1014
|
-
parts.push(`<path d="${segments.join('')}" fill="${strokeColor}"${rule}/>`);
|
|
1015
|
-
}
|
|
1016
|
-
}
|
|
1017
|
-
}
|
|
1018
|
-
|
|
1019
|
-
// Fallback: decode vectorNetworkBlob when no pre-computed fill/strokeGeometry
|
|
1020
|
-
if (!parts.length && node.vectorData?.vectorNetworkBlob != null && blobs) {
|
|
1021
|
-
const vnbD = decodeVnb(blobs, node.vectorData.vectorNetworkBlob, node.vectorData.normalizedSize, node.size);
|
|
1022
|
-
if (vnbD) {
|
|
1023
|
-
if (!fillColor && strokeColor && sw > 0) {
|
|
1024
|
-
parts.push(
|
|
1025
|
-
`<path d="${vnbD}" fill="none" stroke="${strokeColor}" stroke-width="${sw}" ` +
|
|
1026
|
-
`stroke-linecap="${lineCap}" stroke-linejoin="${lineJoin}"${dashAttr}/>`
|
|
1027
|
-
);
|
|
1028
|
-
} else {
|
|
1029
|
-
const color = fillColor ?? strokeColor ?? '#000000';
|
|
1030
|
-
parts.push(`<path d="${vnbD}" fill="${color}" fill-rule="evenodd"/>`);
|
|
1031
|
-
}
|
|
1032
|
-
}
|
|
1033
|
-
}
|
|
1034
|
-
|
|
1035
|
-
if (!parts.length) return renderPlaceholder(deck, node);
|
|
1036
|
-
return `<g transform="matrix(${m00},${m10},${m01},${m11},${m02},${m12})">\n${parts.join('\n')}\n</g>`;
|
|
1037
|
-
}
|
|
1038
|
-
|
|
1039
|
-
/** BOOLEAN_OPERATION — render the pre-computed boolean result shape.
|
|
1040
|
-
* fillGeometry contains the merged boolean result; children are shape operands
|
|
1041
|
-
* baked into fillGeometry. However, the compound path may have winding-direction
|
|
1042
|
-
* holes that need filling. Children are re-rendered with the PARENT's fill color
|
|
1043
|
-
* (not their own) to fill these gaps — Figma applies the boolean node's fill
|
|
1044
|
-
* to all content uniformly. */
|
|
1045
|
-
function renderBooleanOp(deck, node) {
|
|
1046
|
-
const ownSvg = renderVector(deck, node);
|
|
1047
|
-
|
|
1048
|
-
// For UNION booleans: re-render children using the parent's fill color to
|
|
1049
|
-
// fill winding-direction holes. XOR/SUBTRACT/INTERSECT fillGeometry is
|
|
1050
|
-
// self-contained — children are pure shape operands.
|
|
1051
|
-
let inner = '';
|
|
1052
|
-
if (node.booleanOperation === 'UNION') {
|
|
1053
|
-
const parentFill = resolveFill(getFillPaints(node));
|
|
1054
|
-
if (parentFill) {
|
|
1055
|
-
const children = deck.getChildren(nid(node));
|
|
1056
|
-
const childParts = [];
|
|
1057
|
-
for (const child of children) {
|
|
1058
|
-
if (child.phase === 'REMOVED') continue;
|
|
1059
|
-
const origFills = child.fillPaints;
|
|
1060
|
-
child.fillPaints = getFillPaints(node);
|
|
1061
|
-
childParts.push(renderNode(deck, child));
|
|
1062
|
-
child.fillPaints = origFills;
|
|
1063
|
-
}
|
|
1064
|
-
inner = childParts.filter(Boolean).join('\n');
|
|
1065
|
-
}
|
|
1066
|
-
}
|
|
1067
|
-
|
|
1068
|
-
if (!ownSvg && !inner) return '';
|
|
1069
|
-
if (!inner) return ownSvg;
|
|
1070
|
-
if (!ownSvg) {
|
|
1071
|
-
const t = node.transform ?? {};
|
|
1072
|
-
const m00 = t.m00 ?? 1, m01 = t.m01 ?? 0, m02 = t.m02 ?? 0;
|
|
1073
|
-
const m10 = t.m10 ?? 0, m11 = t.m11 ?? 1, m12 = t.m12 ?? 0;
|
|
1074
|
-
return `<g transform="matrix(${m00},${m10},${m01},${m11},${m02},${m12})">\n${inner}\n</g>`;
|
|
1075
|
-
}
|
|
1076
|
-
const closeIdx = ownSvg.lastIndexOf('</g>');
|
|
1077
|
-
return ownSvg.slice(0, closeIdx) + inner + '\n</g>';
|
|
1078
|
-
}
|
|
1079
|
-
|
|
1080
|
-
/** Decode a commandsBlob index into an SVG path d-string. */
|
|
1081
|
-
function decodeCmdBlob(blobs, blobIdx) {
|
|
1082
|
-
if (blobIdx == null || !blobs?.[blobIdx]) return null;
|
|
1083
|
-
const raw = blobs[blobIdx].bytes ?? blobs[blobIdx];
|
|
1084
|
-
if (!raw) return null;
|
|
1085
|
-
|
|
1086
|
-
// Convert indexed object to Buffer if needed
|
|
1087
|
-
let buf;
|
|
1088
|
-
if (Buffer.isBuffer(raw) || raw instanceof Uint8Array) {
|
|
1089
|
-
buf = Buffer.from(raw);
|
|
1090
|
-
} else {
|
|
1091
|
-
const len = Object.keys(raw).length;
|
|
1092
|
-
buf = Buffer.alloc(len);
|
|
1093
|
-
for (let i = 0; i < len; i++) buf[i] = raw[i];
|
|
1094
|
-
}
|
|
1095
|
-
|
|
1096
|
-
const cmds = [];
|
|
1097
|
-
let off = 0;
|
|
1098
|
-
while (off < buf.length) {
|
|
1099
|
-
const cmd = buf[off++];
|
|
1100
|
-
if (cmd === 0x01) { // moveTo
|
|
1101
|
-
const x = buf.readFloatLE(off); off += 4;
|
|
1102
|
-
const y = buf.readFloatLE(off); off += 4;
|
|
1103
|
-
cmds.push(`M${f(x)},${f(y)}`);
|
|
1104
|
-
} else if (cmd === 0x02) { // lineTo
|
|
1105
|
-
const x = buf.readFloatLE(off); off += 4;
|
|
1106
|
-
const y = buf.readFloatLE(off); off += 4;
|
|
1107
|
-
cmds.push(`L${f(x)},${f(y)}`);
|
|
1108
|
-
} else if (cmd === 0x04) { // cubicTo
|
|
1109
|
-
const c1x = buf.readFloatLE(off); off += 4;
|
|
1110
|
-
const c1y = buf.readFloatLE(off); off += 4;
|
|
1111
|
-
const c2x = buf.readFloatLE(off); off += 4;
|
|
1112
|
-
const c2y = buf.readFloatLE(off); off += 4;
|
|
1113
|
-
const x = buf.readFloatLE(off); off += 4;
|
|
1114
|
-
const y = buf.readFloatLE(off); off += 4;
|
|
1115
|
-
cmds.push(`C${f(c1x)},${f(c1y)} ${f(c2x)},${f(c2y)} ${f(x)},${f(y)}`);
|
|
1116
|
-
} else if (cmd === 0x00) { // close
|
|
1117
|
-
cmds.push('Z');
|
|
1118
|
-
} else {
|
|
1119
|
-
break; // unknown command — stop
|
|
1120
|
-
}
|
|
1121
|
-
}
|
|
1122
|
-
return cmds.length ? cmds.join('') : null;
|
|
1123
|
-
}
|
|
1124
|
-
|
|
1125
|
-
function f(v) { return +v.toFixed(2); }
|
|
1126
|
-
|
|
1127
|
-
/**
|
|
1128
|
-
* Decode a vectorNetworkBlob into an SVG path d-string.
|
|
1129
|
-
*
|
|
1130
|
-
* The byte layout lives in `openfig-core`'s `parseVectorNetworkBlob`, which is held
|
|
1131
|
-
* to it by a byte-identical round-trip over a 42-blob reference corpus. This
|
|
1132
|
-
* function is a thin adapter: it scales coordinates from `normalizedSize` space to
|
|
1133
|
-
* `nodeSize` and emits path commands. It deliberately does not parse bytes — this
|
|
1134
|
-
* package used to carry its own walker, and the two descriptions of the format
|
|
1135
|
-
* drifted apart, with the rasterizer flattening every curve for as long as they did.
|
|
1136
|
-
*
|
|
1137
|
-
* A segment is straight iff all four tangent components are zero; there is no
|
|
1138
|
-
* segment-type field. See `openfig-core/docs/vector.md` and
|
|
1139
|
-
* `docs/figma-behaviour.md`.
|
|
1140
|
-
*/
|
|
1141
|
-
export function decodeVnb(blobs, blobIdx, normalizedSize, nodeSize) {
|
|
1142
|
-
const buf = blobToBuffer(blobs, blobIdx);
|
|
1143
|
-
if (!buf) return null;
|
|
1144
|
-
|
|
1145
|
-
let network;
|
|
1146
|
-
try {
|
|
1147
|
-
network = parseVectorNetworkBlob(new Uint8Array(buf));
|
|
1148
|
-
} catch {
|
|
1149
|
-
// A blob we cannot account for byte-for-byte is one we do not understand.
|
|
1150
|
-
// Returning null lets the caller fall through to its placeholder rather than
|
|
1151
|
-
// rendering geometry we half-read.
|
|
1152
|
-
return null;
|
|
1153
|
-
}
|
|
1154
|
-
|
|
1155
|
-
const scaleX = (nodeSize?.x ?? 1) / (normalizedSize?.x ?? 1);
|
|
1156
|
-
const scaleY = (nodeSize?.y ?? 1) / (normalizedSize?.y ?? 1);
|
|
1157
|
-
const verts = network.vertices.map((v) => ({ x: v.x * scaleX, y: v.y * scaleY }));
|
|
1158
|
-
const segs = network.segments.map((s) => ({
|
|
1159
|
-
sv: s.start.vertex,
|
|
1160
|
-
ev: s.end.vertex,
|
|
1161
|
-
tsx: s.start.dx * scaleX,
|
|
1162
|
-
tsy: s.start.dy * scaleY,
|
|
1163
|
-
tex: s.end.dx * scaleX,
|
|
1164
|
-
tey: s.end.dy * scaleY,
|
|
1165
|
-
isStraight: s.isStraight,
|
|
1166
|
-
}));
|
|
1167
|
-
|
|
1168
|
-
const segToPathCmd = (seg, start, end) => {
|
|
1169
|
-
if (seg.isStraight) return `L${f(end.x)},${f(end.y)}`;
|
|
1170
|
-
const c1x = start.x + seg.tsx;
|
|
1171
|
-
const c1y = start.y + seg.tsy;
|
|
1172
|
-
const c2x = end.x + seg.tex;
|
|
1173
|
-
const c2y = end.y + seg.tey;
|
|
1174
|
-
return `C${f(c1x)},${f(c1y)} ${f(c2x)},${f(c2y)} ${f(end.x)},${f(end.y)}`;
|
|
1175
|
-
};
|
|
1176
|
-
|
|
1177
|
-
// Regions → SVG subpaths. Each loop is its own closed subpath.
|
|
1178
|
-
const cmds = [];
|
|
1179
|
-
for (const region of network.regions) {
|
|
1180
|
-
for (const loop of region.loops) {
|
|
1181
|
-
loop.forEach((segIdx, s) => {
|
|
1182
|
-
const seg = segs[segIdx];
|
|
1183
|
-
if (!seg) return;
|
|
1184
|
-
const start = verts[seg.sv];
|
|
1185
|
-
const end = verts[seg.ev];
|
|
1186
|
-
if (!start || !end) return;
|
|
1187
|
-
if (s === 0) cmds.push(`M${f(start.x)},${f(start.y)}`);
|
|
1188
|
-
cmds.push(segToPathCmd(seg, start, end));
|
|
1189
|
-
});
|
|
1190
|
-
cmds.push('Z');
|
|
1191
|
-
}
|
|
1192
|
-
}
|
|
1193
|
-
|
|
1194
|
-
// Fallback for blobs that carry no usable region loops — an open path authored
|
|
1195
|
-
// via addPath(), or a region block this walk could not consume. Recover the
|
|
1196
|
-
// centerline by walking the stored segments in order so the node renders as a
|
|
1197
|
-
// stroke instead of falling through to the magenta placeholder.
|
|
1198
|
-
//
|
|
1199
|
-
// Note this is genuinely a fallback, not the common case: every stroke-only node
|
|
1200
|
-
// in the current deck fixtures carries regionCount === 1 and is handled above.
|
|
1201
|
-
if (!cmds.length && segs.length) {
|
|
1202
|
-
let currentEnd = null;
|
|
1203
|
-
let subpathStart = null;
|
|
1204
|
-
for (const seg of segs) {
|
|
1205
|
-
const start = verts[seg.sv];
|
|
1206
|
-
const end = verts[seg.ev];
|
|
1207
|
-
if (!start || !end) continue;
|
|
1208
|
-
if (currentEnd == null || seg.sv !== currentEnd) {
|
|
1209
|
-
cmds.push(`M${f(start.x)},${f(start.y)}`);
|
|
1210
|
-
subpathStart = seg.sv;
|
|
1211
|
-
}
|
|
1212
|
-
cmds.push(segToPathCmd(seg, start, end));
|
|
1213
|
-
if (subpathStart != null && seg.ev === subpathStart) {
|
|
1214
|
-
cmds.push('Z');
|
|
1215
|
-
currentEnd = null;
|
|
1216
|
-
subpathStart = null;
|
|
1217
|
-
} else {
|
|
1218
|
-
currentEnd = seg.ev;
|
|
1219
|
-
}
|
|
1220
|
-
}
|
|
1221
|
-
}
|
|
1222
|
-
|
|
1223
|
-
return cmds.length ? cmds.join('') : null;
|
|
1224
|
-
}
|
|
1225
|
-
|
|
1226
|
-
function blobToBuffer(blobs, blobIdx) {
|
|
1227
|
-
if (blobIdx == null || !blobs?.[blobIdx]) return null;
|
|
1228
|
-
const raw = blobs[blobIdx].bytes ?? blobs[blobIdx];
|
|
1229
|
-
if (!raw) return null;
|
|
1230
|
-
if (Buffer.isBuffer(raw) || raw instanceof Uint8Array) return Buffer.from(raw);
|
|
1231
|
-
const len = Object.keys(raw).length;
|
|
1232
|
-
const buf = Buffer.alloc(len);
|
|
1233
|
-
for (let i = 0; i < len; i++) buf[i] = raw[i];
|
|
1234
|
-
return buf;
|
|
1235
|
-
}
|
|
1236
|
-
|
|
1237
|
-
function renderPlaceholder(deck, node) {
|
|
1238
|
-
const { w, h } = size(node);
|
|
1239
|
-
const type = node.type ?? '?';
|
|
1240
|
-
return `<g transform="${svgTransform(node)}"><rect x="0" y="0" width="${w || 40}" height="${h || 40}" fill="none" stroke="#ff00ff" stroke-width="2" stroke-dasharray="6" opacity="0.5"/><!-- ${type} --></g>`;
|
|
1241
|
-
}
|
|
1242
|
-
|
|
1243
|
-
/**
|
|
1244
|
-
* INSTANCE → SYMBOL resolution.
|
|
1245
|
-
*
|
|
1246
|
-
* Figma templates use INSTANCE nodes that reference a SYMBOL definition.
|
|
1247
|
-
* The SYMBOL's children (TEXT, shapes, frames, etc.) define the visual content.
|
|
1248
|
-
* The INSTANCE may carry symbolOverrides that modify specific child properties
|
|
1249
|
-
* (text content, fills, etc.).
|
|
1250
|
-
*
|
|
1251
|
-
* Strategy:
|
|
1252
|
-
* - Resolve the SYMBOL via symbolData.symbolID
|
|
1253
|
-
* - Render the SYMBOL's children tree (they live in the normal node hierarchy)
|
|
1254
|
-
* - Apply symbolOverrides: text and fill overrides are temporarily applied
|
|
1255
|
-
* to the target nodes, rendered, then restored.
|
|
1256
|
-
*/
|
|
1257
|
-
function renderInstance(deck, node) {
|
|
1258
|
-
const symbolId = node.symbolData?.symbolID;
|
|
1259
|
-
if (!symbolId) return renderPlaceholder(deck, node);
|
|
1260
|
-
|
|
1261
|
-
const symNid = `${symbolId.sessionID}:${symbolId.localID}`;
|
|
1262
|
-
const symbol = deck.getNode(symNid);
|
|
1263
|
-
if (!symbol) return renderPlaceholder(deck, node);
|
|
1264
|
-
|
|
1265
|
-
// Figma-parity: reject instances of symbols with invalid variant specs.
|
|
1266
|
-
// Figma Desktop silently shows blank slides for these. We match that behavior
|
|
1267
|
-
// deliberately so our preview catches invalid decks instead of hiding them.
|
|
1268
|
-
// Root cause: older tooling created SYMBOL variants with names (e.g.
|
|
1269
|
-
// "Size=Wide") that don't exist in the component set's variantPropSpecs.
|
|
1270
|
-
if (symbol.componentKey && symbol.variantPropSpecs) {
|
|
1271
|
-
const specValues = new Set(symbol.variantPropSpecs.map(s => s.value));
|
|
1272
|
-
const nameValues = (symbol.name || '').split(', ').map(p => p.split('=')[1]).filter(Boolean);
|
|
1273
|
-
const invalid = nameValues.some(v => !specValues.has(v));
|
|
1274
|
-
if (invalid) {
|
|
1275
|
-
const nid = `${node.guid.sessionID}:${node.guid.localID}`;
|
|
1276
|
-
console.warn(`⚠️ Skipping INSTANCE ${nid}: symbol ${symNid} "${symbol.name}" has invalid variant specs — Figma would show blank`);
|
|
1277
|
-
return renderPlaceholder(deck, node);
|
|
1278
|
-
}
|
|
1279
|
-
}
|
|
1280
|
-
|
|
1281
|
-
// Temporarily apply symbolOverrides so rendered content reflects overrides.
|
|
1282
|
-
// Override guidPaths may reference library-original IDs (e.g. 100:656) rather
|
|
1283
|
-
// than local node IDs (e.g. 1:1131). Nodes expose their library ID via the
|
|
1284
|
-
// `overrideKey` property, so we build a lookup from overrideKey → local node.
|
|
1285
|
-
const overrides = node.symbolData?.symbolOverrides ?? [];
|
|
1286
|
-
const restores = [];
|
|
1287
|
-
|
|
1288
|
-
// Build overrideKey → node map for all SYMBOL descendants
|
|
1289
|
-
const okMap = new Map();
|
|
1290
|
-
function buildOkMap(nid) {
|
|
1291
|
-
for (const child of deck.getChildren(nid)) {
|
|
1292
|
-
const ok = child.overrideKey;
|
|
1293
|
-
if (ok) okMap.set(`${ok.sessionID}:${ok.localID}`, child);
|
|
1294
|
-
buildOkMap(`${child.guid.sessionID}:${child.guid.localID}`);
|
|
1295
|
-
}
|
|
1296
|
-
}
|
|
1297
|
-
buildOkMap(symNid);
|
|
1298
|
-
|
|
1299
|
-
// Build derivedSymbolData lookup: guidPath ID → entry.
|
|
1300
|
-
// Contains Figma-computed layout (size, transform, derivedTextData) for child
|
|
1301
|
-
// nodes as they appear in this INSTANCE, accounting for auto-layout resizing.
|
|
1302
|
-
const dsdMap = new Map();
|
|
1303
|
-
for (const entry of node.derivedSymbolData ?? []) {
|
|
1304
|
-
const guids = entry.guidPath?.guids;
|
|
1305
|
-
if (!guids?.length) continue;
|
|
1306
|
-
// Use the last guid in the path for single-level lookups
|
|
1307
|
-
const g = guids[guids.length - 1];
|
|
1308
|
-
dsdMap.set(`${g.sessionID}:${g.localID}`, entry);
|
|
1309
|
-
}
|
|
1310
|
-
|
|
1311
|
-
// Apply symbolOverrides (symbol swaps, text characters, fill paints).
|
|
1312
|
-
// overriddenSymbolID entries swap which SYMBOL a nested INSTANCE renders —
|
|
1313
|
-
// e.g. swapping a body pose or head style in a character component.
|
|
1314
|
-
// These must be processed first so okMap gets extended with the new symbol's
|
|
1315
|
-
// descendants before text/fill overrides are applied.
|
|
1316
|
-
for (const ov of overrides) {
|
|
1317
|
-
const guids = ov.guidPath?.guids;
|
|
1318
|
-
if (!guids?.length || guids.length !== 1) continue;
|
|
1319
|
-
const targetId = `${guids[0].sessionID}:${guids[0].localID}`;
|
|
1320
|
-
const target = deck.getNode(targetId) ?? okMap.get(targetId);
|
|
1321
|
-
if (!target) continue;
|
|
1322
|
-
|
|
1323
|
-
if (ov.overriddenSymbolID && target.symbolData) {
|
|
1324
|
-
const origSymbolID = target.symbolData.symbolID;
|
|
1325
|
-
restores.push(() => { target.symbolData.symbolID = origSymbolID; });
|
|
1326
|
-
target.symbolData.symbolID = ov.overriddenSymbolID;
|
|
1327
|
-
// Extend okMap with the new symbol's descendants so downstream
|
|
1328
|
-
// overrides and derivedSymbolData can find them by overrideKey.
|
|
1329
|
-
const newSymNid = `${ov.overriddenSymbolID.sessionID}:${ov.overriddenSymbolID.localID}`;
|
|
1330
|
-
buildOkMap(newSymNid);
|
|
1331
|
-
}
|
|
1332
|
-
|
|
1333
|
-
if (ov.textData?.characters != null && target.textData) {
|
|
1334
|
-
const origChars = target.textData.characters;
|
|
1335
|
-
restores.push(() => { target.textData.characters = origChars; });
|
|
1336
|
-
target.textData.characters = ov.textData.characters;
|
|
1337
|
-
}
|
|
1338
|
-
|
|
1339
|
-
if (ov.fillPaints) {
|
|
1340
|
-
const origFill = target.fillPaints;
|
|
1341
|
-
restores.push(() => { target.fillPaints = origFill; });
|
|
1342
|
-
target.fillPaints = ov.fillPaints;
|
|
1343
|
-
}
|
|
1344
|
-
}
|
|
1345
|
-
|
|
1346
|
-
// Apply derivedSymbolData to matching nodes.
|
|
1347
|
-
// Auto-layout symbols (stackMode set): Figma re-positions/resizes children,
|
|
1348
|
-
// so apply size + transform + derivedTextData and skip global scale.
|
|
1349
|
-
// Non-auto-layout symbols: children scale proportionally, so only apply
|
|
1350
|
-
// derivedTextData (glyph re-layout) and use global scale for positioning.
|
|
1351
|
-
const isAutoLayout = !!symbol.stackMode;
|
|
1352
|
-
for (const [dsdId, dsd] of dsdMap) {
|
|
1353
|
-
const target = deck.getNode(dsdId) ?? okMap.get(dsdId);
|
|
1354
|
-
if (!target) continue;
|
|
1355
|
-
|
|
1356
|
-
if (dsd.derivedTextData) {
|
|
1357
|
-
const orig = target.derivedTextData;
|
|
1358
|
-
restores.push(() => { target.derivedTextData = orig; });
|
|
1359
|
-
target.derivedTextData = dsd.derivedTextData;
|
|
1360
|
-
}
|
|
1361
|
-
if (isAutoLayout && dsd.size) {
|
|
1362
|
-
const orig = target.size;
|
|
1363
|
-
restores.push(() => { target.size = orig; });
|
|
1364
|
-
target.size = dsd.size;
|
|
1365
|
-
}
|
|
1366
|
-
if (isAutoLayout && dsd.transform) {
|
|
1367
|
-
const orig = target.transform;
|
|
1368
|
-
restores.push(() => { target.transform = orig; });
|
|
1369
|
-
target.transform = dsd.transform;
|
|
1370
|
-
}
|
|
1371
|
-
}
|
|
1372
|
-
|
|
1373
|
-
// Scale when INSTANCE size differs from SYMBOL size.
|
|
1374
|
-
// Auto-layout symbols have per-node layout from derivedSymbolData, so skip scale.
|
|
1375
|
-
const instSize = size(node);
|
|
1376
|
-
const symSize = size(symbol.size ? symbol : node);
|
|
1377
|
-
const sx = symSize.w ? instSize.w / symSize.w : 1;
|
|
1378
|
-
const sy = symSize.h ? instSize.h / symSize.h : 1;
|
|
1379
|
-
const needsScale = !isAutoLayout && (Math.abs(sx - 1) > 0.001 || Math.abs(sy - 1) > 0.001);
|
|
1380
|
-
|
|
1381
|
-
// Render SYMBOL's own fill as background (e.g. dark-blue cover slide)
|
|
1382
|
-
// Use INSTANCE size when auto-layout provides per-node layout
|
|
1383
|
-
const bgW = isAutoLayout ? instSize.w : symSize.w;
|
|
1384
|
-
const bgH = isAutoLayout ? instSize.h : symSize.h;
|
|
1385
|
-
const rx = Math.min(symbol.cornerRadius ?? 0, bgW / 2, bgH / 2);
|
|
1386
|
-
let { defs, bg } = renderRoundedRectFillStack(deck, getFillPaints(symbol), bgW, bgH, rx);
|
|
1387
|
-
|
|
1388
|
-
// Render stroke. Use the INSTANCE's strokeGeometry (already computed for
|
|
1389
|
-
// INSTANCE dimensions) when borders are independent; fall back to SYMBOL rect.
|
|
1390
|
-
let strokeSvg = '';
|
|
1391
|
-
const strokeSrc = node.strokePaints ? node : symbol;
|
|
1392
|
-
const strokeColor = resolveFill(strokeSrc.strokePaints);
|
|
1393
|
-
if (strokeColor && (strokeSrc.strokeWeight ?? 0) > 0) {
|
|
1394
|
-
if (strokeSrc.borderStrokeWeightsIndependent && strokeSrc.strokeGeometry?.length) {
|
|
1395
|
-
const blobs = deck.message?.blobs;
|
|
1396
|
-
if (blobs) {
|
|
1397
|
-
const segs = [];
|
|
1398
|
-
for (const geo of strokeSrc.strokeGeometry) {
|
|
1399
|
-
const d = decodeCmdBlob(blobs, geo.commandsBlob);
|
|
1400
|
-
if (d) segs.push(d);
|
|
1401
|
-
}
|
|
1402
|
-
if (segs.length) {
|
|
1403
|
-
// Clip stroke to frame bounds — Figma's INSIDE-aligned stroke geometry
|
|
1404
|
-
// extends ±strokeWeight outside the frame edge (symmetric expansion).
|
|
1405
|
-
// A clipPath matching the frame bounds shows only the inside portion.
|
|
1406
|
-
const scId = `stroke-clip-${++_svgIdSeq}`;
|
|
1407
|
-
strokeSvg = `<clipPath id="${scId}"><rect width="${bgW}" height="${bgH}"/></clipPath>`
|
|
1408
|
-
+ `<path d="${segs.join('')}" fill="${strokeColor}" clip-path="url(#${scId})"/>`;
|
|
1409
|
-
}
|
|
1410
|
-
}
|
|
1411
|
-
} else {
|
|
1412
|
-
const stroke = strokeSpec(strokeSrc);
|
|
1413
|
-
strokeSvg = rectStrokeSvg(0, 0, bgW, bgH, rx, stroke);
|
|
1414
|
-
}
|
|
1415
|
-
}
|
|
1416
|
-
|
|
1417
|
-
_symbolDepth++;
|
|
1418
|
-
const inner = childrenSvg(deck, symbol);
|
|
1419
|
-
_symbolDepth--;
|
|
1420
|
-
|
|
1421
|
-
// Restore mutations
|
|
1422
|
-
for (const fn of restores) fn();
|
|
1423
|
-
|
|
1424
|
-
let content = [defs, bg, inner, strokeSvg].filter(Boolean).join('\n');
|
|
1425
|
-
if (!content) return '';
|
|
1426
|
-
if (needsScale) {
|
|
1427
|
-
content = `<g transform="scale(${sx},${sy})">\n${content}\n</g>`;
|
|
1428
|
-
}
|
|
1429
|
-
return `<g transform="${svgTransform(node)}">\n${content}\n</g>`;
|
|
1430
|
-
}
|
|
1431
|
-
|
|
1432
|
-
// ── Dispatcher ────────────────────────────────────────────────────────────────
|
|
1433
|
-
|
|
1434
|
-
const RENDERERS = {
|
|
1435
|
-
ROUNDED_RECTANGLE: renderRect,
|
|
1436
|
-
RECTANGLE: renderRect,
|
|
1437
|
-
SHAPE_WITH_TEXT: renderShapeWithText,
|
|
1438
|
-
ELLIPSE: renderEllipse,
|
|
1439
|
-
TEXT: renderText,
|
|
1440
|
-
FRAME: renderFrame,
|
|
1441
|
-
GROUP: renderGroup,
|
|
1442
|
-
SECTION: renderGroup,
|
|
1443
|
-
BOOLEAN_OPERATION: renderBooleanOp,
|
|
1444
|
-
VECTOR: renderVector,
|
|
1445
|
-
LINE: renderLine,
|
|
1446
|
-
STAR: renderVector,
|
|
1447
|
-
REGULAR_POLYGON: renderVector,
|
|
1448
|
-
POLYGON: renderVector,
|
|
1449
|
-
INSTANCE: renderInstance,
|
|
1450
|
-
};
|
|
1451
|
-
|
|
1452
|
-
/** Build an SVG 1.1 <filter> for DROP_SHADOW effects.
|
|
1453
|
-
* Uses feGaussianBlur + feOffset + feFlood + feComposite + feMerge (SVG 1.1)
|
|
1454
|
-
* instead of feDropShadow (SVG 2) for broad renderer compatibility. */
|
|
1455
|
-
function buildEffectFilter(node) {
|
|
1456
|
-
const effects = node.effects?.filter(e => e.visible !== false);
|
|
1457
|
-
if (!effects?.length) return null;
|
|
1458
|
-
|
|
1459
|
-
const shadows = effects.filter(e => e.type === 'DROP_SHADOW');
|
|
1460
|
-
if (!shadows.length) return null;
|
|
1461
|
-
|
|
1462
|
-
const id = `fx-${++_svgIdSeq}`;
|
|
1463
|
-
const parts = [];
|
|
1464
|
-
const mergeNodes = [];
|
|
1465
|
-
|
|
1466
|
-
for (let i = 0; i < shadows.length; i++) {
|
|
1467
|
-
const s = shadows[i];
|
|
1468
|
-
const c = s.color ?? {};
|
|
1469
|
-
const r = Math.round((c.r ?? 0) * 255);
|
|
1470
|
-
const g = Math.round((c.g ?? 0) * 255);
|
|
1471
|
-
const b = Math.round((c.b ?? 0) * 255);
|
|
1472
|
-
const a = (c.a ?? 1).toFixed(4);
|
|
1473
|
-
const dx = s.offset?.x ?? 0;
|
|
1474
|
-
const dy = s.offset?.y ?? 0;
|
|
1475
|
-
const stdDev = (s.radius ?? 0) / 2;
|
|
1476
|
-
const sid = `s${i}`;
|
|
1477
|
-
parts.push(
|
|
1478
|
-
`<feGaussianBlur in="SourceAlpha" stdDeviation="${stdDev}" result="${sid}b"/>`,
|
|
1479
|
-
`<feOffset in="${sid}b" dx="${dx}" dy="${dy}" result="${sid}o"/>`,
|
|
1480
|
-
`<feFlood flood-color="rgb(${r},${g},${b})" flood-opacity="${a}" result="${sid}c"/>`,
|
|
1481
|
-
`<feComposite in="${sid}c" in2="${sid}o" operator="in" result="${sid}"/>`,
|
|
1482
|
-
);
|
|
1483
|
-
mergeNodes.push(`<feMergeNode in="${sid}"/>`);
|
|
1484
|
-
}
|
|
1485
|
-
mergeNodes.push(`<feMergeNode in="SourceGraphic"/>`);
|
|
1486
|
-
parts.push(`<feMerge>${mergeNodes.join('')}</feMerge>`);
|
|
1487
|
-
|
|
1488
|
-
// SVG default filter region: 10% padding. Sufficient for typical drop shadows
|
|
1489
|
-
// (radius ≤ 20px, offset ≤ 20px on elements > 100px).
|
|
1490
|
-
const defs = `<filter id="${id}" x="-10%" y="-10%" width="120%" height="120%" color-interpolation-filters="sRGB">${parts.join('')}</filter>`;
|
|
1491
|
-
return { defs, attr: `filter="url(#${id})"` };
|
|
1492
|
-
}
|
|
1493
|
-
|
|
1494
|
-
function renderNode(deck, node) {
|
|
1495
|
-
if (node.phase === 'REMOVED') return '';
|
|
1496
|
-
const fn = RENDERERS[node.type] ?? renderPlaceholder;
|
|
1497
|
-
let svg = fn(deck, node);
|
|
1498
|
-
if (!svg) return '';
|
|
1499
|
-
|
|
1500
|
-
// Apply effects (drop shadows)
|
|
1501
|
-
const fx = buildEffectFilter(node);
|
|
1502
|
-
if (fx) {
|
|
1503
|
-
svg = `<defs>${fx.defs}</defs>\n<g ${fx.attr}>${svg}</g>`;
|
|
1504
|
-
}
|
|
1505
|
-
|
|
1506
|
-
const op = node.opacity;
|
|
1507
|
-
if (op != null && op < 1) {
|
|
1508
|
-
svg = `<g opacity="${op}">${svg}</g>`;
|
|
1509
|
-
}
|
|
1510
|
-
return svg;
|
|
1511
|
-
}
|
|
1512
|
-
|
|
1513
|
-
function childrenSvg(deck, node) {
|
|
1514
|
-
const out = [];
|
|
1515
|
-
let activeMask = null;
|
|
1516
|
-
let masked = [];
|
|
1517
|
-
|
|
1518
|
-
const flushMask = () => {
|
|
1519
|
-
if (!activeMask) return;
|
|
1520
|
-
const body = masked.filter(Boolean).join('\n');
|
|
1521
|
-
if (body) {
|
|
1522
|
-
const id = `alpha-mask-${++_svgIdSeq}`;
|
|
1523
|
-
const maskSvg = renderNode(deck, activeMask);
|
|
1524
|
-
out.push(
|
|
1525
|
-
`<defs><mask id="${id}" maskUnits="userSpaceOnUse" x="-100%" y="-100%" `
|
|
1526
|
-
+ `width="300%" height="300%" style="mask-type:alpha">${maskSvg}</mask></defs>`,
|
|
1527
|
-
`<g mask="url(#${id})">${body}</g>`,
|
|
1528
|
-
);
|
|
1529
|
-
}
|
|
1530
|
-
activeMask = null;
|
|
1531
|
-
masked = [];
|
|
1532
|
-
};
|
|
1533
|
-
|
|
1534
|
-
for (const child of deck.getChildren(nid(node))) {
|
|
1535
|
-
// This converter emits ALPHA masks. Keep other mask types on the legacy
|
|
1536
|
-
// rendering path until their outline/luminance semantics are implemented.
|
|
1537
|
-
if (child.mask === true && child.maskType === 'ALPHA') {
|
|
1538
|
-
flushMask();
|
|
1539
|
-
activeMask = child;
|
|
1540
|
-
continue;
|
|
1541
|
-
}
|
|
1542
|
-
const svg = renderNode(deck, child);
|
|
1543
|
-
if (!svg) continue;
|
|
1544
|
-
if (activeMask) masked.push(svg);
|
|
1545
|
-
else out.push(svg);
|
|
1546
|
-
}
|
|
1547
|
-
flushMask();
|
|
1548
|
-
return out.join('\n');
|
|
1549
|
-
}
|
|
1550
|
-
|
|
1551
|
-
// ── Public API ────────────────────────────────────────────────────────────────
|
|
1552
|
-
|
|
1553
|
-
/**
|
|
1554
|
-
* Convert a single slide node and its subtree to an SVG string.
|
|
1555
|
-
*
|
|
1556
|
-
* @param {import('../fig-deck.mjs').FigDeck} deck
|
|
1557
|
-
* @param {object} slideNode - The SLIDE node object
|
|
1558
|
-
* @returns {string} - Complete SVG string (1920×1080)
|
|
1559
|
-
*/
|
|
1560
|
-
export function slideToSvg(deck, slideNode) {
|
|
1561
|
-
_svgIdSeq = 0;
|
|
1562
|
-
_symbolDepth = 0;
|
|
1563
|
-
const bg = resolveFill(getFillPaints(slideNode)) ?? 'white';
|
|
1564
|
-
|
|
1565
|
-
const body = childrenSvg(deck, slideNode);
|
|
1566
|
-
return `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" \
|
|
1567
|
-
width="${SLIDE_W}" height="${SLIDE_H}" viewBox="0 0 ${SLIDE_W} ${SLIDE_H}">
|
|
1568
|
-
<defs>
|
|
1569
|
-
<clipPath id="slide-clip"><rect width="${SLIDE_W}" height="${SLIDE_H}"/></clipPath>
|
|
1570
|
-
</defs>
|
|
1571
|
-
<rect width="${SLIDE_W}" height="${SLIDE_H}" fill="${bg}"/>
|
|
1572
|
-
<g clip-path="url(#slide-clip)">
|
|
1573
|
-
${body}
|
|
1574
|
-
</g>
|
|
1575
|
-
</svg>`;
|
|
1576
|
-
}
|
|
1577
|
-
|
|
1578
|
-
/**
|
|
1579
|
-
* Render any node (FRAME, GROUP, etc.) to SVG using its own size as the viewport.
|
|
1580
|
-
* Works for Design file frames, standalone components, or any node with a size field.
|
|
1581
|
-
*
|
|
1582
|
-
* Note: Figma's export expands bounds to include overflow content when a frame has
|
|
1583
|
-
* When frameMaskDisabled=true (clip content OFF), Figma's export expands the
|
|
1584
|
-
* bounds to include overflowing children. We replicate this by computing the
|
|
1585
|
-
* content bounding box and expanding the SVG viewport accordingly.
|
|
1586
|
-
*
|
|
1587
|
-
* @param {FigDeck} fig - Parsed Figma file (works with both .deck and .fig)
|
|
1588
|
-
* @param {object} node - The node to render (typically a FRAME)
|
|
1589
|
-
*/
|
|
1590
|
-
export function frameToSvg(fig, node) {
|
|
1591
|
-
_svgIdSeq = 0;
|
|
1592
|
-
_symbolDepth = 0;
|
|
1593
|
-
const fw = Math.round(node.size?.x ?? 100);
|
|
1594
|
-
const fh = Math.round(node.size?.y ?? 100);
|
|
1595
|
-
const body = childrenSvg(fig, node);
|
|
1596
|
-
|
|
1597
|
-
// Build background fill (supports solid, gradient, and image fills)
|
|
1598
|
-
const { defs: bgDefs, bg: bgSvg } = renderRoundedRectFillStack(fig, getFillPaints(node), fw, fh, 0);
|
|
1599
|
-
// Fallback to white rect if no visible fills
|
|
1600
|
-
const bgContent = bgSvg || `<rect x="0" y="0" width="${fw}" height="${fh}" fill="white"/>`;
|
|
1601
|
-
const defsBlock = bgDefs ? `${bgDefs}\n` : '';
|
|
1602
|
-
|
|
1603
|
-
// When clip content is OFF, expand viewport to include overflow.
|
|
1604
|
-
// Use fractional viewBox origin for exact positioning; ceil the total
|
|
1605
|
-
// coordinate range for pixel dimensions (matches Figma's export sizing).
|
|
1606
|
-
let vx = 0, vy = 0, w = fw, h = fh;
|
|
1607
|
-
if (node.frameMaskDisabled === true) {
|
|
1608
|
-
const bounds = _contentBounds(fig, node);
|
|
1609
|
-
vx = bounds.minX;
|
|
1610
|
-
vy = bounds.minY;
|
|
1611
|
-
w = Math.ceil(bounds.maxX - bounds.minX);
|
|
1612
|
-
h = Math.ceil(bounds.maxY - bounds.minY);
|
|
1613
|
-
}
|
|
1614
|
-
|
|
1615
|
-
return `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" \
|
|
1616
|
-
width="${w}" height="${h}" viewBox="${vx} ${vy} ${w} ${h}">
|
|
1617
|
-
${defsBlock}${bgContent}
|
|
1618
|
-
${body}
|
|
1619
|
-
</svg>`;
|
|
1620
|
-
}
|
|
1621
|
-
|
|
1622
|
-
/** Compute content bounding box of a node's children in the node's local space.
|
|
1623
|
-
* Recurses into INSTANCE→SYMBOL to catch overflow from scaled symbol children. */
|
|
1624
|
-
function _contentBounds(deck, node, depth = 2) {
|
|
1625
|
-
const fw = node.size?.x ?? 0;
|
|
1626
|
-
const fh = node.size?.y ?? 0;
|
|
1627
|
-
let minX = 0, minY = 0, maxX = fw, maxY = fh;
|
|
1628
|
-
|
|
1629
|
-
for (const child of deck.getChildren(nid(node))) {
|
|
1630
|
-
if (child.phase === 'REMOVED' || child.visible === false) continue;
|
|
1631
|
-
|
|
1632
|
-
const cx = child.transform?.m02 ?? 0;
|
|
1633
|
-
const cy = child.transform?.m12 ?? 0;
|
|
1634
|
-
const cw = child.size?.x ?? 0;
|
|
1635
|
-
const ch = child.size?.y ?? 0;
|
|
1636
|
-
|
|
1637
|
-
minX = Math.min(minX, cx);
|
|
1638
|
-
minY = Math.min(minY, cy);
|
|
1639
|
-
maxX = Math.max(maxX, cx + cw);
|
|
1640
|
-
maxY = Math.max(maxY, cy + ch);
|
|
1641
|
-
|
|
1642
|
-
// For INSTANCE nodes, check if symbol children overflow (scaled)
|
|
1643
|
-
if (depth > 0 && child.type === 'INSTANCE' && child.symbolData?.symbolID) {
|
|
1644
|
-
const symId = child.symbolData.symbolID;
|
|
1645
|
-
const sym = deck.getNode(`${symId.sessionID}:${symId.localID}`);
|
|
1646
|
-
if (sym) {
|
|
1647
|
-
const sw = sym.size?.x || cw;
|
|
1648
|
-
const sh = sym.size?.y || ch;
|
|
1649
|
-
const sx = cw / sw;
|
|
1650
|
-
const sy = ch / sh;
|
|
1651
|
-
const symBounds = _contentBounds(deck, sym, depth - 1);
|
|
1652
|
-
minX = Math.min(minX, cx + symBounds.minX * sx);
|
|
1653
|
-
minY = Math.min(minY, cy + symBounds.minY * sy);
|
|
1654
|
-
maxX = Math.max(maxX, cx + symBounds.maxX * sx);
|
|
1655
|
-
maxY = Math.max(maxY, cy + symBounds.maxY * sy);
|
|
1656
|
-
}
|
|
1657
|
-
}
|
|
1658
|
-
}
|
|
1659
|
-
|
|
1660
|
-
return { minX, minY, maxX, maxY };
|
|
1661
|
-
}
|
|
1
|
+
// Vendored from openfig-cli 0.6.0 (lib/rasterizer/svg-builder.mjs), MIT License — see LICENSE-openfig-cli.
|
|
2
|
+
// https://github.com/OpenFig-org/openfig-cli
|
|
3
|
+
// Local changes: helper imports inlined; image fills are read from the in-memory archive
|
|
4
|
+
// (deck.readImage) instead of an extracted images directory.
|
|
5
|
+
/**
|
|
6
|
+
* svg-builder.mjs — Convert a Figma node tree to an SVG string.
|
|
7
|
+
*
|
|
8
|
+
* Architecture: dispatcher pattern — each Figma node type maps to a render
|
|
9
|
+
* function. Unknown types emit a magenta placeholder rect so renders never
|
|
10
|
+
* crash. Add handlers incrementally as coverage grows.
|
|
11
|
+
*
|
|
12
|
+
* Parameter naming — two entry points, one shared engine:
|
|
13
|
+
*
|
|
14
|
+
* slideToSvg(deck, slideNode) — Slides entry point (.deck files)
|
|
15
|
+
* "deck" = a parsed .deck file. Expects SLIDE nodes, 1920×1080 viewport.
|
|
16
|
+
*
|
|
17
|
+
* frameToSvg(fig, node) — Design entry point (.fig files)
|
|
18
|
+
* "fig" = a parsed .fig file. Uses the node's own size as viewport.
|
|
19
|
+
*
|
|
20
|
+
* Internal render functions all accept "deck" for historical reasons,
|
|
21
|
+
* but they are format-agnostic — they work on any Figma node tree
|
|
22
|
+
* regardless of whether it came from a .deck or .fig file.
|
|
23
|
+
* Both formats share the same binary codec (canvas.fig inside a ZIP).
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { readFileSync } from 'fs';
|
|
27
|
+
import { join } from 'path';
|
|
28
|
+
import { extractRenderableGradientFill, parseVectorNetworkBlob, resolveGradientGeometry } from 'openfig-core';
|
|
29
|
+
const hashToHex = arr => Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
|
|
30
|
+
import { nodeId as nid } from 'openfig-core';
|
|
31
|
+
|
|
32
|
+
export const SLIDE_W = 1920;
|
|
33
|
+
export const SLIDE_H = 1080;
|
|
34
|
+
|
|
35
|
+
// Per-slide ID counter — reset at the start of each slideToSvg call so IDs are unique within each SVG doc
|
|
36
|
+
let _svgIdSeq = 0;
|
|
37
|
+
|
|
38
|
+
// Depth counter for SYMBOL rendering context. When > 0 we're inside a component
|
|
39
|
+
// tree and frame clipping is suppressed — Figma doesn't enforce child frame clips
|
|
40
|
+
// inside components whose root allows overflow (frameMaskDisabled=true).
|
|
41
|
+
let _symbolDepth = 0;
|
|
42
|
+
|
|
43
|
+
// ── Color helpers ─────────────────────────────────────────────────────────────
|
|
44
|
+
|
|
45
|
+
function cssColor(color, opacity = 1) {
|
|
46
|
+
const r = Math.round((color.r ?? 0) * 255);
|
|
47
|
+
const g = Math.round((color.g ?? 0) * 255);
|
|
48
|
+
const b = Math.round((color.b ?? 0) * 255);
|
|
49
|
+
const a = ((color.a ?? 1) * opacity).toFixed(4);
|
|
50
|
+
return `rgba(${r},${g},${b},${a})`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function resolveFill(fillPaints) {
|
|
54
|
+
if (!fillPaints?.length) return null;
|
|
55
|
+
const p = fillPaints.find(p => p.visible !== false && p.type === 'SOLID');
|
|
56
|
+
if (!p) return null;
|
|
57
|
+
return cssColor(p.color ?? {}, p.opacity ?? 1);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Generate an SVG gradient definition for a GRADIENT_LINEAR or GRADIENT_RADIAL paint.
|
|
61
|
+
* w, h = element dimensions in pixels (needed for userSpaceOnUse coordinates).
|
|
62
|
+
* Returns { defs: string, fill: string } where fill is 'url(#grad-N)'. */
|
|
63
|
+
function resolveGradientSvg(paint, w, h) {
|
|
64
|
+
const gradient = extractRenderableGradientFill([paint]);
|
|
65
|
+
if (!gradient) return null;
|
|
66
|
+
const geometry = resolveGradientGeometry(gradient, w, h);
|
|
67
|
+
if (!geometry) return null;
|
|
68
|
+
|
|
69
|
+
const id = `grad-${++_svgIdSeq}`;
|
|
70
|
+
const stops = gradient.stops.map(s => {
|
|
71
|
+
const color = cssColor(s.color ?? {});
|
|
72
|
+
return `<stop offset="${s.position}" stop-color="${color}"/>`;
|
|
73
|
+
}).join('');
|
|
74
|
+
const opacityAttr = gradient.opacity !== 1 ? ` opacity="${gradient.opacity}"` : '';
|
|
75
|
+
const f = v => +v.toFixed(2);
|
|
76
|
+
|
|
77
|
+
if (geometry.type === 'linear') {
|
|
78
|
+
return {
|
|
79
|
+
defs: `<linearGradient id="${id}" x1="${f(geometry.start.x)}" y1="${f(geometry.start.y)}" x2="${f(geometry.end.x)}" y2="${f(geometry.end.y)}" gradientUnits="userSpaceOnUse">${stops}</linearGradient>`,
|
|
80
|
+
fill: `url(#${id})`,
|
|
81
|
+
opacityAttr,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
const cx = f(geometry.center.x), cy = f(geometry.center.y);
|
|
85
|
+
const rx = f(geometry.radiusX), ry = f(geometry.radiusY);
|
|
86
|
+
const angle = f(geometry.angle * 180 / Math.PI);
|
|
87
|
+
return {
|
|
88
|
+
defs: `<radialGradient id="${id}" cx="${cx}" cy="${cy}" rx="${rx}" ry="${ry}" gradientUnits="userSpaceOnUse" gradientTransform="rotate(${angle},${cx},${cy})">${stops}</radialGradient>`,
|
|
89
|
+
fill: `url(#${id})`,
|
|
90
|
+
opacityAttr,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function appendDefs(defs, extra) {
|
|
95
|
+
if (!extra) return defs;
|
|
96
|
+
return defs
|
|
97
|
+
? defs.replace('</defs>', `${extra}</defs>`)
|
|
98
|
+
: `<defs>${extra}</defs>`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Get effective fillPaints for any node type. */
|
|
102
|
+
function getFillPaints(node) {
|
|
103
|
+
if (node.fillPaints?.length) return node.fillPaints;
|
|
104
|
+
// SHAPE_WITH_TEXT stores fill in nodeGenerationData.overrides[0].fillPaints
|
|
105
|
+
return node.nodeGenerationData?.overrides?.[0]?.fillPaints ?? null;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function strokeSpec(node) {
|
|
109
|
+
if (!node.strokeWeight || node.strokeWeight === 0) return null;
|
|
110
|
+
const color = resolveFill(node.strokePaints) ?? 'none';
|
|
111
|
+
if (color === 'none') return null;
|
|
112
|
+
return {
|
|
113
|
+
color,
|
|
114
|
+
width: node.strokeWeight,
|
|
115
|
+
align: node.strokeAlign ?? 'CENTER',
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Render strokeGeometry blobs as filled <path> elements (Figma's pre-expanded stroke outlines).
|
|
120
|
+
* Returns SVG string or '' if no strokeGeometry is available. */
|
|
121
|
+
function strokeGeometrySvg(deck, node) {
|
|
122
|
+
const strokeColor = resolveFill(node.strokePaints);
|
|
123
|
+
const sw = node.strokeWeight ?? 0;
|
|
124
|
+
const blobs = deck.message?.blobs;
|
|
125
|
+
if (!strokeColor || sw <= 0 || !node.strokeGeometry?.length || !blobs) return '';
|
|
126
|
+
const segments = [];
|
|
127
|
+
let hasEvenOdd = false;
|
|
128
|
+
for (const geo of node.strokeGeometry) {
|
|
129
|
+
const d = decodeCmdBlob(blobs, geo.commandsBlob);
|
|
130
|
+
if (d) segments.push(d);
|
|
131
|
+
if (geo.windingRule === 'EVENODD') hasEvenOdd = true;
|
|
132
|
+
}
|
|
133
|
+
if (!segments.length) return '';
|
|
134
|
+
const rule = (segments.length > 1 || hasEvenOdd) ? ' fill-rule="evenodd"' : '';
|
|
135
|
+
return `<path d="${segments.join('')}" fill="${strokeColor}"${rule}/>`;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function rectStrokeSvg(x, y, w, h, rx, stroke) {
|
|
139
|
+
if (!stroke) return '';
|
|
140
|
+
let sx = x;
|
|
141
|
+
let sy = y;
|
|
142
|
+
let sw = w;
|
|
143
|
+
let sh = h;
|
|
144
|
+
let srx = Math.min(rx, w / 2, h / 2);
|
|
145
|
+
|
|
146
|
+
if (stroke.align === 'INSIDE') {
|
|
147
|
+
sx += stroke.width / 2;
|
|
148
|
+
sy += stroke.width / 2;
|
|
149
|
+
sw -= stroke.width;
|
|
150
|
+
sh -= stroke.width;
|
|
151
|
+
srx = Math.max(0, srx - stroke.width / 2);
|
|
152
|
+
} else if (stroke.align === 'OUTSIDE') {
|
|
153
|
+
sx -= stroke.width / 2;
|
|
154
|
+
sy -= stroke.width / 2;
|
|
155
|
+
sw += stroke.width;
|
|
156
|
+
sh += stroke.width;
|
|
157
|
+
srx += stroke.width / 2;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (sw <= 0 || sh <= 0) return '';
|
|
161
|
+
return `<rect x="${sx}" y="${sy}" width="${sw}" height="${sh}" rx="${srx}" ry="${srx}" fill="none" stroke="${stroke.color}" stroke-width="${stroke.width}"/>`;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function ellipseStrokeSvg(cx, cy, rx, ry, stroke) {
|
|
165
|
+
if (!stroke) return '';
|
|
166
|
+
let srx = rx;
|
|
167
|
+
let sry = ry;
|
|
168
|
+
|
|
169
|
+
if (stroke.align === 'INSIDE') {
|
|
170
|
+
srx -= stroke.width / 2;
|
|
171
|
+
sry -= stroke.width / 2;
|
|
172
|
+
} else if (stroke.align === 'OUTSIDE') {
|
|
173
|
+
srx += stroke.width / 2;
|
|
174
|
+
sry += stroke.width / 2;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (srx <= 0 || sry <= 0) return '';
|
|
178
|
+
return `<ellipse cx="${cx}" cy="${cy}" rx="${srx}" ry="${sry}" fill="none" stroke="${stroke.color}" stroke-width="${stroke.width}"/>`;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// ── Transform helpers ─────────────────────────────────────────────────────────
|
|
182
|
+
|
|
183
|
+
/** Return the full SVG transform attribute value for a node.
|
|
184
|
+
* Uses `translate(x,y)` for pure translations, `matrix(a,b,c,d,e,f)` when
|
|
185
|
+
* rotation or scale is present. */
|
|
186
|
+
function svgTransform(node) {
|
|
187
|
+
const t = node.transform;
|
|
188
|
+
if (!t) return 'translate(0,0)';
|
|
189
|
+
const m00 = t.m00 ?? 1, m01 = t.m01 ?? 0, m02 = t.m02 ?? 0;
|
|
190
|
+
const m10 = t.m10 ?? 0, m11 = t.m11 ?? 1, m12 = t.m12 ?? 0;
|
|
191
|
+
// Pure translation — no rotation or scale
|
|
192
|
+
if (Math.abs(m00 - 1) < 1e-6 && Math.abs(m01) < 1e-6 &&
|
|
193
|
+
Math.abs(m10) < 1e-6 && Math.abs(m11 - 1) < 1e-6) {
|
|
194
|
+
return `translate(${m02},${m12})`;
|
|
195
|
+
}
|
|
196
|
+
// Use high precision for rotation/scale — 2dp on a 2000px element = ~8px error
|
|
197
|
+
const h = v => +v.toFixed(6);
|
|
198
|
+
return `matrix(${h(m00)},${h(m10)},${h(m01)},${h(m11)},${f(m02)},${f(m12)})`;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function size(node) {
|
|
202
|
+
return { w: node.size?.x ?? 0, h: node.size?.y ?? 0 };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ── Node renderers ────────────────────────────────────────────────────────────
|
|
206
|
+
|
|
207
|
+
function renderRect(deck, node) {
|
|
208
|
+
const { w, h } = size(node);
|
|
209
|
+
const rx = Math.min(node.cornerRadius ?? 0, w / 2, h / 2);
|
|
210
|
+
const { defs, bg } = renderRoundedRectFillStack(deck, getFillPaints(node), w, h, rx);
|
|
211
|
+
const fillSvg = bg ? `${[defs, bg].filter(Boolean).join('\n')}` : '';
|
|
212
|
+
// Prefer strokeGeometry (Figma's pre-computed outline) for matching anti-aliasing.
|
|
213
|
+
// strokeGeometry is CENTER-aligned — render underneath fill so fill covers inner half.
|
|
214
|
+
const geoStroke = strokeGeometrySvg(deck, node);
|
|
215
|
+
const strokeSvg = geoStroke || rectStrokeSvg(0, 0, w, h, rx, strokeSpec(node));
|
|
216
|
+
// Stroke underneath, fill on top (hides inner half for OUTSIDE strokes)
|
|
217
|
+
const inner = geoStroke
|
|
218
|
+
? [strokeSvg, fillSvg].filter(Boolean).join('\n')
|
|
219
|
+
: [fillSvg, strokeSvg].filter(Boolean).join('\n');
|
|
220
|
+
if (!inner) return '';
|
|
221
|
+
return `<g transform="${svgTransform(node)}">\n${inner}\n</g>`;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function renderEllipse(deck, node) {
|
|
225
|
+
const { w, h } = size(node);
|
|
226
|
+
const fill = resolveFill(getFillPaints(node)) ?? 'none';
|
|
227
|
+
// Local coordinates — svgTransform handles position + rotation
|
|
228
|
+
const cx = w / 2;
|
|
229
|
+
const cy = h / 2;
|
|
230
|
+
const rx = w / 2;
|
|
231
|
+
const ry = h / 2;
|
|
232
|
+
const fillSvg = `<ellipse cx="${cx}" cy="${cy}" rx="${rx}" ry="${ry}" fill="${fill}"/>`;
|
|
233
|
+
// Prefer strokeGeometry (Figma's pre-computed outline) for matching anti-aliasing.
|
|
234
|
+
// strokeGeometry is CENTER-aligned — render underneath fill so fill covers inner half.
|
|
235
|
+
const geoStroke = strokeGeometrySvg(deck, node);
|
|
236
|
+
const strokeSvg = geoStroke || ellipseStrokeSvg(cx, cy, rx, ry, strokeSpec(node));
|
|
237
|
+
// Stroke underneath, fill on top (hides inner half for OUTSIDE strokes)
|
|
238
|
+
const inner = geoStroke
|
|
239
|
+
? [strokeSvg, fillSvg].filter(Boolean).join('\n')
|
|
240
|
+
: [fillSvg, strokeSvg].filter(Boolean).join('\n');
|
|
241
|
+
return `<g transform="${svgTransform(node)}">\n${inner}\n</g>`;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function resolveLineHeight(lh, fontSize) {
|
|
245
|
+
if (!lh) return fontSize * 1.2;
|
|
246
|
+
switch (lh.units) {
|
|
247
|
+
case 'RAW': return lh.value * fontSize;
|
|
248
|
+
case 'PERCENT': return (lh.value / 100) * fontSize;
|
|
249
|
+
case 'PIXELS': return lh.value;
|
|
250
|
+
default: return fontSize * 1.2;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// ── Text width approximation (Inter-like proportional metrics) ──────────────
|
|
255
|
+
//
|
|
256
|
+
// Used only when wrapping text in the fallback layout path (no derivedTextData,
|
|
257
|
+
// e.g. programmatically-generated text). Values are expressed as a fraction of
|
|
258
|
+
// fontSize and tuned for Inter Regular — close enough for word-wrap decisions.
|
|
259
|
+
const _NARROW = new Set('iIlt.,:;!|\'`"()[]{}/\\'.split(''));
|
|
260
|
+
const _WIDE = new Set('ABCDEFGHJKLNOPQRSTUVXYZmw'.split(''));
|
|
261
|
+
const _XWIDE = new Set('MW@%'.split(''));
|
|
262
|
+
function approxCharWidth(ch, fontSize) {
|
|
263
|
+
if (ch === ' ') return fontSize * 0.28;
|
|
264
|
+
if (_NARROW.has(ch)) return fontSize * 0.28;
|
|
265
|
+
if (_XWIDE.has(ch)) return fontSize * 0.85;
|
|
266
|
+
if (_WIDE.has(ch)) return fontSize * 0.66;
|
|
267
|
+
return fontSize * 0.52; // default for lowercase + digits + punctuation
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function approxTextWidth(str, fontSize, letterSpacingPx = 0) {
|
|
271
|
+
let w = 0;
|
|
272
|
+
for (let i = 0; i < str.length; i++) w += approxCharWidth(str[i], fontSize);
|
|
273
|
+
if (str.length > 1) w += letterSpacingPx * (str.length - 1);
|
|
274
|
+
return w;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Word-wrap a single line into multiple lines that each fit within maxWidth.
|
|
279
|
+
* Breaks on ASCII spaces only. If a single "word" overflows maxWidth it is
|
|
280
|
+
* placed on its own line (no mid-word break).
|
|
281
|
+
* @param {string} line
|
|
282
|
+
* @param {number} fontSize
|
|
283
|
+
* @param {number} maxWidth
|
|
284
|
+
* @param {number} letterSpacingPx
|
|
285
|
+
* @returns {string[]}
|
|
286
|
+
*/
|
|
287
|
+
function wrapLineByWidth(line, fontSize, maxWidth, letterSpacingPx = 0) {
|
|
288
|
+
if (!line) return [line];
|
|
289
|
+
if (!(maxWidth > 0)) return [line];
|
|
290
|
+
if (approxTextWidth(line, fontSize, letterSpacingPx) <= maxWidth) return [line];
|
|
291
|
+
const words = line.split(' ');
|
|
292
|
+
const out = [];
|
|
293
|
+
let cur = '';
|
|
294
|
+
for (const word of words) {
|
|
295
|
+
const candidate = cur ? cur + ' ' + word : word;
|
|
296
|
+
if (approxTextWidth(candidate, fontSize, letterSpacingPx) <= maxWidth || !cur) {
|
|
297
|
+
cur = candidate;
|
|
298
|
+
} else {
|
|
299
|
+
out.push(cur);
|
|
300
|
+
cur = word;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
if (cur) out.push(cur);
|
|
304
|
+
return out;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function esc(s) {
|
|
308
|
+
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Detect stale derivedTextData: text was edited outside Figma but glyph layout
|
|
313
|
+
* wasn't recomputed. Returns true when the layout clearly doesn't match the text.
|
|
314
|
+
*/
|
|
315
|
+
function isStaleLayout(chars, baselines, glyphs) {
|
|
316
|
+
if (!chars) return false;
|
|
317
|
+
// No derivedTextData at all (e.g. programmatically created text)
|
|
318
|
+
if (!baselines?.length && !glyphs?.length) return true;
|
|
319
|
+
const len = chars.length;
|
|
320
|
+
|
|
321
|
+
if (baselines?.length) {
|
|
322
|
+
const lastEnd = baselines[baselines.length - 1]?.endCharacter;
|
|
323
|
+
// baselines endCharacter should match chars length (±1 for trailing newline)
|
|
324
|
+
if (lastEnd != null && Math.abs(lastEnd - len) > 1) return true;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
if (glyphs?.length) {
|
|
328
|
+
const maxFirstChar = glyphs.reduce((max, g) =>
|
|
329
|
+
Math.max(max, g.firstCharacter ?? 0), 0);
|
|
330
|
+
if (maxFirstChar >= len) return true; // glyphs point beyond new text
|
|
331
|
+
if (len > maxFirstChar + 3) return true; // new text much longer than glyph coverage
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
return false;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Fallback text layout for stale derivedTextData.
|
|
339
|
+
* Emits line-level <tspan> elements and lets resvg handle per-glyph layout.
|
|
340
|
+
* Uses original baseline metrics (line height, ascent, position) where available
|
|
341
|
+
* since those are style-dependent, not content-dependent.
|
|
342
|
+
* Auto-scales font size down when new text is longer than the original.
|
|
343
|
+
* Returns { tspans, fontSize } so the caller can use the adjusted size.
|
|
344
|
+
*/
|
|
345
|
+
function fallbackTextTspans(dispChars, fontSize, node, letterSpacingPx = 0) {
|
|
346
|
+
const baselines = node.derivedTextData?.baselines;
|
|
347
|
+
const rawLines = dispChars.split('\n');
|
|
348
|
+
// Drop trailing empty line from trailing newline
|
|
349
|
+
if (rawLines.length > 1 && !rawLines[rawLines.length - 1]) rawLines.pop();
|
|
350
|
+
|
|
351
|
+
// Use original baseline metrics for spacing (style property, still valid).
|
|
352
|
+
// When baselines are absent (programmatically-generated text), honour the
|
|
353
|
+
// node's own lineHeight (RAW/PERCENT/PIXELS) rather than falling back to
|
|
354
|
+
// a hard-coded 1.2× multiplier, so hand-authored lineHeight values render
|
|
355
|
+
// correctly. Ultimate default 1.25× per spec.
|
|
356
|
+
const lhFromNode = node.lineHeight ? resolveLineHeight(node.lineHeight, fontSize) : null;
|
|
357
|
+
let lineHeightPx = baselines?.[0]?.lineHeight ?? lhFromNode ?? fontSize * 1.25;
|
|
358
|
+
let lineAscent = baselines?.[0]?.lineAscent ?? fontSize * 0.8;
|
|
359
|
+
|
|
360
|
+
// Auto-fit: scale font size down when new text is longer than original.
|
|
361
|
+
// Uses character count ratio per line as a proxy for width ratio.
|
|
362
|
+
const nodeW = node.size?.x ?? 1920;
|
|
363
|
+
const nodeH = node.size?.y ?? 0;
|
|
364
|
+
let scale = 1;
|
|
365
|
+
if (baselines?.length) {
|
|
366
|
+
const maxOrigCharsPerLine = Math.max(...baselines.map(b =>
|
|
367
|
+
Math.max(0, (b.endCharacter ?? 0) - (b.firstCharacter ?? 0))));
|
|
368
|
+
const maxNewCharsPerLine = Math.max(...rawLines.map(l => l.length));
|
|
369
|
+
|
|
370
|
+
// Scale down if widest new line has more chars than widest original line
|
|
371
|
+
if (maxNewCharsPerLine > maxOrigCharsPerLine && maxOrigCharsPerLine > 0) {
|
|
372
|
+
scale = Math.min(scale, maxOrigCharsPerLine / maxNewCharsPerLine);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// Also scale down if more lines than original (would overflow vertically)
|
|
376
|
+
if (rawLines.length > baselines.length && nodeH > 0) {
|
|
377
|
+
scale = Math.min(scale, baselines.length / rawLines.length);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
scale = Math.max(scale, 0.15); // don't shrink below 15%
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
const adjFontSize = fontSize * scale;
|
|
384
|
+
const adjLineHeight = lineHeightPx * scale;
|
|
385
|
+
const adjLineAscent = lineAscent * scale;
|
|
386
|
+
const adjLetterSpacingPx = letterSpacingPx * scale;
|
|
387
|
+
|
|
388
|
+
// Horizontal alignment → text-anchor + x position
|
|
389
|
+
const align = node.textAlignHorizontal ?? 'LEFT';
|
|
390
|
+
const anchor = align === 'CENTER' ? 'middle' : align === 'RIGHT' ? 'end' : 'start';
|
|
391
|
+
const anchorX = align === 'CENTER' ? nodeW / 2 : align === 'RIGHT' ? nodeW : 0;
|
|
392
|
+
|
|
393
|
+
// Use first baseline position if available (preserves Figma's padding/offset),
|
|
394
|
+
// otherwise compute from vertical alignment
|
|
395
|
+
let startX, startY;
|
|
396
|
+
if (baselines?.[0]?.position) {
|
|
397
|
+
startX = align === 'LEFT' ? baselines[0].position.x : anchorX;
|
|
398
|
+
// Scale startY relative to the baseline position for auto-fit
|
|
399
|
+
startY = baselines[0].position.y * scale;
|
|
400
|
+
} else {
|
|
401
|
+
startX = anchorX;
|
|
402
|
+
const vAlign = node.textAlignVertical ?? 'TOP';
|
|
403
|
+
// Placeholder; recomputed below once we know the wrapped line count.
|
|
404
|
+
startY = adjLineAscent;
|
|
405
|
+
// Mark that we need to recompute after word-wrap based on final line count
|
|
406
|
+
// (kept here for readability — actual recompute below).
|
|
407
|
+
if (vAlign !== 'TOP') startY = null;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// Word-wrap each hard-newline-delimited line to fit within the node's width.
|
|
411
|
+
// Only wrap when the node has an explicit size.x and ≥1 hard line overflows.
|
|
412
|
+
// Preserves alignment via the outer text-anchor/startX logic.
|
|
413
|
+
const lineType0 = null;
|
|
414
|
+
const linesMeta = node.textData?.lines ?? [];
|
|
415
|
+
// Interpret each rawLine and wrap — track (text, metaIndex) for each output line
|
|
416
|
+
const wrapped = []; // array of { text, metaIndex }
|
|
417
|
+
for (let i = 0; i < rawLines.length; i++) {
|
|
418
|
+
const rawLine = rawLines[i];
|
|
419
|
+
// Reserve horizontal space consumed by list marker + indent on this meta line
|
|
420
|
+
const meta = linesMeta[i];
|
|
421
|
+
const indent = (meta?.indentationLevel ?? 0) * adjFontSize * 0.8;
|
|
422
|
+
const effectiveMaxW = Math.max(0, nodeW - indent);
|
|
423
|
+
const pieces = wrapLineByWidth(rawLine, adjFontSize, effectiveMaxW, adjLetterSpacingPx);
|
|
424
|
+
for (const piece of pieces) wrapped.push({ text: piece, metaIndex: i });
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// Recompute startY for non-TOP vertical alignment now that we know final line count
|
|
428
|
+
if (startY === null) {
|
|
429
|
+
const totalH = wrapped.length * adjLineHeight;
|
|
430
|
+
const nodeHH = node.size?.y ?? totalH;
|
|
431
|
+
const vAlign = node.textAlignVertical ?? 'TOP';
|
|
432
|
+
startY = vAlign === 'CENTER' ? (nodeHH - totalH) / 2 + adjLineAscent
|
|
433
|
+
: vAlign === 'BOTTOM' ? nodeHH - totalH + adjLineAscent
|
|
434
|
+
: adjLineAscent;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// List marker support: read lineType from textData.lines. Only apply marker
|
|
438
|
+
// to the first visual line of a wrapped paragraph.
|
|
439
|
+
let orderedCounter = 0;
|
|
440
|
+
let lastMetaIdx = -1;
|
|
441
|
+
|
|
442
|
+
const tspans = wrapped.map(({ text, metaIndex }, i) => {
|
|
443
|
+
const y = startY + i * adjLineHeight;
|
|
444
|
+
const meta = linesMeta[metaIndex];
|
|
445
|
+
const lineType = meta?.lineType;
|
|
446
|
+
const indent = (meta?.indentationLevel ?? 0) * adjFontSize * 0.8;
|
|
447
|
+
let prefix = '';
|
|
448
|
+
const isFirstVisualOfMeta = metaIndex !== lastMetaIdx;
|
|
449
|
+
if (isFirstVisualOfMeta) {
|
|
450
|
+
if (lineType === 'UNORDERED_LIST') {
|
|
451
|
+
prefix = '\u2022 '; // bullet •
|
|
452
|
+
orderedCounter = 0;
|
|
453
|
+
} else if (lineType === 'ORDERED_LIST') {
|
|
454
|
+
orderedCounter++;
|
|
455
|
+
prefix = `${orderedCounter}. `;
|
|
456
|
+
} else {
|
|
457
|
+
orderedCounter = 0;
|
|
458
|
+
}
|
|
459
|
+
lastMetaIdx = metaIndex;
|
|
460
|
+
}
|
|
461
|
+
const x = startX + indent;
|
|
462
|
+
return `<tspan x="${x.toFixed(2)}" y="${y.toFixed(2)}" text-anchor="${anchor}">${esc(prefix + text) || ' '}</tspan>`;
|
|
463
|
+
}).join('');
|
|
464
|
+
|
|
465
|
+
return { tspans, fontSize: adjFontSize };
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function styleAttrsFromFontName(fontName, derivedFontWeight) {
|
|
469
|
+
const style = fontName?.style ?? 'Regular';
|
|
470
|
+
const weight = derivedFontWeight
|
|
471
|
+
? String(derivedFontWeight)
|
|
472
|
+
: /semibold/i.test(style) ? '600'
|
|
473
|
+
: /bold/i.test(style) ? '700'
|
|
474
|
+
: /medium/i.test(style) ? '500'
|
|
475
|
+
: '400';
|
|
476
|
+
const italic = /italic/i.test(style) ? 'italic' : 'normal';
|
|
477
|
+
return { weight, italic };
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
function glyphSlice(chars, glyphs, index) {
|
|
481
|
+
const g = glyphs[index];
|
|
482
|
+
if (g.firstCharacter == null) {
|
|
483
|
+
throw new Error('Unexpected glyph without firstCharacter');
|
|
484
|
+
}
|
|
485
|
+
let nextChar = null;
|
|
486
|
+
for (let j = index + 1; j < glyphs.length; j++) {
|
|
487
|
+
const fc = glyphs[j].firstCharacter;
|
|
488
|
+
if (fc != null && fc > g.firstCharacter) {
|
|
489
|
+
nextChar = fc;
|
|
490
|
+
break;
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
return chars.slice(g.firstCharacter, nextChar ?? (g.firstCharacter + 1));
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
function renderText(deck, node) {
|
|
497
|
+
const chars = node.textData?.characters ?? '';
|
|
498
|
+
if (!chars.trim()) return '';
|
|
499
|
+
const dispChars = node.textCase === 'UPPER' ? chars.toUpperCase()
|
|
500
|
+
: node.textCase === 'LOWER' ? chars.toLowerCase()
|
|
501
|
+
: chars;
|
|
502
|
+
|
|
503
|
+
let fontSize = node.derivedTextData?.glyphs?.[0]?.fontSize ?? node.fontSize ?? 24;
|
|
504
|
+
const fontFamily = node.fontName?.family ?? 'Inter';
|
|
505
|
+
const fill = resolveFill(getFillPaints(node)) ?? '#000000';
|
|
506
|
+
// Letter spacing: PERCENT is % of fontSize, PIXELS is absolute
|
|
507
|
+
const ls = node.letterSpacing;
|
|
508
|
+
let letterSpacingPx = !ls ? 0
|
|
509
|
+
: ls.units === 'PERCENT' ? (ls.value / 100) * fontSize
|
|
510
|
+
: ls.units === 'PIXELS' ? ls.value
|
|
511
|
+
: 0;
|
|
512
|
+
const baselines = node.derivedTextData?.baselines;
|
|
513
|
+
const glyphs = node.derivedTextData?.glyphs;
|
|
514
|
+
const styleIds = node.textData?.characterStyleIDs;
|
|
515
|
+
const styleTable = node.textData?.styleOverrideTable;
|
|
516
|
+
const stale = isStaleLayout(chars, baselines, glyphs);
|
|
517
|
+
if (!glyphs?.length && !stale) {
|
|
518
|
+
throw new Error(`TEXT ${node.name ?? nid(node)} is missing derived glyph layout`);
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// Build styleID → {weight, italic, decoration, family} map
|
|
522
|
+
const styleMap = {};
|
|
523
|
+
if (styleIds && styleTable) {
|
|
524
|
+
for (const ov of styleTable) {
|
|
525
|
+
// Only override weight/italic/family if fontName is explicitly set in this style run
|
|
526
|
+
const hasFontName = ov.fontName?.family || ov.fontName?.style;
|
|
527
|
+
const { weight, italic } = hasFontName ? styleAttrsFromFontName(ov.fontName, null) : {};
|
|
528
|
+
styleMap[ov.styleID] = {
|
|
529
|
+
family: hasFontName ? (ov.fontName?.family ?? fontFamily) : null,
|
|
530
|
+
weight: hasFontName ? weight : null, // null → fall through to defWeight
|
|
531
|
+
italic: hasFontName ? italic : null, // null → fall through to defItalic
|
|
532
|
+
decoration: ov.textDecoration === 'UNDERLINE' ? 'underline' : 'none',
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// Node-level defaults
|
|
538
|
+
const { weight: defWeight, italic: defItalic } = styleAttrsFromFontName(
|
|
539
|
+
node.fontName, node.derivedTextData?.fontMetaData?.[0]?.fontWeight
|
|
540
|
+
);
|
|
541
|
+
|
|
542
|
+
// Per-glyph positioning with ligature merging: each character gets its own
|
|
543
|
+
// <tspan> with Figma's x,y, EXCEPT known ligature sequences (fi, fl, ff,
|
|
544
|
+
// ffi, ffl) which are merged into a single <tspan> positioned at the first
|
|
545
|
+
// glyph so the font engine can substitute the ligature glyph.
|
|
546
|
+
const LIGATURES = ['ffl', 'ffi', 'ff', 'fi', 'fl'];
|
|
547
|
+
|
|
548
|
+
/** Check if a ligature starts at position i in the display string.
|
|
549
|
+
* Returns the ligature length or 0. */
|
|
550
|
+
function ligatureAt(i) {
|
|
551
|
+
for (const lig of LIGATURES) {
|
|
552
|
+
if (dispChars.slice(i, i + lig.length) === lig) return lig.length;
|
|
553
|
+
}
|
|
554
|
+
return 0;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
let tspans = '';
|
|
558
|
+
if (stale || !glyphs?.length) {
|
|
559
|
+
// Fallback: derivedTextData is stale (text was edited outside Figma).
|
|
560
|
+
// Emit line-level tspans and let resvg handle per-glyph layout.
|
|
561
|
+
const origFontSize = fontSize;
|
|
562
|
+
const fb = fallbackTextTspans(dispChars, fontSize, node, letterSpacingPx);
|
|
563
|
+
tspans = fb.tspans;
|
|
564
|
+
fontSize = fb.fontSize; // auto-fit may have scaled down
|
|
565
|
+
if (origFontSize > 0) letterSpacingPx *= fontSize / origFontSize;
|
|
566
|
+
} else if (baselines?.length && glyphs?.length && styleIds?.length) {
|
|
567
|
+
// Mixed-style: group consecutive glyphs by styleID, emit per-glyph with ligature merge
|
|
568
|
+
for (const b of baselines) {
|
|
569
|
+
const lineGlyphs = glyphs.filter(g => g.firstCharacter >= b.firstCharacter && g.firstCharacter < b.endCharacter);
|
|
570
|
+
if (!lineGlyphs.length) continue;
|
|
571
|
+
|
|
572
|
+
const runs = [];
|
|
573
|
+
let curRun = null;
|
|
574
|
+
for (const g of lineGlyphs) {
|
|
575
|
+
const sid = styleIds[g.firstCharacter] ?? 0;
|
|
576
|
+
if (!curRun || sid !== curRun.sid) {
|
|
577
|
+
curRun = { sid, glyphs: [] };
|
|
578
|
+
runs.push(curRun);
|
|
579
|
+
}
|
|
580
|
+
curRun.glyphs.push(g);
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
for (const run of runs) {
|
|
584
|
+
const st = styleMap[run.sid] ?? {};
|
|
585
|
+
const w = st.weight ?? defWeight;
|
|
586
|
+
const it = st.italic ?? defItalic;
|
|
587
|
+
const fam = st.family ?? fontFamily;
|
|
588
|
+
for (let gi = 0; gi < run.glyphs.length; gi++) {
|
|
589
|
+
const g = run.glyphs[gi];
|
|
590
|
+
const ligLen = ligatureAt(g.firstCharacter);
|
|
591
|
+
const span = ligLen > 1 ? ligLen : 1;
|
|
592
|
+
const endIdx = gi + span < run.glyphs.length
|
|
593
|
+
? run.glyphs[gi + span].firstCharacter
|
|
594
|
+
: Math.min((run.glyphs[run.glyphs.length - 1].firstCharacter + 1), b.endCharacter);
|
|
595
|
+
const slice = dispChars.slice(g.firstCharacter, endIdx).replace(/\n$/, '');
|
|
596
|
+
if (!slice || /^\s+$/.test(slice)) continue;
|
|
597
|
+
tspans += `<tspan x="${g.position.x}" y="${g.position.y}" font-family="${fam}, sans-serif" font-weight="${w}" font-style="${it}">${esc(slice)}</tspan>`;
|
|
598
|
+
if (span > 1) gi += span - 1; // skip merged glyphs
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
} else if (glyphs?.length) {
|
|
603
|
+
// Per-glyph positioning with ligature merging
|
|
604
|
+
for (let i = 0; i < glyphs.length; i++) {
|
|
605
|
+
const g = glyphs[i];
|
|
606
|
+
const ligLen = ligatureAt(g.firstCharacter);
|
|
607
|
+
const span = ligLen > 1 ? ligLen : 1;
|
|
608
|
+
const endIdx = i + span < glyphs.length
|
|
609
|
+
? glyphs[i + span].firstCharacter
|
|
610
|
+
: chars.length;
|
|
611
|
+
const slice = dispChars.slice(g.firstCharacter, endIdx).replace(/\n$/, '');
|
|
612
|
+
if (!slice || /^\s+$/.test(slice)) { continue; }
|
|
613
|
+
tspans += `<tspan x="${g.position.x}" y="${g.position.y}">${esc(slice)}</tspan>`;
|
|
614
|
+
if (span > 1) i += span - 1; // skip merged glyphs
|
|
615
|
+
}
|
|
616
|
+
} else if (baselines?.length) {
|
|
617
|
+
tspans = baselines.map(b => {
|
|
618
|
+
const slice = dispChars.slice(b.firstCharacter, b.endCharacter).replace(/\n$/, '');
|
|
619
|
+
return `<tspan x="${b.position.x}" y="${b.position.y}">${esc(slice) || ' '}</tspan>`;
|
|
620
|
+
}).join('');
|
|
621
|
+
} else {
|
|
622
|
+
throw new Error(`TEXT ${node.name ?? nid(node)} is missing derived baselines`);
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
const lsAttr = letterSpacingPx === 0 ? '' : ` letter-spacing="${letterSpacingPx.toFixed(3)}"`;
|
|
626
|
+
|
|
627
|
+
const textEl = [
|
|
628
|
+
`<text font-size="${fontSize}" font-family="${fontFamily}, sans-serif"`,
|
|
629
|
+
` font-weight="${defWeight}" font-style="${defItalic}" fill="${fill}"${lsAttr}`,
|
|
630
|
+
` text-rendering="geometricPrecision">${tspans}</text>`,
|
|
631
|
+
].join('\n');
|
|
632
|
+
|
|
633
|
+
// Use Figma's pre-computed decoration rectangles (underline/strikethrough).
|
|
634
|
+
// derivedTextData.decorations[].rects are relative to the node's local origin.
|
|
635
|
+
const decorations = node.derivedTextData?.decorations ?? [];
|
|
636
|
+
if (!decorations.length) return `<g transform="${svgTransform(node)}">\n${textEl}\n</g>`;
|
|
637
|
+
const decorationRects = decorations.flatMap(d =>
|
|
638
|
+
(d.rects ?? []).map(r =>
|
|
639
|
+
`<rect x="${r.x.toFixed(2)}" y="${r.y.toFixed(2)}" width="${r.w.toFixed(2)}" height="${r.h.toFixed(2)}" fill="${fill}"/>`
|
|
640
|
+
)
|
|
641
|
+
);
|
|
642
|
+
const inner = decorationRects.length ? textEl + '\n' + decorationRects.join('\n') : textEl;
|
|
643
|
+
return `<g transform="${svgTransform(node)}">\n${inner}\n</g>`;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* Resolve an IMAGE-type fillPaint to inline SVG defs + bg element.
|
|
648
|
+
* Supports FILL (cover), FIT (contain), and TILE scale modes.
|
|
649
|
+
* Throws if the image file cannot be read.
|
|
650
|
+
*/
|
|
651
|
+
function resolveImageFillSvg(deck, imgFill, w, h, rx) {
|
|
652
|
+
const hashBytes = imgFill.image?.hash;
|
|
653
|
+
const hash = hashBytes?.length ? hashToHex(hashBytes) : imgFill.image?.name;
|
|
654
|
+
if (!hash) throw new Error('Visible IMAGE fill is missing its asset hash');
|
|
655
|
+
const buf = deck.readImage(hash);
|
|
656
|
+
if (!buf) throw new Error(`Missing image fill asset ${hash}`);
|
|
657
|
+
|
|
658
|
+
const mime = (buf[0] === 0xFF && buf[1] === 0xD8) ? 'image/jpeg' : 'image/png';
|
|
659
|
+
const dataUri = `data:${mime};base64,${buf.toString('base64')}`;
|
|
660
|
+
const id = ++_svgIdSeq;
|
|
661
|
+
const clipId = `img-clip-${id}`;
|
|
662
|
+
const clipDef = `<clipPath id="${clipId}"><rect width="${w}" height="${h}" rx="${rx}" ry="${rx}"/></clipPath>`;
|
|
663
|
+
const mode = imgFill.imageScaleMode ?? 'FILL';
|
|
664
|
+
const opacityAttr = (imgFill.opacity ?? 1) !== 1 ? ` opacity="${imgFill.opacity}"` : '';
|
|
665
|
+
|
|
666
|
+
if (mode === 'TILE') {
|
|
667
|
+
const tw = (imgFill.originalImageWidth ?? 100) * (imgFill.scale ?? 1);
|
|
668
|
+
const th = (imgFill.originalImageHeight ?? 100) * (imgFill.scale ?? 1);
|
|
669
|
+
const patId = `img-pat-${id}`;
|
|
670
|
+
return {
|
|
671
|
+
defs: `${clipDef}<pattern id="${patId}" x="0" y="0" width="${tw}" height="${th}" patternUnits="userSpaceOnUse"><image href="${dataUri}" width="${tw}" height="${th}"${opacityAttr}/></pattern>`,
|
|
672
|
+
bg: `<rect x="0" y="0" width="${w}" height="${h}" rx="${rx}" ry="${rx}" fill="url(#${patId})" clip-path="url(#${clipId})"/>`,
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
if (mode === 'STRETCH') {
|
|
677
|
+
const t = imgFill.transform;
|
|
678
|
+
const ow = imgFill.originalImageWidth ?? 0;
|
|
679
|
+
const oh = imgFill.originalImageHeight ?? 0;
|
|
680
|
+
const axisAligned = t
|
|
681
|
+
&& Math.abs(t.m01 ?? 0) < 1e-9
|
|
682
|
+
&& Math.abs(t.m10 ?? 0) < 1e-9
|
|
683
|
+
&& t.m00 > 0
|
|
684
|
+
&& t.m11 > 0
|
|
685
|
+
&& ow > 0
|
|
686
|
+
&& oh > 0;
|
|
687
|
+
if (axisAligned) {
|
|
688
|
+
const cropX = t.m02 * ow;
|
|
689
|
+
const cropY = t.m12 * oh;
|
|
690
|
+
const cropW = t.m00 * ow;
|
|
691
|
+
const cropH = t.m11 * oh;
|
|
692
|
+
const scaleX = w / cropW;
|
|
693
|
+
const scaleY = h / cropH;
|
|
694
|
+
return {
|
|
695
|
+
defs: clipDef,
|
|
696
|
+
bg: `<image href="${dataUri}" x="${-cropX * scaleX}" y="${-cropY * scaleY}" `
|
|
697
|
+
+ `width="${ow * scaleX}" height="${oh * scaleY}" preserveAspectRatio="none" `
|
|
698
|
+
+ `clip-path="url(#${clipId})"${opacityAttr}/>`,
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
// FILL (cover) or FIT (contain), plus a safe fallback for an unsupported
|
|
704
|
+
// rotated/skewed STRETCH (plugin API: CROP) transform.
|
|
705
|
+
const par = mode === 'FIT' ? 'xMidYMid meet' : 'xMidYMid slice';
|
|
706
|
+
return {
|
|
707
|
+
defs: clipDef,
|
|
708
|
+
bg: `<image href="${dataUri}" x="0" y="0" width="${w}" height="${h}" preserveAspectRatio="${par}" clip-path="url(#${clipId})"${opacityAttr}/>`,
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
function renderRoundedRectFillStack(deck, fillPaints, w, h, rx) {
|
|
713
|
+
const visibleFills = fillPaints?.filter(p => p.visible !== false) ?? [];
|
|
714
|
+
let defs = '';
|
|
715
|
+
const bgParts = [];
|
|
716
|
+
|
|
717
|
+
for (const fill of visibleFills) {
|
|
718
|
+
if (fill.type === 'SOLID') {
|
|
719
|
+
bgParts.push(`<rect x="0" y="0" width="${w}" height="${h}" rx="${rx}" ry="${rx}" fill="${cssColor(fill.color ?? {}, fill.opacity ?? 1)}"/>`);
|
|
720
|
+
continue;
|
|
721
|
+
}
|
|
722
|
+
if (fill.type === 'IMAGE') {
|
|
723
|
+
const result = resolveImageFillSvg(deck, fill, w, h, rx);
|
|
724
|
+
defs = appendDefs(defs, result.defs);
|
|
725
|
+
bgParts.push(result.bg);
|
|
726
|
+
continue;
|
|
727
|
+
}
|
|
728
|
+
if (fill.type === 'GRADIENT_LINEAR' || fill.type === 'GRADIENT_RADIAL') {
|
|
729
|
+
const grad = resolveGradientSvg(fill, w, h);
|
|
730
|
+
if (grad) {
|
|
731
|
+
defs = appendDefs(defs, grad.defs);
|
|
732
|
+
bgParts.push(`<rect x="0" y="0" width="${w}" height="${h}" rx="${rx}" ry="${rx}" fill="${grad.fill}"${grad.opacityAttr}/>`);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
return { defs, bg: bgParts.join('\n') };
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
function renderFrame(deck, node) {
|
|
741
|
+
const { w, h } = size(node);
|
|
742
|
+
const rx = Math.min(node.cornerRadius ?? 0, w / 2, h / 2);
|
|
743
|
+
const stroke = strokeSpec(node);
|
|
744
|
+
const inner = childrenSvg(deck, node);
|
|
745
|
+
let { defs, bg } = renderRoundedRectFillStack(deck, getFillPaints(node), w, h, rx);
|
|
746
|
+
|
|
747
|
+
// Frame clipping: Figma frames clip children when "Clip content" is ON,
|
|
748
|
+
// stored as frameMaskDisabled === false (explicit). Clipping is suppressed:
|
|
749
|
+
// - inside SYMBOL trees (Figma doesn't enforce child frame clips in components)
|
|
750
|
+
// - on frames with no visible fill (grouping containers, not visual viewports)
|
|
751
|
+
const hasFill = getFillPaints(node)?.some(p => p.visible !== false);
|
|
752
|
+
let clippedInner = inner;
|
|
753
|
+
if (inner && node.frameMaskDisabled === false && _symbolDepth === 0 && hasFill) {
|
|
754
|
+
const clipId = `frame-clip-${++_svgIdSeq}`;
|
|
755
|
+
defs += `<clipPath id="${clipId}"><rect width="${w}" height="${h}" rx="${rx}" ry="${rx}"/></clipPath>`;
|
|
756
|
+
clippedInner = `<g clip-path="url(#${clipId})">${inner}</g>`;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
const strokeSvg = rectStrokeSvg(0, 0, w, h, rx, stroke);
|
|
760
|
+
|
|
761
|
+
const parts = [defs, bg, clippedInner, strokeSvg].filter(Boolean).join('\n');
|
|
762
|
+
if (!parts) return '';
|
|
763
|
+
return `<g transform="${svgTransform(node)}">\n${parts}\n</g>`;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
function renderGroup(deck, node) {
|
|
767
|
+
const inner = childrenSvg(deck, node);
|
|
768
|
+
if (!inner) return '';
|
|
769
|
+
return `<g transform="${svgTransform(node)}">\n${inner}\n</g>`;
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/**
|
|
773
|
+
* SHAPE_WITH_TEXT: pill/badge nodes — styling and text stored in nodeGenerationData.overrides.
|
|
774
|
+
* overrides[0] = shape (fill, stroke, cornerRadius)
|
|
775
|
+
* overrides[1] = text (textData.characters, fontName, fontSize, textCase)
|
|
776
|
+
* Text position comes from derivedImmutableFrameData.overrides[1].
|
|
777
|
+
*/
|
|
778
|
+
function renderShapeWithText(deck, node) {
|
|
779
|
+
const { w, h } = size(node);
|
|
780
|
+
const genOvs = node.nodeGenerationData?.overrides ?? [];
|
|
781
|
+
const shapeOv = genOvs[0] ?? {};
|
|
782
|
+
const textOv = genOvs[1] ?? {};
|
|
783
|
+
|
|
784
|
+
// Shape styling
|
|
785
|
+
const rawRx = shapeOv.cornerRadius ?? 0;
|
|
786
|
+
const rx = Math.min(rawRx, w / 2, h / 2); // 1000000 → pill
|
|
787
|
+
const fill = resolveFill(shapeOv.fillPaints) ?? 'none';
|
|
788
|
+
|
|
789
|
+
// Prefer strokeGeometry (pre-computed filled outlines) over manual SVG strokes
|
|
790
|
+
const geoStroke = strokeGeometrySvg(deck, node);
|
|
791
|
+
let strokeAttr = '';
|
|
792
|
+
if (!geoStroke) {
|
|
793
|
+
const sw = shapeOv.strokeWeight ?? 0;
|
|
794
|
+
const stroke = sw > 0 ? resolveFill(shapeOv.strokePaints) ?? 'none' : 'none';
|
|
795
|
+
strokeAttr = sw > 0 && stroke !== 'none' ? `stroke="${stroke}" stroke-width="${sw}"` : '';
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
const fillSvg = `<rect x="0" y="0" width="${w}" height="${h}" rx="${rx}" ry="${rx}" fill="${fill}" ${strokeAttr}/>`;
|
|
799
|
+
// Stroke-under-fill compositing: strokeGeometry underneath, fill on top
|
|
800
|
+
const rectSvg = geoStroke ? `${geoStroke}\n${fillSvg}` : fillSvg;
|
|
801
|
+
|
|
802
|
+
// Text
|
|
803
|
+
const chars = textOv.textData?.characters ?? '';
|
|
804
|
+
if (!chars.trim()) return `<g transform="${svgTransform(node)}">${rectSvg}</g>`;
|
|
805
|
+
|
|
806
|
+
const textCase = textOv.textCase ?? 'ORIGINAL';
|
|
807
|
+
const dispChars = textCase === 'UPPER' ? chars.toUpperCase()
|
|
808
|
+
: textCase === 'LOWER' ? chars.toLowerCase()
|
|
809
|
+
: chars;
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
// Text offset + authoritative font metrics from derivedImmutableFrameData
|
|
813
|
+
const derivedOvs = node.derivedImmutableFrameData?.overrides ?? [];
|
|
814
|
+
const textDerived = derivedOvs.find(o => o.derivedTextData) ?? {};
|
|
815
|
+
const textBoxX = textDerived.transform?.m02 ?? 0;
|
|
816
|
+
const textBoxY = textDerived.transform?.m12 ?? 0;
|
|
817
|
+
const derivedText = textDerived.derivedTextData ?? {};
|
|
818
|
+
const glyphs = derivedText.glyphs;
|
|
819
|
+
const truncationStartIndex = derivedText.truncationStartIndex >= 0
|
|
820
|
+
? derivedText.truncationStartIndex
|
|
821
|
+
: null;
|
|
822
|
+
const swtStale = isStaleLayout(chars, derivedText.baselines, glyphs);
|
|
823
|
+
if (!glyphs?.length && !swtStale) {
|
|
824
|
+
throw new Error(`SHAPE_WITH_TEXT ${node.name ?? nid(node)} is missing derived glyph layout`);
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
// derivedTextData is authoritative — nodeGenerationData can have stale/wrong values
|
|
828
|
+
const derivedFont = textDerived.derivedTextData?.fontMetaData?.[0]?.key;
|
|
829
|
+
const fontSize = textDerived.derivedTextData?.glyphs?.[0]?.fontSize ?? textOv.fontSize ?? 24;
|
|
830
|
+
const fontFamily = derivedFont?.family ?? textOv.fontName?.family ?? 'Inter';
|
|
831
|
+
const fontStyle = derivedFont?.style ?? textOv.fontName?.style ?? 'Regular';
|
|
832
|
+
const fontWeight = /semibold|bold/i.test(fontStyle) ? 'bold'
|
|
833
|
+
: /medium/i.test(fontStyle) ? '500' : 'normal';
|
|
834
|
+
const fontItalic = /italic/i.test(fontStyle) ? 'italic' : 'normal';
|
|
835
|
+
const textFill = resolveFill(textOv.fillPaints) ?? '#000000';
|
|
836
|
+
|
|
837
|
+
let tspan;
|
|
838
|
+
|
|
839
|
+
if (swtStale || !glyphs?.length) {
|
|
840
|
+
// Fallback: stale layout — center text in shape using textBox offset
|
|
841
|
+
const swtBaselines = derivedText.baselines;
|
|
842
|
+
const lineHeightPx = swtBaselines?.[0]?.lineHeight ?? fontSize * 1.2;
|
|
843
|
+
const lineAscent = swtBaselines?.[0]?.lineAscent ?? fontSize * 0.8;
|
|
844
|
+
const lines = dispChars.split('\n').filter((l, i, a) => i < a.length - 1 || l);
|
|
845
|
+
const totalH = lines.length * lineHeightPx;
|
|
846
|
+
// Center vertically in the text box area
|
|
847
|
+
const textBoxH = textDerived.size?.y ?? h;
|
|
848
|
+
const startY = textBoxY + (textBoxH - totalH) / 2 + lineAscent;
|
|
849
|
+
const textBoxW = textDerived.size?.x ?? w;
|
|
850
|
+
const cx = textBoxX + textBoxW / 2;
|
|
851
|
+
tspan = lines.map((line, i) => {
|
|
852
|
+
const y = startY + i * lineHeightPx;
|
|
853
|
+
return `<tspan x="${cx}" y="${y.toFixed(2)}" text-anchor="middle">${esc(line) || ' '}</tspan>`;
|
|
854
|
+
}).join('');
|
|
855
|
+
} else {
|
|
856
|
+
const spans = [];
|
|
857
|
+
for (let i = 0; i < glyphs.length; i++) {
|
|
858
|
+
const g = glyphs[i];
|
|
859
|
+
if (truncationStartIndex != null && g.firstCharacter != null && g.firstCharacter >= truncationStartIndex) continue;
|
|
860
|
+
|
|
861
|
+
let slice = '';
|
|
862
|
+
let stopAfter = false;
|
|
863
|
+
if (g.firstCharacter == null) {
|
|
864
|
+
if (truncationStartIndex == null) continue;
|
|
865
|
+
slice = '…';
|
|
866
|
+
stopAfter = true;
|
|
867
|
+
} else {
|
|
868
|
+
let nextChar = null;
|
|
869
|
+
for (let j = i + 1; j < glyphs.length; j++) {
|
|
870
|
+
const fc = glyphs[j].firstCharacter;
|
|
871
|
+
if (fc != null && fc > g.firstCharacter) {
|
|
872
|
+
nextChar = fc;
|
|
873
|
+
break;
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
slice = dispChars.slice(g.firstCharacter, nextChar ?? (g.firstCharacter + 1));
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
if (!slice) continue;
|
|
880
|
+
spans.push(`<tspan x="${textBoxX + g.position.x}" y="${textBoxY + g.position.y}">${esc(slice)}</tspan>`);
|
|
881
|
+
if (stopAfter) break;
|
|
882
|
+
}
|
|
883
|
+
tspan = spans.join('');
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
const textSvg = [
|
|
887
|
+
`<text font-size="${fontSize}" font-family="${fontFamily}, sans-serif"`,
|
|
888
|
+
` font-weight="${fontWeight}" font-style="${fontItalic}" fill="${textFill}"`,
|
|
889
|
+
` text-rendering="geometricPrecision">${tspan}</text>`,
|
|
890
|
+
].join('\n');
|
|
891
|
+
|
|
892
|
+
return `<g transform="${svgTransform(node)}">\n${rectSvg}\n${textSvg}\n</g>`;
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
function renderLine(deck, node) {
|
|
896
|
+
// Prefer strokeGeometry (filled path outline) — gives better anti-aliasing
|
|
897
|
+
// than SVG <line> for near-horizontal/vertical angled lines.
|
|
898
|
+
const geoSvg = strokeGeometrySvg(deck, node);
|
|
899
|
+
if (geoSvg) {
|
|
900
|
+
return `<g transform="${svgTransform(node)}">\n${geoSvg}\n</g>`;
|
|
901
|
+
}
|
|
902
|
+
// Fallback: LINE uses full transform matrix: direction = (m00, m10), origin = (m02, m12)
|
|
903
|
+
const x1 = node.transform?.m02 ?? 0;
|
|
904
|
+
const y1 = node.transform?.m12 ?? 0;
|
|
905
|
+
const m00 = node.transform?.m00 ?? 1;
|
|
906
|
+
const m10 = node.transform?.m10 ?? 0;
|
|
907
|
+
const len = node.size?.x ?? 0;
|
|
908
|
+
const x2 = x1 + len * m00;
|
|
909
|
+
const y2 = y1 + len * m10;
|
|
910
|
+
const stroke = resolveFill(node.strokePaints) ?? '#000000';
|
|
911
|
+
const sw = node.strokeWeight ?? 1;
|
|
912
|
+
return `<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="${stroke}" stroke-width="${sw}"/>`;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
/**
|
|
916
|
+
* VECTOR — decode fillGeometry/strokeGeometry commandsBlob binary to SVG paths.
|
|
917
|
+
*
|
|
918
|
+
* Blob format: [cmdByte][float32LE params...]
|
|
919
|
+
* 0x01 = moveTo (x, y)
|
|
920
|
+
* 0x02 = lineTo (x, y)
|
|
921
|
+
* 0x04 = cubicTo (c1x, c1y, c2x, c2y, x, y)
|
|
922
|
+
* 0x00 = close
|
|
923
|
+
*
|
|
924
|
+
* Coordinates are in node-size space. The full affine transform matrix is used
|
|
925
|
+
* to position, scale, and rotate the vector in the slide.
|
|
926
|
+
*/
|
|
927
|
+
function renderVector(deck, node) {
|
|
928
|
+
const t = node.transform ?? {};
|
|
929
|
+
const m00 = t.m00 ?? 1, m01 = t.m01 ?? 0, m02 = t.m02 ?? 0;
|
|
930
|
+
const m10 = t.m10 ?? 0, m11 = t.m11 ?? 1, m12 = t.m12 ?? 0;
|
|
931
|
+
const blobs = deck.message?.blobs;
|
|
932
|
+
const parts = [];
|
|
933
|
+
|
|
934
|
+
// Collect fill paths — each fillGeometry entry is an independent fill region.
|
|
935
|
+
// Sub-paths *within* one entry interact via fill-rule (e.g. QR codes, letter cutouts),
|
|
936
|
+
// but entries are never combined — otherwise nesting causes evenodd to cut holes.
|
|
937
|
+
const fillColor = resolveFill(getFillPaints(node));
|
|
938
|
+
const fillEntries = []; // { d, color, rule }
|
|
939
|
+
if (node.fillGeometry?.length && blobs) {
|
|
940
|
+
// Build styleID → fill color map from per-path overrides
|
|
941
|
+
const styleMap = new Map();
|
|
942
|
+
if (node.vectorData?.styleOverrideTable?.length) {
|
|
943
|
+
for (const s of node.vectorData.styleOverrideTable) {
|
|
944
|
+
if (s.styleID != null && s.fillPaints) {
|
|
945
|
+
styleMap.set(s.styleID, resolveFill(s.fillPaints));
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
for (const geo of node.fillGeometry) {
|
|
951
|
+
const color = (geo.styleID && styleMap.has(geo.styleID))
|
|
952
|
+
? styleMap.get(geo.styleID)
|
|
953
|
+
: fillColor;
|
|
954
|
+
if (!color) continue;
|
|
955
|
+
const d = decodeCmdBlob(blobs, geo.commandsBlob);
|
|
956
|
+
if (!d) continue;
|
|
957
|
+
const rule = geo.windingRule === 'EVENODD' ? ' fill-rule="evenodd"' : '';
|
|
958
|
+
fillEntries.push({ d, color, rule });
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
// Stroke handling — depends on strokeAlign:
|
|
963
|
+
// OUTSIDE: strokeGeometry is always CENTER-aligned in the blob data, regardless of
|
|
964
|
+
// the node's strokeAlign setting. For OUTSIDE, we use SVG native strokes at
|
|
965
|
+
// 2× width underneath the fill — the fill covers the inner half, leaving
|
|
966
|
+
// only the outer portion visible.
|
|
967
|
+
// CENTER: strokeGeometry blobs are pre-expanded filled outlines (correct as-is).
|
|
968
|
+
// INSIDE: strokeGeometry + clip (TODO — falls back to CENTER for now).
|
|
969
|
+
const strokeColor = resolveFill(node.strokePaints);
|
|
970
|
+
const sw = node.strokeWeight ?? 0;
|
|
971
|
+
const strokeAlign = node.strokeAlign ?? 'CENTER';
|
|
972
|
+
const dashAttr = Array.isArray(node.dashPattern) && node.dashPattern.length
|
|
973
|
+
? ` stroke-dasharray="${node.dashPattern.join(' ')}"`
|
|
974
|
+
: '';
|
|
975
|
+
const lineCap = node.strokeCap === 'ROUND'
|
|
976
|
+
? 'round'
|
|
977
|
+
: node.strokeCap === 'SQUARE'
|
|
978
|
+
? 'square'
|
|
979
|
+
: 'butt';
|
|
980
|
+
const lineJoin = node.strokeJoin === 'ROUND'
|
|
981
|
+
? 'round'
|
|
982
|
+
: node.strokeJoin === 'BEVEL'
|
|
983
|
+
? 'bevel'
|
|
984
|
+
: 'miter';
|
|
985
|
+
|
|
986
|
+
if (strokeAlign === 'OUTSIDE' && strokeColor && sw > 0 && fillEntries.length) {
|
|
987
|
+
// Stroke layer underneath (2× width, centered = sw outside + sw inside)
|
|
988
|
+
for (const { d, rule } of fillEntries) {
|
|
989
|
+
parts.push(
|
|
990
|
+
`<path d="${d}" fill="none" stroke="${strokeColor}" stroke-width="${sw * 2}" ` +
|
|
991
|
+
`stroke-linecap="${lineCap}" stroke-linejoin="${lineJoin}"${dashAttr}${rule}/>`
|
|
992
|
+
);
|
|
993
|
+
}
|
|
994
|
+
// Fill layer on top — covers inner half of stroke
|
|
995
|
+
for (const { d, color, rule } of fillEntries) {
|
|
996
|
+
parts.push(`<path d="${d}" fill="${color}"${rule}/>`);
|
|
997
|
+
}
|
|
998
|
+
} else {
|
|
999
|
+
// Emit fill paths
|
|
1000
|
+
for (const { d, color, rule } of fillEntries) {
|
|
1001
|
+
parts.push(`<path d="${d}" fill="${color}"${rule}/>`);
|
|
1002
|
+
}
|
|
1003
|
+
// CENTER/INSIDE: use pre-computed strokeGeometry outlines as filled paths
|
|
1004
|
+
if (strokeColor && sw > 0 && node.strokeGeometry?.length && blobs) {
|
|
1005
|
+
const segments = [];
|
|
1006
|
+
let hasEvenOdd = false;
|
|
1007
|
+
for (const geo of node.strokeGeometry) {
|
|
1008
|
+
const d = decodeCmdBlob(blobs, geo.commandsBlob);
|
|
1009
|
+
if (d) segments.push(d);
|
|
1010
|
+
if (geo.windingRule === 'EVENODD') hasEvenOdd = true;
|
|
1011
|
+
}
|
|
1012
|
+
if (segments.length) {
|
|
1013
|
+
const rule = (segments.length > 1 || hasEvenOdd) ? ' fill-rule="evenodd"' : '';
|
|
1014
|
+
parts.push(`<path d="${segments.join('')}" fill="${strokeColor}"${rule}/>`);
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
// Fallback: decode vectorNetworkBlob when no pre-computed fill/strokeGeometry
|
|
1020
|
+
if (!parts.length && node.vectorData?.vectorNetworkBlob != null && blobs) {
|
|
1021
|
+
const vnbD = decodeVnb(blobs, node.vectorData.vectorNetworkBlob, node.vectorData.normalizedSize, node.size);
|
|
1022
|
+
if (vnbD) {
|
|
1023
|
+
if (!fillColor && strokeColor && sw > 0) {
|
|
1024
|
+
parts.push(
|
|
1025
|
+
`<path d="${vnbD}" fill="none" stroke="${strokeColor}" stroke-width="${sw}" ` +
|
|
1026
|
+
`stroke-linecap="${lineCap}" stroke-linejoin="${lineJoin}"${dashAttr}/>`
|
|
1027
|
+
);
|
|
1028
|
+
} else {
|
|
1029
|
+
const color = fillColor ?? strokeColor ?? '#000000';
|
|
1030
|
+
parts.push(`<path d="${vnbD}" fill="${color}" fill-rule="evenodd"/>`);
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
if (!parts.length) return renderPlaceholder(deck, node);
|
|
1036
|
+
return `<g transform="matrix(${m00},${m10},${m01},${m11},${m02},${m12})">\n${parts.join('\n')}\n</g>`;
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
/** BOOLEAN_OPERATION — render the pre-computed boolean result shape.
|
|
1040
|
+
* fillGeometry contains the merged boolean result; children are shape operands
|
|
1041
|
+
* baked into fillGeometry. However, the compound path may have winding-direction
|
|
1042
|
+
* holes that need filling. Children are re-rendered with the PARENT's fill color
|
|
1043
|
+
* (not their own) to fill these gaps — Figma applies the boolean node's fill
|
|
1044
|
+
* to all content uniformly. */
|
|
1045
|
+
function renderBooleanOp(deck, node) {
|
|
1046
|
+
const ownSvg = renderVector(deck, node);
|
|
1047
|
+
|
|
1048
|
+
// For UNION booleans: re-render children using the parent's fill color to
|
|
1049
|
+
// fill winding-direction holes. XOR/SUBTRACT/INTERSECT fillGeometry is
|
|
1050
|
+
// self-contained — children are pure shape operands.
|
|
1051
|
+
let inner = '';
|
|
1052
|
+
if (node.booleanOperation === 'UNION') {
|
|
1053
|
+
const parentFill = resolveFill(getFillPaints(node));
|
|
1054
|
+
if (parentFill) {
|
|
1055
|
+
const children = deck.getChildren(nid(node));
|
|
1056
|
+
const childParts = [];
|
|
1057
|
+
for (const child of children) {
|
|
1058
|
+
if (child.phase === 'REMOVED') continue;
|
|
1059
|
+
const origFills = child.fillPaints;
|
|
1060
|
+
child.fillPaints = getFillPaints(node);
|
|
1061
|
+
childParts.push(renderNode(deck, child));
|
|
1062
|
+
child.fillPaints = origFills;
|
|
1063
|
+
}
|
|
1064
|
+
inner = childParts.filter(Boolean).join('\n');
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
if (!ownSvg && !inner) return '';
|
|
1069
|
+
if (!inner) return ownSvg;
|
|
1070
|
+
if (!ownSvg) {
|
|
1071
|
+
const t = node.transform ?? {};
|
|
1072
|
+
const m00 = t.m00 ?? 1, m01 = t.m01 ?? 0, m02 = t.m02 ?? 0;
|
|
1073
|
+
const m10 = t.m10 ?? 0, m11 = t.m11 ?? 1, m12 = t.m12 ?? 0;
|
|
1074
|
+
return `<g transform="matrix(${m00},${m10},${m01},${m11},${m02},${m12})">\n${inner}\n</g>`;
|
|
1075
|
+
}
|
|
1076
|
+
const closeIdx = ownSvg.lastIndexOf('</g>');
|
|
1077
|
+
return ownSvg.slice(0, closeIdx) + inner + '\n</g>';
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
/** Decode a commandsBlob index into an SVG path d-string. */
|
|
1081
|
+
function decodeCmdBlob(blobs, blobIdx) {
|
|
1082
|
+
if (blobIdx == null || !blobs?.[blobIdx]) return null;
|
|
1083
|
+
const raw = blobs[blobIdx].bytes ?? blobs[blobIdx];
|
|
1084
|
+
if (!raw) return null;
|
|
1085
|
+
|
|
1086
|
+
// Convert indexed object to Buffer if needed
|
|
1087
|
+
let buf;
|
|
1088
|
+
if (Buffer.isBuffer(raw) || raw instanceof Uint8Array) {
|
|
1089
|
+
buf = Buffer.from(raw);
|
|
1090
|
+
} else {
|
|
1091
|
+
const len = Object.keys(raw).length;
|
|
1092
|
+
buf = Buffer.alloc(len);
|
|
1093
|
+
for (let i = 0; i < len; i++) buf[i] = raw[i];
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
const cmds = [];
|
|
1097
|
+
let off = 0;
|
|
1098
|
+
while (off < buf.length) {
|
|
1099
|
+
const cmd = buf[off++];
|
|
1100
|
+
if (cmd === 0x01) { // moveTo
|
|
1101
|
+
const x = buf.readFloatLE(off); off += 4;
|
|
1102
|
+
const y = buf.readFloatLE(off); off += 4;
|
|
1103
|
+
cmds.push(`M${f(x)},${f(y)}`);
|
|
1104
|
+
} else if (cmd === 0x02) { // lineTo
|
|
1105
|
+
const x = buf.readFloatLE(off); off += 4;
|
|
1106
|
+
const y = buf.readFloatLE(off); off += 4;
|
|
1107
|
+
cmds.push(`L${f(x)},${f(y)}`);
|
|
1108
|
+
} else if (cmd === 0x04) { // cubicTo
|
|
1109
|
+
const c1x = buf.readFloatLE(off); off += 4;
|
|
1110
|
+
const c1y = buf.readFloatLE(off); off += 4;
|
|
1111
|
+
const c2x = buf.readFloatLE(off); off += 4;
|
|
1112
|
+
const c2y = buf.readFloatLE(off); off += 4;
|
|
1113
|
+
const x = buf.readFloatLE(off); off += 4;
|
|
1114
|
+
const y = buf.readFloatLE(off); off += 4;
|
|
1115
|
+
cmds.push(`C${f(c1x)},${f(c1y)} ${f(c2x)},${f(c2y)} ${f(x)},${f(y)}`);
|
|
1116
|
+
} else if (cmd === 0x00) { // close
|
|
1117
|
+
cmds.push('Z');
|
|
1118
|
+
} else {
|
|
1119
|
+
break; // unknown command — stop
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
return cmds.length ? cmds.join('') : null;
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
function f(v) { return +v.toFixed(2); }
|
|
1126
|
+
|
|
1127
|
+
/**
|
|
1128
|
+
* Decode a vectorNetworkBlob into an SVG path d-string.
|
|
1129
|
+
*
|
|
1130
|
+
* The byte layout lives in `openfig-core`'s `parseVectorNetworkBlob`, which is held
|
|
1131
|
+
* to it by a byte-identical round-trip over a 42-blob reference corpus. This
|
|
1132
|
+
* function is a thin adapter: it scales coordinates from `normalizedSize` space to
|
|
1133
|
+
* `nodeSize` and emits path commands. It deliberately does not parse bytes — this
|
|
1134
|
+
* package used to carry its own walker, and the two descriptions of the format
|
|
1135
|
+
* drifted apart, with the rasterizer flattening every curve for as long as they did.
|
|
1136
|
+
*
|
|
1137
|
+
* A segment is straight iff all four tangent components are zero; there is no
|
|
1138
|
+
* segment-type field. See `openfig-core/docs/vector.md` and
|
|
1139
|
+
* `docs/figma-behaviour.md`.
|
|
1140
|
+
*/
|
|
1141
|
+
export function decodeVnb(blobs, blobIdx, normalizedSize, nodeSize) {
|
|
1142
|
+
const buf = blobToBuffer(blobs, blobIdx);
|
|
1143
|
+
if (!buf) return null;
|
|
1144
|
+
|
|
1145
|
+
let network;
|
|
1146
|
+
try {
|
|
1147
|
+
network = parseVectorNetworkBlob(new Uint8Array(buf));
|
|
1148
|
+
} catch {
|
|
1149
|
+
// A blob we cannot account for byte-for-byte is one we do not understand.
|
|
1150
|
+
// Returning null lets the caller fall through to its placeholder rather than
|
|
1151
|
+
// rendering geometry we half-read.
|
|
1152
|
+
return null;
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
const scaleX = (nodeSize?.x ?? 1) / (normalizedSize?.x ?? 1);
|
|
1156
|
+
const scaleY = (nodeSize?.y ?? 1) / (normalizedSize?.y ?? 1);
|
|
1157
|
+
const verts = network.vertices.map((v) => ({ x: v.x * scaleX, y: v.y * scaleY }));
|
|
1158
|
+
const segs = network.segments.map((s) => ({
|
|
1159
|
+
sv: s.start.vertex,
|
|
1160
|
+
ev: s.end.vertex,
|
|
1161
|
+
tsx: s.start.dx * scaleX,
|
|
1162
|
+
tsy: s.start.dy * scaleY,
|
|
1163
|
+
tex: s.end.dx * scaleX,
|
|
1164
|
+
tey: s.end.dy * scaleY,
|
|
1165
|
+
isStraight: s.isStraight,
|
|
1166
|
+
}));
|
|
1167
|
+
|
|
1168
|
+
const segToPathCmd = (seg, start, end) => {
|
|
1169
|
+
if (seg.isStraight) return `L${f(end.x)},${f(end.y)}`;
|
|
1170
|
+
const c1x = start.x + seg.tsx;
|
|
1171
|
+
const c1y = start.y + seg.tsy;
|
|
1172
|
+
const c2x = end.x + seg.tex;
|
|
1173
|
+
const c2y = end.y + seg.tey;
|
|
1174
|
+
return `C${f(c1x)},${f(c1y)} ${f(c2x)},${f(c2y)} ${f(end.x)},${f(end.y)}`;
|
|
1175
|
+
};
|
|
1176
|
+
|
|
1177
|
+
// Regions → SVG subpaths. Each loop is its own closed subpath.
|
|
1178
|
+
const cmds = [];
|
|
1179
|
+
for (const region of network.regions) {
|
|
1180
|
+
for (const loop of region.loops) {
|
|
1181
|
+
loop.forEach((segIdx, s) => {
|
|
1182
|
+
const seg = segs[segIdx];
|
|
1183
|
+
if (!seg) return;
|
|
1184
|
+
const start = verts[seg.sv];
|
|
1185
|
+
const end = verts[seg.ev];
|
|
1186
|
+
if (!start || !end) return;
|
|
1187
|
+
if (s === 0) cmds.push(`M${f(start.x)},${f(start.y)}`);
|
|
1188
|
+
cmds.push(segToPathCmd(seg, start, end));
|
|
1189
|
+
});
|
|
1190
|
+
cmds.push('Z');
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
// Fallback for blobs that carry no usable region loops — an open path authored
|
|
1195
|
+
// via addPath(), or a region block this walk could not consume. Recover the
|
|
1196
|
+
// centerline by walking the stored segments in order so the node renders as a
|
|
1197
|
+
// stroke instead of falling through to the magenta placeholder.
|
|
1198
|
+
//
|
|
1199
|
+
// Note this is genuinely a fallback, not the common case: every stroke-only node
|
|
1200
|
+
// in the current deck fixtures carries regionCount === 1 and is handled above.
|
|
1201
|
+
if (!cmds.length && segs.length) {
|
|
1202
|
+
let currentEnd = null;
|
|
1203
|
+
let subpathStart = null;
|
|
1204
|
+
for (const seg of segs) {
|
|
1205
|
+
const start = verts[seg.sv];
|
|
1206
|
+
const end = verts[seg.ev];
|
|
1207
|
+
if (!start || !end) continue;
|
|
1208
|
+
if (currentEnd == null || seg.sv !== currentEnd) {
|
|
1209
|
+
cmds.push(`M${f(start.x)},${f(start.y)}`);
|
|
1210
|
+
subpathStart = seg.sv;
|
|
1211
|
+
}
|
|
1212
|
+
cmds.push(segToPathCmd(seg, start, end));
|
|
1213
|
+
if (subpathStart != null && seg.ev === subpathStart) {
|
|
1214
|
+
cmds.push('Z');
|
|
1215
|
+
currentEnd = null;
|
|
1216
|
+
subpathStart = null;
|
|
1217
|
+
} else {
|
|
1218
|
+
currentEnd = seg.ev;
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
return cmds.length ? cmds.join('') : null;
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
function blobToBuffer(blobs, blobIdx) {
|
|
1227
|
+
if (blobIdx == null || !blobs?.[blobIdx]) return null;
|
|
1228
|
+
const raw = blobs[blobIdx].bytes ?? blobs[blobIdx];
|
|
1229
|
+
if (!raw) return null;
|
|
1230
|
+
if (Buffer.isBuffer(raw) || raw instanceof Uint8Array) return Buffer.from(raw);
|
|
1231
|
+
const len = Object.keys(raw).length;
|
|
1232
|
+
const buf = Buffer.alloc(len);
|
|
1233
|
+
for (let i = 0; i < len; i++) buf[i] = raw[i];
|
|
1234
|
+
return buf;
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
function renderPlaceholder(deck, node) {
|
|
1238
|
+
const { w, h } = size(node);
|
|
1239
|
+
const type = node.type ?? '?';
|
|
1240
|
+
return `<g transform="${svgTransform(node)}"><rect x="0" y="0" width="${w || 40}" height="${h || 40}" fill="none" stroke="#ff00ff" stroke-width="2" stroke-dasharray="6" opacity="0.5"/><!-- ${type} --></g>`;
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
/**
|
|
1244
|
+
* INSTANCE → SYMBOL resolution.
|
|
1245
|
+
*
|
|
1246
|
+
* Figma templates use INSTANCE nodes that reference a SYMBOL definition.
|
|
1247
|
+
* The SYMBOL's children (TEXT, shapes, frames, etc.) define the visual content.
|
|
1248
|
+
* The INSTANCE may carry symbolOverrides that modify specific child properties
|
|
1249
|
+
* (text content, fills, etc.).
|
|
1250
|
+
*
|
|
1251
|
+
* Strategy:
|
|
1252
|
+
* - Resolve the SYMBOL via symbolData.symbolID
|
|
1253
|
+
* - Render the SYMBOL's children tree (they live in the normal node hierarchy)
|
|
1254
|
+
* - Apply symbolOverrides: text and fill overrides are temporarily applied
|
|
1255
|
+
* to the target nodes, rendered, then restored.
|
|
1256
|
+
*/
|
|
1257
|
+
function renderInstance(deck, node) {
|
|
1258
|
+
const symbolId = node.symbolData?.symbolID;
|
|
1259
|
+
if (!symbolId) return renderPlaceholder(deck, node);
|
|
1260
|
+
|
|
1261
|
+
const symNid = `${symbolId.sessionID}:${symbolId.localID}`;
|
|
1262
|
+
const symbol = deck.getNode(symNid);
|
|
1263
|
+
if (!symbol) return renderPlaceholder(deck, node);
|
|
1264
|
+
|
|
1265
|
+
// Figma-parity: reject instances of symbols with invalid variant specs.
|
|
1266
|
+
// Figma Desktop silently shows blank slides for these. We match that behavior
|
|
1267
|
+
// deliberately so our preview catches invalid decks instead of hiding them.
|
|
1268
|
+
// Root cause: older tooling created SYMBOL variants with names (e.g.
|
|
1269
|
+
// "Size=Wide") that don't exist in the component set's variantPropSpecs.
|
|
1270
|
+
if (symbol.componentKey && symbol.variantPropSpecs) {
|
|
1271
|
+
const specValues = new Set(symbol.variantPropSpecs.map(s => s.value));
|
|
1272
|
+
const nameValues = (symbol.name || '').split(', ').map(p => p.split('=')[1]).filter(Boolean);
|
|
1273
|
+
const invalid = nameValues.some(v => !specValues.has(v));
|
|
1274
|
+
if (invalid) {
|
|
1275
|
+
const nid = `${node.guid.sessionID}:${node.guid.localID}`;
|
|
1276
|
+
console.warn(`⚠️ Skipping INSTANCE ${nid}: symbol ${symNid} "${symbol.name}" has invalid variant specs — Figma would show blank`);
|
|
1277
|
+
return renderPlaceholder(deck, node);
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
// Temporarily apply symbolOverrides so rendered content reflects overrides.
|
|
1282
|
+
// Override guidPaths may reference library-original IDs (e.g. 100:656) rather
|
|
1283
|
+
// than local node IDs (e.g. 1:1131). Nodes expose their library ID via the
|
|
1284
|
+
// `overrideKey` property, so we build a lookup from overrideKey → local node.
|
|
1285
|
+
const overrides = node.symbolData?.symbolOverrides ?? [];
|
|
1286
|
+
const restores = [];
|
|
1287
|
+
|
|
1288
|
+
// Build overrideKey → node map for all SYMBOL descendants
|
|
1289
|
+
const okMap = new Map();
|
|
1290
|
+
function buildOkMap(nid) {
|
|
1291
|
+
for (const child of deck.getChildren(nid)) {
|
|
1292
|
+
const ok = child.overrideKey;
|
|
1293
|
+
if (ok) okMap.set(`${ok.sessionID}:${ok.localID}`, child);
|
|
1294
|
+
buildOkMap(`${child.guid.sessionID}:${child.guid.localID}`);
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
buildOkMap(symNid);
|
|
1298
|
+
|
|
1299
|
+
// Build derivedSymbolData lookup: guidPath ID → entry.
|
|
1300
|
+
// Contains Figma-computed layout (size, transform, derivedTextData) for child
|
|
1301
|
+
// nodes as they appear in this INSTANCE, accounting for auto-layout resizing.
|
|
1302
|
+
const dsdMap = new Map();
|
|
1303
|
+
for (const entry of node.derivedSymbolData ?? []) {
|
|
1304
|
+
const guids = entry.guidPath?.guids;
|
|
1305
|
+
if (!guids?.length) continue;
|
|
1306
|
+
// Use the last guid in the path for single-level lookups
|
|
1307
|
+
const g = guids[guids.length - 1];
|
|
1308
|
+
dsdMap.set(`${g.sessionID}:${g.localID}`, entry);
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
// Apply symbolOverrides (symbol swaps, text characters, fill paints).
|
|
1312
|
+
// overriddenSymbolID entries swap which SYMBOL a nested INSTANCE renders —
|
|
1313
|
+
// e.g. swapping a body pose or head style in a character component.
|
|
1314
|
+
// These must be processed first so okMap gets extended with the new symbol's
|
|
1315
|
+
// descendants before text/fill overrides are applied.
|
|
1316
|
+
for (const ov of overrides) {
|
|
1317
|
+
const guids = ov.guidPath?.guids;
|
|
1318
|
+
if (!guids?.length || guids.length !== 1) continue;
|
|
1319
|
+
const targetId = `${guids[0].sessionID}:${guids[0].localID}`;
|
|
1320
|
+
const target = deck.getNode(targetId) ?? okMap.get(targetId);
|
|
1321
|
+
if (!target) continue;
|
|
1322
|
+
|
|
1323
|
+
if (ov.overriddenSymbolID && target.symbolData) {
|
|
1324
|
+
const origSymbolID = target.symbolData.symbolID;
|
|
1325
|
+
restores.push(() => { target.symbolData.symbolID = origSymbolID; });
|
|
1326
|
+
target.symbolData.symbolID = ov.overriddenSymbolID;
|
|
1327
|
+
// Extend okMap with the new symbol's descendants so downstream
|
|
1328
|
+
// overrides and derivedSymbolData can find them by overrideKey.
|
|
1329
|
+
const newSymNid = `${ov.overriddenSymbolID.sessionID}:${ov.overriddenSymbolID.localID}`;
|
|
1330
|
+
buildOkMap(newSymNid);
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
if (ov.textData?.characters != null && target.textData) {
|
|
1334
|
+
const origChars = target.textData.characters;
|
|
1335
|
+
restores.push(() => { target.textData.characters = origChars; });
|
|
1336
|
+
target.textData.characters = ov.textData.characters;
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
if (ov.fillPaints) {
|
|
1340
|
+
const origFill = target.fillPaints;
|
|
1341
|
+
restores.push(() => { target.fillPaints = origFill; });
|
|
1342
|
+
target.fillPaints = ov.fillPaints;
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
// Apply derivedSymbolData to matching nodes.
|
|
1347
|
+
// Auto-layout symbols (stackMode set): Figma re-positions/resizes children,
|
|
1348
|
+
// so apply size + transform + derivedTextData and skip global scale.
|
|
1349
|
+
// Non-auto-layout symbols: children scale proportionally, so only apply
|
|
1350
|
+
// derivedTextData (glyph re-layout) and use global scale for positioning.
|
|
1351
|
+
const isAutoLayout = !!symbol.stackMode;
|
|
1352
|
+
for (const [dsdId, dsd] of dsdMap) {
|
|
1353
|
+
const target = deck.getNode(dsdId) ?? okMap.get(dsdId);
|
|
1354
|
+
if (!target) continue;
|
|
1355
|
+
|
|
1356
|
+
if (dsd.derivedTextData) {
|
|
1357
|
+
const orig = target.derivedTextData;
|
|
1358
|
+
restores.push(() => { target.derivedTextData = orig; });
|
|
1359
|
+
target.derivedTextData = dsd.derivedTextData;
|
|
1360
|
+
}
|
|
1361
|
+
if (isAutoLayout && dsd.size) {
|
|
1362
|
+
const orig = target.size;
|
|
1363
|
+
restores.push(() => { target.size = orig; });
|
|
1364
|
+
target.size = dsd.size;
|
|
1365
|
+
}
|
|
1366
|
+
if (isAutoLayout && dsd.transform) {
|
|
1367
|
+
const orig = target.transform;
|
|
1368
|
+
restores.push(() => { target.transform = orig; });
|
|
1369
|
+
target.transform = dsd.transform;
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
// Scale when INSTANCE size differs from SYMBOL size.
|
|
1374
|
+
// Auto-layout symbols have per-node layout from derivedSymbolData, so skip scale.
|
|
1375
|
+
const instSize = size(node);
|
|
1376
|
+
const symSize = size(symbol.size ? symbol : node);
|
|
1377
|
+
const sx = symSize.w ? instSize.w / symSize.w : 1;
|
|
1378
|
+
const sy = symSize.h ? instSize.h / symSize.h : 1;
|
|
1379
|
+
const needsScale = !isAutoLayout && (Math.abs(sx - 1) > 0.001 || Math.abs(sy - 1) > 0.001);
|
|
1380
|
+
|
|
1381
|
+
// Render SYMBOL's own fill as background (e.g. dark-blue cover slide)
|
|
1382
|
+
// Use INSTANCE size when auto-layout provides per-node layout
|
|
1383
|
+
const bgW = isAutoLayout ? instSize.w : symSize.w;
|
|
1384
|
+
const bgH = isAutoLayout ? instSize.h : symSize.h;
|
|
1385
|
+
const rx = Math.min(symbol.cornerRadius ?? 0, bgW / 2, bgH / 2);
|
|
1386
|
+
let { defs, bg } = renderRoundedRectFillStack(deck, getFillPaints(symbol), bgW, bgH, rx);
|
|
1387
|
+
|
|
1388
|
+
// Render stroke. Use the INSTANCE's strokeGeometry (already computed for
|
|
1389
|
+
// INSTANCE dimensions) when borders are independent; fall back to SYMBOL rect.
|
|
1390
|
+
let strokeSvg = '';
|
|
1391
|
+
const strokeSrc = node.strokePaints ? node : symbol;
|
|
1392
|
+
const strokeColor = resolveFill(strokeSrc.strokePaints);
|
|
1393
|
+
if (strokeColor && (strokeSrc.strokeWeight ?? 0) > 0) {
|
|
1394
|
+
if (strokeSrc.borderStrokeWeightsIndependent && strokeSrc.strokeGeometry?.length) {
|
|
1395
|
+
const blobs = deck.message?.blobs;
|
|
1396
|
+
if (blobs) {
|
|
1397
|
+
const segs = [];
|
|
1398
|
+
for (const geo of strokeSrc.strokeGeometry) {
|
|
1399
|
+
const d = decodeCmdBlob(blobs, geo.commandsBlob);
|
|
1400
|
+
if (d) segs.push(d);
|
|
1401
|
+
}
|
|
1402
|
+
if (segs.length) {
|
|
1403
|
+
// Clip stroke to frame bounds — Figma's INSIDE-aligned stroke geometry
|
|
1404
|
+
// extends ±strokeWeight outside the frame edge (symmetric expansion).
|
|
1405
|
+
// A clipPath matching the frame bounds shows only the inside portion.
|
|
1406
|
+
const scId = `stroke-clip-${++_svgIdSeq}`;
|
|
1407
|
+
strokeSvg = `<clipPath id="${scId}"><rect width="${bgW}" height="${bgH}"/></clipPath>`
|
|
1408
|
+
+ `<path d="${segs.join('')}" fill="${strokeColor}" clip-path="url(#${scId})"/>`;
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
} else {
|
|
1412
|
+
const stroke = strokeSpec(strokeSrc);
|
|
1413
|
+
strokeSvg = rectStrokeSvg(0, 0, bgW, bgH, rx, stroke);
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
|
|
1417
|
+
_symbolDepth++;
|
|
1418
|
+
const inner = childrenSvg(deck, symbol);
|
|
1419
|
+
_symbolDepth--;
|
|
1420
|
+
|
|
1421
|
+
// Restore mutations
|
|
1422
|
+
for (const fn of restores) fn();
|
|
1423
|
+
|
|
1424
|
+
let content = [defs, bg, inner, strokeSvg].filter(Boolean).join('\n');
|
|
1425
|
+
if (!content) return '';
|
|
1426
|
+
if (needsScale) {
|
|
1427
|
+
content = `<g transform="scale(${sx},${sy})">\n${content}\n</g>`;
|
|
1428
|
+
}
|
|
1429
|
+
return `<g transform="${svgTransform(node)}">\n${content}\n</g>`;
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
// ── Dispatcher ────────────────────────────────────────────────────────────────
|
|
1433
|
+
|
|
1434
|
+
const RENDERERS = {
|
|
1435
|
+
ROUNDED_RECTANGLE: renderRect,
|
|
1436
|
+
RECTANGLE: renderRect,
|
|
1437
|
+
SHAPE_WITH_TEXT: renderShapeWithText,
|
|
1438
|
+
ELLIPSE: renderEllipse,
|
|
1439
|
+
TEXT: renderText,
|
|
1440
|
+
FRAME: renderFrame,
|
|
1441
|
+
GROUP: renderGroup,
|
|
1442
|
+
SECTION: renderGroup,
|
|
1443
|
+
BOOLEAN_OPERATION: renderBooleanOp,
|
|
1444
|
+
VECTOR: renderVector,
|
|
1445
|
+
LINE: renderLine,
|
|
1446
|
+
STAR: renderVector,
|
|
1447
|
+
REGULAR_POLYGON: renderVector,
|
|
1448
|
+
POLYGON: renderVector,
|
|
1449
|
+
INSTANCE: renderInstance,
|
|
1450
|
+
};
|
|
1451
|
+
|
|
1452
|
+
/** Build an SVG 1.1 <filter> for DROP_SHADOW effects.
|
|
1453
|
+
* Uses feGaussianBlur + feOffset + feFlood + feComposite + feMerge (SVG 1.1)
|
|
1454
|
+
* instead of feDropShadow (SVG 2) for broad renderer compatibility. */
|
|
1455
|
+
function buildEffectFilter(node) {
|
|
1456
|
+
const effects = node.effects?.filter(e => e.visible !== false);
|
|
1457
|
+
if (!effects?.length) return null;
|
|
1458
|
+
|
|
1459
|
+
const shadows = effects.filter(e => e.type === 'DROP_SHADOW');
|
|
1460
|
+
if (!shadows.length) return null;
|
|
1461
|
+
|
|
1462
|
+
const id = `fx-${++_svgIdSeq}`;
|
|
1463
|
+
const parts = [];
|
|
1464
|
+
const mergeNodes = [];
|
|
1465
|
+
|
|
1466
|
+
for (let i = 0; i < shadows.length; i++) {
|
|
1467
|
+
const s = shadows[i];
|
|
1468
|
+
const c = s.color ?? {};
|
|
1469
|
+
const r = Math.round((c.r ?? 0) * 255);
|
|
1470
|
+
const g = Math.round((c.g ?? 0) * 255);
|
|
1471
|
+
const b = Math.round((c.b ?? 0) * 255);
|
|
1472
|
+
const a = (c.a ?? 1).toFixed(4);
|
|
1473
|
+
const dx = s.offset?.x ?? 0;
|
|
1474
|
+
const dy = s.offset?.y ?? 0;
|
|
1475
|
+
const stdDev = (s.radius ?? 0) / 2;
|
|
1476
|
+
const sid = `s${i}`;
|
|
1477
|
+
parts.push(
|
|
1478
|
+
`<feGaussianBlur in="SourceAlpha" stdDeviation="${stdDev}" result="${sid}b"/>`,
|
|
1479
|
+
`<feOffset in="${sid}b" dx="${dx}" dy="${dy}" result="${sid}o"/>`,
|
|
1480
|
+
`<feFlood flood-color="rgb(${r},${g},${b})" flood-opacity="${a}" result="${sid}c"/>`,
|
|
1481
|
+
`<feComposite in="${sid}c" in2="${sid}o" operator="in" result="${sid}"/>`,
|
|
1482
|
+
);
|
|
1483
|
+
mergeNodes.push(`<feMergeNode in="${sid}"/>`);
|
|
1484
|
+
}
|
|
1485
|
+
mergeNodes.push(`<feMergeNode in="SourceGraphic"/>`);
|
|
1486
|
+
parts.push(`<feMerge>${mergeNodes.join('')}</feMerge>`);
|
|
1487
|
+
|
|
1488
|
+
// SVG default filter region: 10% padding. Sufficient for typical drop shadows
|
|
1489
|
+
// (radius ≤ 20px, offset ≤ 20px on elements > 100px).
|
|
1490
|
+
const defs = `<filter id="${id}" x="-10%" y="-10%" width="120%" height="120%" color-interpolation-filters="sRGB">${parts.join('')}</filter>`;
|
|
1491
|
+
return { defs, attr: `filter="url(#${id})"` };
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1494
|
+
function renderNode(deck, node) {
|
|
1495
|
+
if (node.phase === 'REMOVED') return '';
|
|
1496
|
+
const fn = RENDERERS[node.type] ?? renderPlaceholder;
|
|
1497
|
+
let svg = fn(deck, node);
|
|
1498
|
+
if (!svg) return '';
|
|
1499
|
+
|
|
1500
|
+
// Apply effects (drop shadows)
|
|
1501
|
+
const fx = buildEffectFilter(node);
|
|
1502
|
+
if (fx) {
|
|
1503
|
+
svg = `<defs>${fx.defs}</defs>\n<g ${fx.attr}>${svg}</g>`;
|
|
1504
|
+
}
|
|
1505
|
+
|
|
1506
|
+
const op = node.opacity;
|
|
1507
|
+
if (op != null && op < 1) {
|
|
1508
|
+
svg = `<g opacity="${op}">${svg}</g>`;
|
|
1509
|
+
}
|
|
1510
|
+
return svg;
|
|
1511
|
+
}
|
|
1512
|
+
|
|
1513
|
+
function childrenSvg(deck, node) {
|
|
1514
|
+
const out = [];
|
|
1515
|
+
let activeMask = null;
|
|
1516
|
+
let masked = [];
|
|
1517
|
+
|
|
1518
|
+
const flushMask = () => {
|
|
1519
|
+
if (!activeMask) return;
|
|
1520
|
+
const body = masked.filter(Boolean).join('\n');
|
|
1521
|
+
if (body) {
|
|
1522
|
+
const id = `alpha-mask-${++_svgIdSeq}`;
|
|
1523
|
+
const maskSvg = renderNode(deck, activeMask);
|
|
1524
|
+
out.push(
|
|
1525
|
+
`<defs><mask id="${id}" maskUnits="userSpaceOnUse" x="-100%" y="-100%" `
|
|
1526
|
+
+ `width="300%" height="300%" style="mask-type:alpha">${maskSvg}</mask></defs>`,
|
|
1527
|
+
`<g mask="url(#${id})">${body}</g>`,
|
|
1528
|
+
);
|
|
1529
|
+
}
|
|
1530
|
+
activeMask = null;
|
|
1531
|
+
masked = [];
|
|
1532
|
+
};
|
|
1533
|
+
|
|
1534
|
+
for (const child of deck.getChildren(nid(node))) {
|
|
1535
|
+
// This converter emits ALPHA masks. Keep other mask types on the legacy
|
|
1536
|
+
// rendering path until their outline/luminance semantics are implemented.
|
|
1537
|
+
if (child.mask === true && child.maskType === 'ALPHA') {
|
|
1538
|
+
flushMask();
|
|
1539
|
+
activeMask = child;
|
|
1540
|
+
continue;
|
|
1541
|
+
}
|
|
1542
|
+
const svg = renderNode(deck, child);
|
|
1543
|
+
if (!svg) continue;
|
|
1544
|
+
if (activeMask) masked.push(svg);
|
|
1545
|
+
else out.push(svg);
|
|
1546
|
+
}
|
|
1547
|
+
flushMask();
|
|
1548
|
+
return out.join('\n');
|
|
1549
|
+
}
|
|
1550
|
+
|
|
1551
|
+
// ── Public API ────────────────────────────────────────────────────────────────
|
|
1552
|
+
|
|
1553
|
+
/**
|
|
1554
|
+
* Convert a single slide node and its subtree to an SVG string.
|
|
1555
|
+
*
|
|
1556
|
+
* @param {import('../fig-deck.mjs').FigDeck} deck
|
|
1557
|
+
* @param {object} slideNode - The SLIDE node object
|
|
1558
|
+
* @returns {string} - Complete SVG string (1920×1080)
|
|
1559
|
+
*/
|
|
1560
|
+
export function slideToSvg(deck, slideNode) {
|
|
1561
|
+
_svgIdSeq = 0;
|
|
1562
|
+
_symbolDepth = 0;
|
|
1563
|
+
const bg = resolveFill(getFillPaints(slideNode)) ?? 'white';
|
|
1564
|
+
|
|
1565
|
+
const body = childrenSvg(deck, slideNode);
|
|
1566
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" \
|
|
1567
|
+
width="${SLIDE_W}" height="${SLIDE_H}" viewBox="0 0 ${SLIDE_W} ${SLIDE_H}">
|
|
1568
|
+
<defs>
|
|
1569
|
+
<clipPath id="slide-clip"><rect width="${SLIDE_W}" height="${SLIDE_H}"/></clipPath>
|
|
1570
|
+
</defs>
|
|
1571
|
+
<rect width="${SLIDE_W}" height="${SLIDE_H}" fill="${bg}"/>
|
|
1572
|
+
<g clip-path="url(#slide-clip)">
|
|
1573
|
+
${body}
|
|
1574
|
+
</g>
|
|
1575
|
+
</svg>`;
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
/**
|
|
1579
|
+
* Render any node (FRAME, GROUP, etc.) to SVG using its own size as the viewport.
|
|
1580
|
+
* Works for Design file frames, standalone components, or any node with a size field.
|
|
1581
|
+
*
|
|
1582
|
+
* Note: Figma's export expands bounds to include overflow content when a frame has
|
|
1583
|
+
* When frameMaskDisabled=true (clip content OFF), Figma's export expands the
|
|
1584
|
+
* bounds to include overflowing children. We replicate this by computing the
|
|
1585
|
+
* content bounding box and expanding the SVG viewport accordingly.
|
|
1586
|
+
*
|
|
1587
|
+
* @param {FigDeck} fig - Parsed Figma file (works with both .deck and .fig)
|
|
1588
|
+
* @param {object} node - The node to render (typically a FRAME)
|
|
1589
|
+
*/
|
|
1590
|
+
export function frameToSvg(fig, node) {
|
|
1591
|
+
_svgIdSeq = 0;
|
|
1592
|
+
_symbolDepth = 0;
|
|
1593
|
+
const fw = Math.round(node.size?.x ?? 100);
|
|
1594
|
+
const fh = Math.round(node.size?.y ?? 100);
|
|
1595
|
+
const body = childrenSvg(fig, node);
|
|
1596
|
+
|
|
1597
|
+
// Build background fill (supports solid, gradient, and image fills)
|
|
1598
|
+
const { defs: bgDefs, bg: bgSvg } = renderRoundedRectFillStack(fig, getFillPaints(node), fw, fh, 0);
|
|
1599
|
+
// Fallback to white rect if no visible fills
|
|
1600
|
+
const bgContent = bgSvg || `<rect x="0" y="0" width="${fw}" height="${fh}" fill="white"/>`;
|
|
1601
|
+
const defsBlock = bgDefs ? `${bgDefs}\n` : '';
|
|
1602
|
+
|
|
1603
|
+
// When clip content is OFF, expand viewport to include overflow.
|
|
1604
|
+
// Use fractional viewBox origin for exact positioning; ceil the total
|
|
1605
|
+
// coordinate range for pixel dimensions (matches Figma's export sizing).
|
|
1606
|
+
let vx = 0, vy = 0, w = fw, h = fh;
|
|
1607
|
+
if (node.frameMaskDisabled === true) {
|
|
1608
|
+
const bounds = _contentBounds(fig, node);
|
|
1609
|
+
vx = bounds.minX;
|
|
1610
|
+
vy = bounds.minY;
|
|
1611
|
+
w = Math.ceil(bounds.maxX - bounds.minX);
|
|
1612
|
+
h = Math.ceil(bounds.maxY - bounds.minY);
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" \
|
|
1616
|
+
width="${w}" height="${h}" viewBox="${vx} ${vy} ${w} ${h}">
|
|
1617
|
+
${defsBlock}${bgContent}
|
|
1618
|
+
${body}
|
|
1619
|
+
</svg>`;
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
/** Compute content bounding box of a node's children in the node's local space.
|
|
1623
|
+
* Recurses into INSTANCE→SYMBOL to catch overflow from scaled symbol children. */
|
|
1624
|
+
function _contentBounds(deck, node, depth = 2) {
|
|
1625
|
+
const fw = node.size?.x ?? 0;
|
|
1626
|
+
const fh = node.size?.y ?? 0;
|
|
1627
|
+
let minX = 0, minY = 0, maxX = fw, maxY = fh;
|
|
1628
|
+
|
|
1629
|
+
for (const child of deck.getChildren(nid(node))) {
|
|
1630
|
+
if (child.phase === 'REMOVED' || child.visible === false) continue;
|
|
1631
|
+
|
|
1632
|
+
const cx = child.transform?.m02 ?? 0;
|
|
1633
|
+
const cy = child.transform?.m12 ?? 0;
|
|
1634
|
+
const cw = child.size?.x ?? 0;
|
|
1635
|
+
const ch = child.size?.y ?? 0;
|
|
1636
|
+
|
|
1637
|
+
minX = Math.min(minX, cx);
|
|
1638
|
+
minY = Math.min(minY, cy);
|
|
1639
|
+
maxX = Math.max(maxX, cx + cw);
|
|
1640
|
+
maxY = Math.max(maxY, cy + ch);
|
|
1641
|
+
|
|
1642
|
+
// For INSTANCE nodes, check if symbol children overflow (scaled)
|
|
1643
|
+
if (depth > 0 && child.type === 'INSTANCE' && child.symbolData?.symbolID) {
|
|
1644
|
+
const symId = child.symbolData.symbolID;
|
|
1645
|
+
const sym = deck.getNode(`${symId.sessionID}:${symId.localID}`);
|
|
1646
|
+
if (sym) {
|
|
1647
|
+
const sw = sym.size?.x || cw;
|
|
1648
|
+
const sh = sym.size?.y || ch;
|
|
1649
|
+
const sx = cw / sw;
|
|
1650
|
+
const sy = ch / sh;
|
|
1651
|
+
const symBounds = _contentBounds(deck, sym, depth - 1);
|
|
1652
|
+
minX = Math.min(minX, cx + symBounds.minX * sx);
|
|
1653
|
+
minY = Math.min(minY, cy + symBounds.minY * sy);
|
|
1654
|
+
maxX = Math.max(maxX, cx + symBounds.maxX * sx);
|
|
1655
|
+
maxY = Math.max(maxY, cy + symBounds.maxY * sy);
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
|
|
1660
|
+
return { minX, minY, maxX, maxY };
|
|
1661
|
+
}
|