openfig-mcp 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,484 @@
1
+ // Node tree -> design spec (CSS per node, components, interactions, assets).
2
+ import { cssColor, gid, idOf, r2, hex, slug, sniffExt, fontWeight, NULL_GUID } from './util.mjs';
3
+ import { TokenRegistry, effectsCss, typographyCss } from './tokens.mjs';
4
+ import { describeInteractions, variantStates as variantStatesImpl, animationLoops, flattenStyles } from './interactions.mjs';
5
+
6
+ const VECTORISH = new Set(['VECTOR', 'STAR', 'LINE', 'REGULAR_POLYGON', 'BOOLEAN_OPERATION']);
7
+ const CONTAINERS = new Set(['FRAME', 'SYMBOL', 'INSTANCE', 'SECTION', 'GROUP']);
8
+ export const AUTO_NAME = /^(frame|group|rectangle|ellipse|vector|line|star|polygon|union|subtract|intersect|exclude|mask group|component|instance|image|layer|property 1=.*)( \d+)?$/i;
9
+
10
+ // ---------------------------------------------------------------- paints
11
+ function invert(t) {
12
+ const det = t.m00 * t.m11 - t.m01 * t.m10 || 1e-9;
13
+ const a = t.m11 / det, b = -t.m01 / det, c = -t.m10 / det, d = t.m00 / det;
14
+ return { a, b, c, d, tx: -(a * t.m02 + b * t.m12), ty: -(c * t.m02 + d * t.m12) };
15
+ }
16
+ const apply = (i, x, y) => [i.a * x + i.b * y + i.tx, i.c * x + i.d * y + i.ty];
17
+
18
+ function stopColor(s, p, reg) { return (reg && s.colorVar && reg.aliasVar(s.colorVar)) || cssColor(s.color, p.opacity ?? 1); }
19
+
20
+ function gradientCss(p, w, h, reg) {
21
+ const t = p.transform || { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 };
22
+ const inv = invert(t);
23
+ const stopsSrc = (p.stopsVar?.length ? p.stopsVar : p.stops) || [];
24
+ if (p.type === 'GRADIENT_LINEAR') {
25
+ const [x0, y0] = apply(inv, 0, 0.5), [x1, y1] = apply(inv, 1, 0.5);
26
+ const sx = x0 * w, sy = y0 * h, ex = x1 * w, ey = y1 * h;
27
+ const angle = Math.atan2(ex - sx, -(ey - sy));
28
+ const deg = ((angle * 180 / Math.PI) % 360 + 360) % 360;
29
+ const L = Math.abs(w * Math.sin(angle)) + Math.abs(h * Math.cos(angle)) || 1;
30
+ const dir = [Math.sin(angle), -Math.cos(angle)];
31
+ const proj = (x, y) => ((x - w / 2) * dir[0] + (y - h / 2) * dir[1]) / L + 0.5;
32
+ const t0 = proj(sx, sy), t1 = proj(ex, ey);
33
+ const stops = stopsSrc.map(s => `${stopColor(s, p, reg)} ${r2((t0 + s.position * (t1 - t0)) * 100)}%`).join(', ');
34
+ return `linear-gradient(${Math.round(deg)}deg, ${stops})`;
35
+ }
36
+ const [cx, cy] = apply(inv, 0.5, 0.5);
37
+ const stops = stopsSrc.map(s => `${stopColor(s, p, reg)} ${r2(s.position * 100)}%`).join(', ');
38
+ if (p.type === 'GRADIENT_RADIAL' || p.type === 'GRADIENT_DIAMOND') {
39
+ const [rx1, ry1] = apply(inv, 1, 0.5), [rx2, ry2] = apply(inv, 0.5, 1);
40
+ const rx = Math.hypot((rx1 - cx) * w, (ry1 - cy) * h), ry = Math.hypot((rx2 - cx) * w, (ry2 - cy) * h);
41
+ return `radial-gradient(${r2(rx)}px ${r2(ry)}px at ${r2(cx * 100)}% ${r2(cy * 100)}%, ${stops})`;
42
+ }
43
+ if (p.type === 'GRADIENT_ANGULAR') {
44
+ const [ax, ay] = apply(inv, 1, 0.5);
45
+ const from = Math.round((Math.atan2((ax - cx) * w, -(ay - cy) * h) * 180 / Math.PI + 360) % 360);
46
+ return `conic-gradient(from ${from}deg at ${r2(cx * 100)}% ${r2(cy * 100)}%, ${stops})`;
47
+ }
48
+ return `/* ${p.type} */`;
49
+ }
50
+
51
+ // ---------------------------------------------------------------- assets
52
+ export class AssetRegistry {
53
+ constructor(doc) { this.doc = doc; this.images = new Map(); this.svgs = new Map(); this.rasters = new Map(); this.names = new Set(); }
54
+ image(paint) {
55
+ const h = hex(paint.image.hash);
56
+ if (!this.images.has(h)) {
57
+ const bytes = this.doc.readImage(h);
58
+ const ext = bytes ? sniffExt(bytes) : 'png';
59
+ this.images.set(h, { hash: h, file: `${h.slice(0, 16)}.${ext}`, missing: !bytes, width: paint.originalImageWidth, height: paint.originalImageHeight });
60
+ }
61
+ return `assets/${this.images.get(h).file}`;
62
+ }
63
+ _name(base, ext) {
64
+ let name = `${slug(base).slice(0, 48) || 'asset'}.${ext}`, i = 2;
65
+ while (this.names.has(name)) name = `${slug(base).slice(0, 48) || 'asset'}-${i++}.${ext}`;
66
+ this.names.add(name); return name;
67
+ }
68
+ svg(node, key, label, src = {}) {
69
+ if (!this.svgs.has(key)) this.svgs.set(key, { file: this._name(label, 'svg'), node, ...src });
70
+ return `assets/${this.svgs.get(key).file}`;
71
+ }
72
+ raster(node, label, src = {}) {
73
+ const key = idOf(node);
74
+ if (!this.rasters.has(key)) this.rasters.set(key, { file: this._name(label, 'png'), node, ...src });
75
+ return `assets/${this.rasters.get(key).file}`;
76
+ }
77
+ }
78
+
79
+ // ---------------------------------------------------------------- converter
80
+ export class Converter {
81
+ static seq = 0;
82
+ constructor(doc, opts = {}) {
83
+ this.doc = doc;
84
+ this.tokens = opts.tokens || new TokenRegistry(doc);
85
+ this.assets = opts.assets || new AssetRegistry(doc);
86
+ this.components = new Map(); // symbolId -> info
87
+ this.fonts = new Map();
88
+ this.interactions = [];
89
+ this.stats = { nodes: 0, hidden: 0, text: 0, instances: 0, vectors: 0, images: 0 };
90
+ this.iconMaxSize = opts.iconMaxSize ?? 64;
91
+ this.pinTextBoxes = !!opts.pinTextBoxes;
92
+ }
93
+
94
+ // ---- overrides & component properties
95
+ overrideMap(inst) {
96
+ const m = new Map();
97
+ for (const o of inst.derivedSymbolData || []) { const k = o.guidPath?.guids?.map(gid).join('/'); if (k) m.set(k, o); }
98
+ for (const o of inst.symbolData?.symbolOverrides || []) {
99
+ const k = o.guidPath?.guids?.map(gid).join('/'); if (!k) continue;
100
+ m.set(k, { ...(m.get(k) || {}), ...o });
101
+ }
102
+ return m;
103
+ }
104
+ applyContext(raw, ctx) {
105
+ let n = raw;
106
+ if (ctx.levels.length) {
107
+ const key = raw.overrideKey && raw.overrideKey.sessionID !== NULL_GUID ? gid(raw.overrideKey) : idOf(raw);
108
+ for (let i = ctx.levels.length - 1; i >= 0; i--) { // innermost first, outermost wins
109
+ const { map, prefix } = ctx.levels[i];
110
+ const o = map.get([...prefix, key].join('/'));
111
+ if (o) { n = n === raw ? { ...raw } : n; for (const [k, v] of Object.entries(o)) if (k !== 'guidPath' && k !== 'guid' && k !== 'parentIndex' && k !== 'overrideKey') n[k] = v; }
112
+ }
113
+ }
114
+ if (raw.componentPropRefs?.length && ctx.props.size) {
115
+ for (const ref of raw.componentPropRefs) {
116
+ if (ref.isDeleted) continue;
117
+ const v = ctx.props.get(gid(ref.defID)); if (!v) continue;
118
+ n = n === raw ? { ...raw } : n;
119
+ if (ref.componentPropNodeField === 'VISIBLE' && v.boolValue !== undefined) n.visible = v.boolValue;
120
+ else if (ref.componentPropNodeField === 'TEXT_DATA' && v.textValue) n.textData = v.textValue;
121
+ else if (ref.componentPropNodeField === 'OVERRIDDEN_SYMBOL_ID' && v.guidValue) n.overriddenSymbolID = v.guidValue;
122
+ }
123
+ }
124
+ return n;
125
+ }
126
+
127
+ // ---- css
128
+ fill(n, w, h) {
129
+ const paints = (n.fillPaints || []).filter(p => p.visible !== false && (p.opacity ?? 1) > 0);
130
+ if (!paints.length) return null;
131
+ const layers = paints.map(p => this.paint(p, w, h)).filter(Boolean).reverse();
132
+ return layers.join(', ');
133
+ }
134
+ paint(p, w, h) {
135
+ if (p.type === 'SOLID') return (p.colorVar && this.tokens.aliasVar(p.colorVar)) || cssColor(p.color, p.opacity ?? 1);
136
+ if (p.type?.startsWith('GRADIENT')) return gradientCss(p, w, h, this.tokens);
137
+ if (p.type === 'IMAGE' && p.image?.hash) {
138
+ this.stats.images++;
139
+ const url = this.assets.image(p);
140
+ const fit = { FILL: 'cover', FIT: 'contain', STRETCH: '100% 100%' }[p.imageScaleMode];
141
+ if (p.imageScaleMode === 'TILE') return `url(${url}) 0 0 / ${r2((p.originalImageWidth || 100) * (p.scale || 1))}px repeat`;
142
+ return `url(${url}) center / ${fit || 'cover'} no-repeat`;
143
+ }
144
+ return null;
145
+ }
146
+ isSolidOnly(n) { const f = (n.fillPaints || []).filter(p => p.visible !== false); return f.length === 1 && f[0].type === 'SOLID'; }
147
+
148
+ boxCss(n, parent, isRoot, kids = []) {
149
+ const css = {};
150
+ const t = n.transform || { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 };
151
+ const pAuto = parent && parent.stackMode && parent.stackMode !== 'NONE' && parent.stackMode !== 'GRID';
152
+ const inFlow = pAuto && n.stackPositioning !== 'ABSOLUTE';
153
+ if (!isRoot && !inFlow) { css.position = 'absolute'; css.left = `${r2(t.m02)}px`; css.top = `${r2(t.m12)}px`; }
154
+ if (!isRoot) {
155
+ const isIdentity = Math.abs(t.m00 - 1) < 1e-4 && Math.abs(t.m11 - 1) < 1e-4 && Math.abs(t.m01) < 1e-4 && Math.abs(t.m10) < 1e-4;
156
+ if (!isIdentity) {
157
+ const rot = Math.atan2(t.m10, t.m00), det = t.m00 * t.m11 - t.m01 * t.m10;
158
+ css.transform = det > 0 && Math.abs(Math.hypot(t.m00, t.m10) - 1) < 1e-3 ? `rotate(${r2(rot * 180 / Math.PI)}deg)` : `matrix(${[t.m00, t.m10, t.m01, t.m11, 0, 0].map(v => r2(v)).join(', ')})`;
159
+ css['transform-origin'] = '0 0';
160
+ }
161
+ }
162
+ // every in-flow element is a containing block for its absolutely-positioned children
163
+ if (inFlow) css.position = 'relative';
164
+ const w = n.size?.x ?? 0, h = n.size?.y ?? 0;
165
+ const horizontalParent = parent?.stackMode === 'HORIZONTAL';
166
+ // own hug sizing
167
+ const auto = n.stackMode && n.stackMode !== 'NONE';
168
+ const hugPrimary = auto && n.stackPrimarySizing && n.stackPrimarySizing !== 'FIXED';
169
+ const hugCounter = auto && n.stackCounterSizing && n.stackCounterSizing !== 'FIXED';
170
+ let hugW = n.stackMode === 'HORIZONTAL' ? hugPrimary : n.stackMode === 'VERTICAL' ? hugCounter : false;
171
+ let hugH = n.stackMode === 'VERTICAL' ? hugPrimary : n.stackMode === 'HORIZONTAL' ? hugCounter : false;
172
+ // Figma: a container can't hug along an axis where a child fills it (it then keeps its size)
173
+ if (auto && (hugW || hugH)) {
174
+ const flow = kids.filter(k => k.visible !== false && k.stackPositioning !== 'ABSOLUTE');
175
+ const grows = flow.some(k => k.stackChildPrimaryGrow > 0), stretches = flow.some(k => k.stackChildAlignSelf === 'STRETCH');
176
+ if (n.stackMode === 'HORIZONTAL') { if (grows) hugW = false; if (stretches) hugH = false; }
177
+ else { if (grows) hugH = false; if (stretches) hugW = false; }
178
+ }
179
+ if (n.type === 'TEXT') { hugW = n.textAutoResize === 'WIDTH_AND_HEIGHT'; hugH = n.textAutoResize === 'WIDTH_AND_HEIGHT' || n.textAutoResize === 'HEIGHT'; }
180
+ // pinTextBoxes: size text boxes exactly as Figma measured them (font-independent layout; used by the fidelity test)
181
+ if (n.type === 'TEXT' && this.pinTextBoxes) { hugW = false; hugH = false; }
182
+ let fillW = false, fillH = false;
183
+ if (inFlow) {
184
+ const grow = n.stackChildPrimaryGrow > 0, stretch = n.stackChildAlignSelf === 'STRETCH';
185
+ if (horizontalParent) { fillW = grow; fillH = stretch; } else { fillH = grow; fillW = stretch; }
186
+ if (grow) css.flex = '1 1 0';
187
+ if (stretch) css['align-self'] = 'stretch';
188
+ else if (n.stackChildAlignSelf && n.stackChildAlignSelf !== 'AUTO') css['align-self'] = { MIN: 'flex-start', CENTER: 'center', MAX: 'flex-end', BASELINE: 'baseline' }[n.stackChildAlignSelf];
189
+ for (const [k, c] of [['Top', 'margin-top'], ['Right', 'margin-right'], ['Bottom', 'margin-bottom'], ['Left', 'margin-left']]) if (n[`stackChildMargin${k}`]) css[c] = `${r2(n[`stackChildMargin${k}`])}px`;
190
+ css['flex-shrink'] = grow ? undefined : 0;
191
+ }
192
+ if (!fillW && !(hugW && !isRoot)) css.width = `${r2(w)}px`;
193
+ if (!fillH && !(hugH && !isRoot)) css.height = `${r2(h)}px`;
194
+ if (fillW && !horizontalParent) css.width = 'auto';
195
+ if (isRoot) css.position = 'relative';
196
+ if (inFlow && parent.stackSpacing < 0 && n._index > 0) css[horizontalParent ? 'margin-left' : 'margin-top'] = `${r2(parent.stackSpacing)}px`;
197
+ if (Object.keys(css).length && css['flex-shrink'] === undefined) delete css['flex-shrink'];
198
+ return css;
199
+ }
200
+
201
+ styleCss(n) {
202
+ const css = {};
203
+ const w = n.size?.x ?? 0, h = n.size?.y ?? 0;
204
+ const cm = this.consumption(n);
205
+ if (n.stackMode && n.stackMode !== 'NONE') {
206
+ if (n.stackMode === 'GRID') css.display = 'grid';
207
+ else { css.display = 'flex'; if (n.stackMode === 'VERTICAL') css['flex-direction'] = 'column'; }
208
+ if (n.stackReverseZIndex) css['/* z-order */'] = 'first child on top';
209
+ const sp = n.stackSpacing || 0;
210
+ const between = /^SPACE_/.test(n.stackPrimaryAlignItems || '');
211
+ if (sp > 0 && !between) css.gap = cm.STACK_SPACING || `${r2(sp)}px`;
212
+ if (n.stackWrap === 'WRAP') { css['flex-wrap'] = 'wrap'; if (n.stackCounterSpacing) css['row-gap'] = cm.STACK_COUNTER_SPACING || `${r2(n.stackCounterSpacing)}px`; }
213
+ const pl = n.stackHorizontalPadding ?? 0, pt = n.stackVerticalPadding ?? 0, pr = n.stackPaddingRight ?? pl, pb = n.stackPaddingBottom ?? pt;
214
+ if (pt || pr || pb || pl) css.padding = [cm.STACK_PADDING_TOP || `${r2(pt)}px`, cm.STACK_PADDING_RIGHT || `${r2(pr)}px`, cm.STACK_PADDING_BOTTOM || `${r2(pb)}px`, cm.STACK_PADDING_LEFT || `${r2(pl)}px`].join(' ');
215
+ const jc = { MIN: null, CENTER: 'center', MAX: 'flex-end', SPACE_EVENLY: 'space-between', SPACE_BETWEEN: 'space-between', SPACE_AROUND: 'space-around', SPACE_EVENLY_CSS: 'space-evenly' }[n.stackPrimaryAlignItems];
216
+ const ai = { MIN: 'flex-start', CENTER: 'center', MAX: 'flex-end', BASELINE: 'baseline' }[n.stackCounterAlignItems || 'MIN'];
217
+ if (jc) css['justify-content'] = jc;
218
+ css['align-items'] = ai;
219
+ }
220
+ if (n.type !== 'TEXT') {
221
+ const bg = this.fill(n, w, h);
222
+ if (bg) {
223
+ const st = this.doc.styleRef(n.styleIdForFill);
224
+ css.background = st && this.isSolidOnly(n) && !bg.startsWith('var(') ? `var(${this.tokens.styleVar(st)}, ${bg})` : bg;
225
+ }
226
+ }
227
+ // strokes
228
+ const strokes = (n.strokePaints || []).filter(p => p.visible !== false);
229
+ if (strokes.length && n.strokeWeight > 0 && !VECTORISH.has(n.type) && n.type !== 'TEXT') {
230
+ let c = this.paint(strokes[0], w, h) || 'currentColor';
231
+ if (c.includes('gradient(')) { css['/* stroke */'] = `gradient stroke: ${c}`; c = cssColor(strokes[0].stops?.[0]?.color || { r: 0, g: 0, b: 0, a: 1 }); }
232
+ const st = this.doc.styleRef(n.styleIdForStrokeFill);
233
+ if (st && !c.startsWith('var(')) c = `var(${this.tokens.styleVar(st)}, ${c})`;
234
+ const style = n.dashPattern?.length ? 'dashed' : 'solid';
235
+ const sw = cm.STROKE_WEIGHT || `${r2(n.strokeWeight)}px`;
236
+ if (n.borderStrokeWeightsIndependent) {
237
+ for (const s of ['Top', 'Right', 'Bottom', 'Left']) { const bw = n[`border${s}Weight`]; if (bw) css[`border-${s.toLowerCase()}`] = `${r2(bw)}px ${style} ${c}`; }
238
+ } else {
239
+ // Figma strokes never affect layout -> outline (inside: negative offset) instead of border
240
+ css.outline = `${sw} ${style} ${c}`;
241
+ const off = n.strokeAlign === 'OUTSIDE' ? 0 : n.strokeAlign === 'CENTER' ? n.strokeWeight / 2 : n.strokeWeight;
242
+ if (off) css['outline-offset'] = `-${r2(off)}px`;
243
+ }
244
+ }
245
+ // radius
246
+ if (n.type === 'ELLIPSE') css['border-radius'] = '50%';
247
+ else if (n.rectangleCornerRadiiIndependent) {
248
+ const v = ['TopLeft', 'TopRight', 'BottomRight', 'BottomLeft'].map(k => n[`rectangle${k}CornerRadius`] ?? 0);
249
+ if (v.some(Boolean)) css['border-radius'] = v.map(x => `${r2(x)}px`).join(' ');
250
+ } else if (n.cornerRadius) css['border-radius'] = cm.CORNER_RADIUS || `${r2(n.cornerRadius)}px`;
251
+ if (n.opacity != null && n.opacity < 1) css.opacity = cm.OPACITY || r2(n.opacity);
252
+ if (n.blendMode && !['NORMAL', 'PASS_THROUGH'].includes(n.blendMode)) css['mix-blend-mode'] = n.blendMode.toLowerCase().replace(/_/g, '-').replace('linear-burn', 'color-burn').replace('linear-dodge', 'color-dodge');
253
+ const fx = effectsCss(n.effects, this.tokens);
254
+ const est = this.doc.styleRef(n.styleIdForEffect);
255
+ if (fx['box-shadow'] && est) fx['box-shadow'] = `var(${this.tokens.styleVar(est)}, ${fx['box-shadow']})`;
256
+ if (n.type === 'TEXT' && fx['box-shadow']) {
257
+ // text layers: drop shadows become text-shadow (no spread / inset in CSS text-shadow)
258
+ const ts = (n.effects || []).filter(e => e.visible !== false && e.type === 'DROP_SHADOW')
259
+ .map(e => `${r2(e.offset?.x || 0)}px ${r2(e.offset?.y || 0)}px ${r2(e.radius || 0)}px ${(e.colorVar && this.tokens.aliasVar(e.colorVar)) || cssColor(e.color)}`);
260
+ if (ts.length) fx['text-shadow'] = ts.join(', ');
261
+ delete fx['box-shadow'];
262
+ }
263
+ Object.assign(css, fx);
264
+ if (CONTAINERS.has(n.type) && n.type !== 'SECTION' && n.frameMaskDisabled !== true && n.type !== 'GROUP' && !n.resizeToFit) css.overflow = 'hidden';
265
+ if (n.scrollDirection && n.scrollDirection !== 'NONE') css.overflow = n.scrollDirection === 'VERTICAL' ? 'hidden auto' : n.scrollDirection === 'HORIZONTAL' ? 'auto hidden' : 'auto';
266
+ if (n.type === 'TEXT') Object.assign(css, this.textCss(n, cm));
267
+ return css;
268
+ }
269
+
270
+ consumption(n) {
271
+ const out = {};
272
+ for (const e of n.variableConsumptionMap?.entries || []) {
273
+ const v = this.tokens.aliasVar(e.variableData);
274
+ if (v && e.variableField) out[e.variableField] = v;
275
+ }
276
+ return out;
277
+ }
278
+
279
+ textCss(n, cm = {}) {
280
+ const f = n.fontName || {};
281
+ const key = `${f.family}|${f.style}`;
282
+ if (!this.fonts.has(key)) this.fonts.set(key, { family: f.family, style: f.style, weight: fontWeight(f.style), italic: /italic/i.test(f.style || ''), postscript: f.postscript || undefined });
283
+ const css = typographyCss(n);
284
+ if (cm.FONT_SIZE) css['font-size'] = cm.FONT_SIZE;
285
+ if (cm.LINE_HEIGHT) css['line-height'] = cm.LINE_HEIGHT;
286
+ if (cm.LETTER_SPACING) css['letter-spacing'] = cm.LETTER_SPACING;
287
+ const align = n.textAlignHorizontal;
288
+ if (align && align !== 'LEFT') css['text-align'] = align === 'JUSTIFIED' ? 'justify' : align.toLowerCase();
289
+ if (n.textAutoResize === 'WIDTH_AND_HEIGHT') css['white-space'] = 'nowrap';
290
+ else css['white-space'] = 'pre-wrap';
291
+ if (n.textTruncation === 'ENDING') {
292
+ if (n.maxLines > 1) Object.assign(css, { display: '-webkit-box', '-webkit-line-clamp': n.maxLines, '-webkit-box-orient': 'vertical', overflow: 'hidden' });
293
+ else Object.assign(css, { overflow: 'hidden', 'text-overflow': 'ellipsis', 'white-space': 'nowrap' });
294
+ }
295
+ if (n.textAlignVertical && n.textAlignVertical !== 'TOP' && n.textAutoResize !== 'WIDTH_AND_HEIGHT' && n.textAutoResize !== 'HEIGHT' && css.display === undefined) {
296
+ Object.assign(css, { display: 'flex', 'flex-direction': 'column', 'justify-content': n.textAlignVertical === 'CENTER' ? 'center' : 'flex-end' });
297
+ }
298
+ if (n.paragraphSpacing) css['/* paragraph-spacing */'] = `${r2(n.paragraphSpacing)}px between paragraphs`;
299
+ const fills = (n.fillPaints || []).filter(p => p.visible !== false);
300
+ const st = this.doc.styleRef(n.styleIdForFill);
301
+ if (fills.length === 1 && fills[0].type === 'SOLID') {
302
+ const c = this.paint(fills[0], n.size?.x, n.size?.y);
303
+ css.color = st && !c.startsWith('var(') ? `var(${this.tokens.styleVar(st)}, ${c})` : c;
304
+ } else if (fills.length) {
305
+ css.background = fills.map(p => this.paint(p, n.size?.x || 1, n.size?.y || 1)).filter(Boolean).reverse().join(', ');
306
+ css['-webkit-background-clip'] = 'text'; css['background-clip'] = 'text'; css.color = 'transparent';
307
+ }
308
+ return css;
309
+ }
310
+
311
+ textRuns(n) {
312
+ const td = n.textData; const ids = td?.characterStyleIDs;
313
+ if (!ids?.length || !td.styleOverrideTable?.length) return null;
314
+ const table = new Map(td.styleOverrideTable.map(s => [s.styleID, s]));
315
+ const chars = [...(td.characters || '')];
316
+ const runs = []; let cur = null;
317
+ chars.forEach((ch, i) => { const sid = ids[i] ?? 0; if (!cur || cur.sid !== sid) { cur = { sid, text: '' }; runs.push(cur); } cur.text += ch; });
318
+ if (runs.length < 2) return null;
319
+ const base = this.textCss(n);
320
+ return runs.map(r => {
321
+ const o = table.get(r.sid);
322
+ if (!o) return { text: r.text };
323
+ const merged = { ...n, ...o, textAutoResize: 'HEIGHT', textAlignVertical: 'TOP', textTruncation: undefined };
324
+ const css = this.textCss(merged);
325
+ const diff = {};
326
+ for (const [k, v] of Object.entries(css)) if (base[k] !== v && !k.startsWith('/*') && k !== 'white-space' && k !== 'display') diff[k] = v;
327
+ if (o.hyperlink?.url) diff['/* link */'] = o.hyperlink.url;
328
+ return { text: r.text, css: diff };
329
+ });
330
+ }
331
+
332
+ interactionsOf(n) { return describeInteractions(this.doc, n); }
333
+
334
+ // ---- classification
335
+ isIcon(n) {
336
+ if (!['FRAME', 'INSTANCE', 'SYMBOL', 'GROUP', 'BOOLEAN_OPERATION'].includes(n.type) || !n.size) return false;
337
+ if (n.size.x > this.iconMaxSize || n.size.y > this.iconMaxSize) return false;
338
+ let ok = true, any = false, count = 0;
339
+ const walk = (m, depth) => {
340
+ if (!ok || depth > 8) return;
341
+ const kids = m.type === 'INSTANCE' ? this.doc.children(this.doc.node(gid(m.overriddenSymbolID || m.symbolData?.symbolID)) || {}) : this.doc.children(m);
342
+ for (const c of kids) {
343
+ if (++count > 200) { ok = false; return; }
344
+ if (c.type === 'TEXT') { ok = false; return; }
345
+ if ((c.fillPaints || []).some(p => p.type === 'IMAGE' && p.visible !== false)) { ok = false; return; }
346
+ if (VECTORISH.has(c.type) || c.type === 'ELLIPSE' || c.type === 'ROUNDED_RECTANGLE' || c.type === 'RECTANGLE') any = true;
347
+ walk(c, depth + 1);
348
+ }
349
+ };
350
+ if (n.type === 'INSTANCE' && !n.symbolData) return false;
351
+ walk(n, 0);
352
+ return ok && any;
353
+ }
354
+ singleImage(n, kids) {
355
+ if (kids.length) return null;
356
+ const fills = (n.fillPaints || []).filter(p => p.visible !== false);
357
+ return fills.length === 1 && fills[0].type === 'IMAGE' && fills[0].image?.hash ? fills[0] : null;
358
+ }
359
+
360
+ /** Context for descending into an instance's component children. */
361
+ enterInstance(raw, n, sym, ctx) {
362
+ const set = this.doc.componentSet(sym);
363
+ const props = new Map(ctx.props);
364
+ const defs = (set || sym).componentPropDefs || [];
365
+ for (const d of defs) if (d.type !== 'VARIANT' && d.initialValue && !props.has(gid(d.id))) props.set(gid(d.id), d.initialValue);
366
+ const assigned = {};
367
+ for (const a of n.componentPropAssignments || []) {
368
+ props.set(gid(a.defID), a.value);
369
+ const def = defs.find(d => gid(d.id) === gid(a.defID));
370
+ if (def) assigned[def.name.replace(/#.*$/, '')] = a.value?.textValue?.characters ?? a.value?.boolValue ?? (a.value?.guidValue ? this.doc.node(gid(a.value.guidValue))?.name : undefined);
371
+ }
372
+ const instKey = raw.overrideKey && raw.overrideKey.sessionID !== NULL_GUID ? gid(raw.overrideKey) : idOf(raw);
373
+ const childCtx = { levels: [...ctx.levels.map(l => ({ map: l.map, prefix: [...l.prefix, instKey] })), { map: this.overrideMap(n), prefix: [] }], props, idPrefix: ctx.idPrefix ? `${ctx.idPrefix};${idOf(raw)}` : `I${idOf(raw)}` };
374
+ return { props, assigned, childCtx };
375
+ }
376
+
377
+ /**
378
+ * Expand a subtree into plain nodes with every instance override / component property applied,
379
+ * registered temporarily in the deck so openfig's SVG renderer draws what Figma shows.
380
+ * Returns { root, cleanup }.
381
+ */
382
+ materialize(raw, ctx = { levels: [], props: new Map() }) {
383
+ const deck = this.doc.deck, keys = [];
384
+ const visit = (r, c, parentGuid, idx, isRoot) => {
385
+ const n = this.applyContext(r, c);
386
+ if (n.visible === false && !isRoot) return null;
387
+ const guid = { sessionID: 999999990, localID: ++Converter.seq };
388
+ const copy = { ...n, guid, visible: true, parentIndex: { guid: parentGuid || guid, position: String(idx).padStart(6, '0') }, _fid: c.idPrefix ? `${c.idPrefix};${idOf(r)}` : idOf(r) };
389
+ let kids = this.doc.children(r), cc = c;
390
+ if (n.type === 'INSTANCE') {
391
+ const sym = this.doc.node(gid(n.overriddenSymbolID || n.symbolData?.symbolID));
392
+ if (sym) {
393
+ cc = this.enterInstance(r, n, sym, c).childCtx;
394
+ kids = this.doc.children(sym);
395
+ copy.type = 'FRAME';
396
+ for (const k of ['fillPaints', 'strokePaints', 'effects', 'cornerRadius', 'frameMaskDisabled', 'strokeWeight', 'strokeAlign']) if (copy[k] === undefined && sym[k] !== undefined) copy[k] = sym[k];
397
+ delete copy.symbolData; delete copy.derivedSymbolData;
398
+ }
399
+ }
400
+ const list = [];
401
+ for (const k of kids) { const m = visit(k, cc, guid, list.length, false); if (m) list.push(m); }
402
+ const key = gid(guid);
403
+ deck.childrenMap.set(key, list); deck.nodeMap.set(key, copy); keys.push(key);
404
+ return copy;
405
+ };
406
+ const root = visit(raw, ctx, raw.parentIndex?.guid, 0, true);
407
+ return { root, cleanup: () => { for (const k of keys) { deck.childrenMap.delete(k); deck.nodeMap.delete(k); } } };
408
+ }
409
+
410
+ // ---- tree
411
+ build(raw, parent = null, ctx = { levels: [], props: new Map() }, isRoot = true, index = 0) {
412
+ if (raw.phase === 'REMOVED') return null;
413
+ const n0 = this.applyContext(raw, ctx);
414
+ if (n0.visible === false) { this.stats.hidden++; return null; }
415
+ const n = index ? { ...n0, _index: index } : n0;
416
+ this.stats.nodes++;
417
+ const spec = { id: ctx.idPrefix ? `${ctx.idPrefix};${idOf(raw)}` : idOf(raw), name: n.name, type: n.type };
418
+ const symForBox = n.type === 'INSTANCE' ? this.doc.node(gid(n.overriddenSymbolID || n.symbolData?.symbolID)) : null;
419
+ spec.box = this.boxCss(n, parent, isRoot, this.doc.children(symForBox || raw));
420
+ spec.style = this.styleCss(n);
421
+ const st = this.doc.styleRef(n.styleIdForText);
422
+ if (n.type === 'TEXT') {
423
+ this.stats.text++;
424
+ spec.text = n.textData?.characters ?? '';
425
+ const runs = this.textRuns(n); if (runs) spec.runs = runs;
426
+ if (st) spec.textStyle = { name: st.name, className: this.tokens.textClass(st) };
427
+ if (n.hyperlink?.url) spec.href = n.hyperlink.url;
428
+ }
429
+ // instances inherit the main component's prototype interactions unless they override them
430
+ const ix = this.interactionsOf(n.type === 'INSTANCE' && !n.prototypeInteractions?.length && symForBox ? symForBox : n);
431
+ if (n.scrollBehavior === 'FIXED_WHEN_CHILD_OF_SCROLLING_FRAME') spec.scroll = 'fixed';
432
+ else if (n.scrollBehavior === 'STICKY_SCROLLS') spec.scroll = 'sticky';
433
+ if (ix) { spec.interactions = ix; this.interactions.push({ node: spec, from: n, list: ix }); }
434
+ if (n.horizontalConstraint || n.verticalConstraint) spec.constraints = { h: n.horizontalConstraint || 'MIN', v: n.verticalConstraint || 'MIN' };
435
+ if (n.exportSettings?.length) spec.exportSettings = n.exportSettings.map(e => `${e.imageType}${e.constraint?.value && e.constraint.value !== 1 ? '@' + e.constraint.value + 'x' : ''}`);
436
+
437
+ let kids = this.doc.children(raw);
438
+ let childCtx = ctx, layoutParent = n;
439
+ if (n.type === 'INSTANCE') {
440
+ this.stats.instances++;
441
+ const sym = this.doc.node(gid(n.overriddenSymbolID || n.symbolData?.symbolID));
442
+ if (sym) {
443
+ const set = this.doc.componentSet(sym);
444
+ const name = this.doc.componentName(sym);
445
+ const variant = this.doc.variantProps(sym);
446
+ spec.component = { name, id: idOf(set || sym), variant: variant || undefined };
447
+ const { props, assigned, childCtx: cc } = this.enterInstance(raw, n, sym, ctx);
448
+ if (Object.keys(assigned).length) spec.component.props = assigned;
449
+ const key = idOf(sym);
450
+ if (!this.components.has(key)) this.components.set(key, { name, setId: set ? idOf(set) : undefined, symbolId: key, variant: variant || undefined, uses: 0, description: (set || sym).symbolDescription || undefined });
451
+ this.components.get(key).uses++;
452
+ kids = this.doc.children(sym);
453
+ childCtx = cc;
454
+ layoutParent = { ...sym, ...n, stackMode: n.stackMode ?? sym.stackMode, stackSpacing: n.stackSpacing ?? sym.stackSpacing };
455
+ } else spec.component = { name: '(missing component)', id: gid(n.symbolData?.symbolID) };
456
+ }
457
+ // leaf assets
458
+ const hasMask = kids.some(k => k.mask);
459
+ if (VECTORISH.has(n.type) || (!isRoot && this.isIcon(n))) {
460
+ this.stats.vectors++;
461
+ const label = spec.component?.name && !AUTO_NAME.test(spec.component.name) ? spec.component.name : (AUTO_NAME.test(n.name) ? n.type.toLowerCase() : n.name);
462
+ const pureInstance = n.type === 'INSTANCE' && !n.symbolData?.symbolOverrides?.length && !ctx.levels.length;
463
+ spec.asset = this.assets.svg(n, pureInstance ? `sym:${spec.component.id}:${r2(n.size.x)}x${r2(n.size.y)}` : `node:${spec.id}:${ctx.levels.length}`, label, { raw, ctx, conv: this });
464
+ spec.assetKind = 'svg';
465
+ return spec;
466
+ }
467
+ if (hasMask && !isRoot) {
468
+ spec.asset = this.assets.raster(n, AUTO_NAME.test(n.name) ? 'masked-group' : n.name, { raw, ctx, conv: this });
469
+ spec.assetKind = 'png';
470
+ spec.note = 'mask group rendered to PNG';
471
+ return spec;
472
+ }
473
+ const img = n.type !== 'TEXT' && !isRoot && this.singleImage(n, kids);
474
+ if (img) { spec.image = { src: spec.style.background?.match(/url\(([^)]+)\)/)?.[1], fit: { FILL: 'cover', FIT: 'contain', TILE: 'none', STRETCH: 'fill' }[img.imageScaleMode] || 'cover', alt: img.altText || undefined }; delete spec.style.background; }
475
+ const children = [];
476
+ kids.forEach((k, i) => { const c = this.build(k, layoutParent, childCtx, false, i); if (c) children.push(c); });
477
+ if (children.length) spec.children = children;
478
+ return spec;
479
+ }
480
+ }
481
+
482
+ // ---------------------------------------------------------------- interactive states (see interactions.mjs)
483
+ export function variantStates(doc, converter) { return variantStatesImpl(doc, converter, Converter); }
484
+ export { animationLoops, flattenStyles };
package/src/deck.mjs ADDED
@@ -0,0 +1,31 @@
1
+ // Minimal deck over openfig-core's parser (the interface the renderer and FigDoc need).
2
+ import { parseFig, parseFigBinary, nodeId } from 'openfig-core';
3
+
4
+ export class Deck {
5
+ /** @param {Uint8Array} bytes a .fig file (ZIP) or a raw canvas.fig (fig-kiwi) */
6
+ static fromBytes(bytes) {
7
+ const isZip = bytes[0] === 0x50 && bytes[1] === 0x4b;
8
+ return new Deck(isZip ? parseFig(bytes) : parseFigBinary(bytes));
9
+ }
10
+ constructor(doc) {
11
+ this.message = doc.message;
12
+ this.schema = doc.schema;
13
+ this.nodeMap = doc.nodeMap;
14
+ this.childrenMap = doc.childrenMap;
15
+ this.images = doc.images || new Map();
16
+ this.deckMeta = doc.meta || null;
17
+ this.thumbnail = doc.thumbnail || null;
18
+ }
19
+ getNode(id) { return this.nodeMap.get(id); }
20
+ getChildren(id) { return this.childrenMap.get(id) || []; }
21
+ /** Image bytes by SHA-1 hex hash (as referenced by IMAGE paints). */
22
+ readImage(hash) { const b = this.images.get(hash) || this.images.get(`images/${hash}`); return b ? Buffer.from(b.buffer, b.byteOffset, b.byteLength) : null; }
23
+ hasImage(hash) { return this.images.has(hash) || this.images.has(`images/${hash}`); }
24
+ /** User-facing pages, in document order. */
25
+ getPages() {
26
+ return this.message.nodeChanges
27
+ .filter(n => n.type === 'CANVAS' && n.phase !== 'REMOVED' && !n.internalOnly && n.name !== 'Internal Only Canvas')
28
+ .sort((a, b) => (a.parentIndex?.position ?? '').localeCompare(b.parentIndex?.position ?? ''));
29
+ }
30
+ }
31
+ export { nodeId };
package/src/doc.mjs ADDED
@@ -0,0 +1,85 @@
1
+ // Loading + indexing a .fig file with openfig-core's parser.
2
+ import { Deck } from './deck.mjs';
3
+ import { statSync, readFileSync } from 'fs';
4
+ import { resolve } from 'path';
5
+ import { gid, idOf, NULL_GUID } from './util.mjs';
6
+
7
+ const cache = new Map(); // abs path -> { mtimeMs, doc }
8
+
9
+ /** Load (cached by path + mtime) and index a .fig file. */
10
+ export async function loadFig(path) {
11
+ const abs = resolve(path);
12
+ const st = statSync(abs);
13
+ const hit = cache.get(abs);
14
+ if (hit && hit.mtimeMs === st.mtimeMs) return hit.doc;
15
+ const buf = readFileSync(abs);
16
+ const deck = Deck.fromBytes(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));
17
+ const doc = new FigDoc(deck, abs);
18
+ cache.set(abs, { mtimeMs: st.mtimeMs, doc });
19
+ return doc;
20
+ }
21
+
22
+ export class FigDoc {
23
+ constructor(deck, path) {
24
+ this.deck = deck;
25
+ this.path = path;
26
+ this.nodes = deck.message.nodeChanges.filter(n => n.phase !== 'REMOVED');
27
+ this.styles = this.nodes.filter(n => n.styleType);
28
+ this.styleByKey = new Map(this.styles.filter(n => n.key).map(n => [n.key, n]));
29
+ this.styleByGuid = new Map(this.styles.map(n => [idOf(n), n]));
30
+ this.variables = this.nodes.filter(n => n.type === 'VARIABLE');
31
+ this.variableSets = this.nodes.filter(n => n.type === 'VARIABLE_SET');
32
+ this.varByGuid = new Map(this.variables.map(n => [idOf(n), n]));
33
+ this.varByKey = new Map(this.variables.filter(n => n.key).map(n => [n.key, n]));
34
+ this.varSetByGuid = new Map(this.variableSets.map(n => [idOf(n), n]));
35
+ this.varSetByKey = new Map(this.variableSets.filter(n => n.key).map(n => [n.key, n]));
36
+ }
37
+ get name() { return this.deck.deckMeta?.file_name || this.path.split(/[\\/]/).pop().replace(/\.fig$/i, ''); }
38
+ get blobs() { return this.deck.message.blobs; }
39
+ readImage(hash) { return this.deck.readImage(hash); }
40
+ node(id) { const n = this.deck.getNode(id); return n && n.phase !== 'REMOVED' ? n : null; }
41
+ parent(n) { return n?.parentIndex ? this.node(gid(n.parentIndex.guid)) : null; }
42
+ children(n) {
43
+ return this.deck.getChildren(idOf(n))
44
+ .filter(c => c.phase !== 'REMOVED')
45
+ .sort((a, b) => (a.parentIndex.position < b.parentIndex.position ? -1 : a.parentIndex.position > b.parentIndex.position ? 1 : 0));
46
+ }
47
+ pages() { return this.deck.getPages(); }
48
+ pageOf(n) { let c = n; while (c && c.type !== 'CANVAS') c = this.parent(c); return c; }
49
+ /** Ancestor chain (excluding DOCUMENT), root first. */
50
+ ancestors(n) { const out = []; let c = n; while (c && c.type !== 'DOCUMENT') { out.unshift(c); c = this.parent(c); } return out; }
51
+ isInternal(n) { const p = this.pageOf(n); return !p || p.internalOnly || p.name === 'Internal Only Canvas'; }
52
+
53
+ styleRef(ref) {
54
+ if (!ref) return null;
55
+ if (ref.assetRef?.key) return this.styleByKey.get(ref.assetRef.key) || null;
56
+ if (ref.guid && ref.guid.sessionID !== NULL_GUID) return this.styleByGuid.get(gid(ref.guid)) || null;
57
+ return null;
58
+ }
59
+ /** Resolve a VariableID {guid|assetRef} to a VARIABLE node. */
60
+ variable(vid) {
61
+ if (!vid) return null;
62
+ if (vid.guid && vid.guid.sessionID !== NULL_GUID) { const v = this.varByGuid.get(gid(vid.guid)); if (v) return v; }
63
+ if (vid.assetRef?.key) return this.varByKey.get(vid.assetRef.key) || null;
64
+ return null;
65
+ }
66
+ variableSet(sid) {
67
+ if (!sid) return null;
68
+ if (sid.guid) { const s = this.varSetByGuid.get(gid(sid.guid)); if (s) return s; }
69
+ if (sid.assetRef?.key) return this.varSetByKey.get(sid.assetRef.key) || null;
70
+ return null;
71
+ }
72
+ /** If a component lives in a variant set, return the set. */
73
+ componentSet(sym) { const p = this.parent(sym); return p?.isStateGroup ? p : null; }
74
+ variantProps(sym) {
75
+ const set = this.componentSet(sym);
76
+ if (!set) return null;
77
+ const defs = new Map((set.componentPropDefs || []).map(p => [gid(p.id), p.name]));
78
+ const props = Object.fromEntries((sym.variantPropSpecs || []).map(v => [defs.get(gid(v.propDefId)) || '?', v.value]));
79
+ if (!Object.keys(props).length) { // fall back to parsing the "A=b, C=d" name
80
+ for (const part of String(sym.name).split(',')) { const [k, v] = part.split('='); if (v !== undefined) props[k.trim()] = v.trim(); }
81
+ }
82
+ return props;
83
+ }
84
+ componentName(sym) { const set = this.componentSet(sym); return set ? set.name : sym.name; }
85
+ }