figma-mcp-console 0.5.3 → 0.6.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.
- package/README.md +4 -0
- package/bin/darwin-amd64/figma-mcp +0 -0
- package/bin/darwin-arm64/figma-mcp +0 -0
- package/bin/linux-amd64/figma-mcp +0 -0
- package/bin/linux-arm64/figma-mcp +0 -0
- package/bin/plugin/code.js +1091 -114
- package/bin/plugin/manifest.json +1 -0
- package/bin/plugin/ui.html +498 -30
- package/bin/windows-amd64/figma-mcp.exe +0 -0
- package/bin/windows-arm64/figma-mcp.exe +0 -0
- package/package.json +2 -2
package/bin/plugin/code.js
CHANGED
|
@@ -2,15 +2,15 @@
|
|
|
2
2
|
// Receives {id, command, params} from the Go bridge (relayed through ui.html),
|
|
3
3
|
// executes it against the Figma Plugin API, and replies {id, result|error}.
|
|
4
4
|
|
|
5
|
-
figma.showUI(__html__, { width:
|
|
5
|
+
figma.showUI(__html__, { width: 280, height: 104 });
|
|
6
6
|
|
|
7
7
|
// Tell the UI which file this plugin window runs in; the UI forwards it to
|
|
8
8
|
// the bridge on every (re)connect so calls can be routed per file when
|
|
9
|
-
// several files run the plugin at once. figma.fileKey
|
|
10
|
-
//
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
});
|
|
9
|
+
// several files run the plugin at once. figma.fileKey needs
|
|
10
|
+
// enablePrivatePluginApi in the manifest, so the file name stays the fallback.
|
|
11
|
+
// readOnly rides along so AI sees it in list_files before it plans an edit.
|
|
12
|
+
const register = () =>
|
|
13
|
+
figma.ui.postMessage({ register: { key: figma.fileKey || undefined, name: figma.root.name, read_only: readOnly } });
|
|
14
14
|
|
|
15
15
|
// ---------- helpers ----------
|
|
16
16
|
|
|
@@ -27,11 +27,92 @@ async function node(id) {
|
|
|
27
27
|
return n;
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
+
// Pages are addressed by id or name. With documentAccess "dynamic-page" a
|
|
31
|
+
// page's children are unreachable until it is loaded, so load it here.
|
|
32
|
+
async function resolvePage(ref) {
|
|
33
|
+
const want = String(ref);
|
|
34
|
+
const lower = want.toLowerCase();
|
|
35
|
+
const pages = figma.root.children;
|
|
36
|
+
let p = pages.find((x) => x.id === want) || pages.find((x) => x.name.toLowerCase() === lower);
|
|
37
|
+
if (!p) {
|
|
38
|
+
const partial = pages.filter((x) => x.name.toLowerCase().indexOf(lower) !== -1);
|
|
39
|
+
if (partial.length > 1) {
|
|
40
|
+
throw new Error("page " + ref + " is ambiguous: " + partial.map((x) => x.name).join(", "));
|
|
41
|
+
}
|
|
42
|
+
p = partial[0];
|
|
43
|
+
}
|
|
44
|
+
if (!p) throw new Error("page not found: " + ref + " (see list_pages)");
|
|
45
|
+
await p.loadAsync();
|
|
46
|
+
return p;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Figma stacks newly combined variants on top of each other and never grows
|
|
50
|
+
// the set to fit them, so the extras are invisible and clipped. Lay them out.
|
|
51
|
+
function arrangeVariants(set) {
|
|
52
|
+
if (set.layoutMode && set.layoutMode !== "NONE") return;
|
|
53
|
+
const gap = 32;
|
|
54
|
+
let y = 0;
|
|
55
|
+
let w = 0;
|
|
56
|
+
for (const v of set.children) {
|
|
57
|
+
v.x = 0;
|
|
58
|
+
v.y = y;
|
|
59
|
+
y += v.height + gap;
|
|
60
|
+
w = Math.max(w, v.width);
|
|
61
|
+
}
|
|
62
|
+
if (y > 0) set.resize(Math.max(w, 1), Math.max(y - gap, 1));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Mutating commands accept one node_id or many node_ids so a bulk edit costs
|
|
66
|
+
// one call instead of one per node.
|
|
67
|
+
async function targets(params) {
|
|
68
|
+
const ids = params.node_ids && params.node_ids.length
|
|
69
|
+
? params.node_ids
|
|
70
|
+
: params.node_id ? [params.node_id] : [];
|
|
71
|
+
if (!ids.length) throw new Error("node_id or node_ids is required");
|
|
72
|
+
const out = [];
|
|
73
|
+
for (const id of ids) out.push(await node(id));
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Result of a mutating command. Echoing a full summary per node drowns the
|
|
78
|
+
// caller's context on a 50-node batch, so default to ids and let the caller
|
|
79
|
+
// ask for the rest with verbose.
|
|
80
|
+
function done(params, nodes, extra) {
|
|
81
|
+
const list = Array.isArray(nodes) ? nodes : [nodes];
|
|
82
|
+
const out = params.verbose
|
|
83
|
+
? { nodes: list.map(summarize) }
|
|
84
|
+
: { ok: true, ids: list.map((n) => n.id) };
|
|
85
|
+
return Object.assign(out, extra || {});
|
|
86
|
+
}
|
|
87
|
+
|
|
30
88
|
// Mixed values (figma.mixed) are Symbols, which postMessage cannot clone.
|
|
31
89
|
function val(x) {
|
|
32
90
|
return x === figma.mixed ? "mixed" : x;
|
|
33
91
|
}
|
|
34
92
|
|
|
93
|
+
function rgbToHex(c) {
|
|
94
|
+
const h = (v) => ("0" + Math.round(v * 255).toString(16)).slice(-2);
|
|
95
|
+
return "#" + h(c.r) + h(c.g) + h(c.b);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// A full PaintObject is ~20 lines of JSON (17-digit float channels, complete
|
|
99
|
+
// gradientTransform); compact callers only ever need the color.
|
|
100
|
+
function paintBrief(p) {
|
|
101
|
+
if (p.visible === false) return "hidden";
|
|
102
|
+
if (p.type !== "SOLID") return p.type;
|
|
103
|
+
const hex = rgbToHex(p.color);
|
|
104
|
+
return p.opacity === undefined || p.opacity === 1 ? hex : hex + "@" + p.opacity;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// First visible solid fill as hex, for find_nodes' fill filter.
|
|
108
|
+
function solidFillHex(n) {
|
|
109
|
+
if (!("fills" in n) || !Array.isArray(n.fills)) return null;
|
|
110
|
+
for (const p of n.fills) {
|
|
111
|
+
if (p.type === "SOLID" && p.visible !== false) return rgbToHex(p.color);
|
|
112
|
+
}
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
|
|
35
116
|
function summarize(n) {
|
|
36
117
|
const s = { id: n.id, name: n.name, type: n.type };
|
|
37
118
|
if (n.parent) s.parentId = n.parent.id;
|
|
@@ -41,16 +122,48 @@ function summarize(n) {
|
|
|
41
122
|
return s;
|
|
42
123
|
}
|
|
43
124
|
|
|
44
|
-
|
|
125
|
+
// The file key needed to build share links. Development plugins only get
|
|
126
|
+
// figma.fileKey because the manifest sets enablePrivatePluginApi.
|
|
127
|
+
const fileKey = figma.fileKey || "";
|
|
128
|
+
|
|
129
|
+
// nodeLink builds a shareable figma.com URL that jumps straight to a node (the
|
|
130
|
+
// same link as Figma's "Copy link to selection"). Returns null when no file
|
|
131
|
+
// key is known yet, so callers simply omit the link.
|
|
132
|
+
function nodeLink(id) {
|
|
133
|
+
if (!fileKey) return null;
|
|
134
|
+
return (
|
|
135
|
+
"https://www.figma.com/design/" +
|
|
136
|
+
fileKey +
|
|
137
|
+
"/" +
|
|
138
|
+
encodeURIComponent(figma.root.name) +
|
|
139
|
+
"?node-id=" +
|
|
140
|
+
id.replace(/:/g, "-")
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// compact drops defaults (visible, full opacity, empty fills) and renders
|
|
145
|
+
// paints as hex: depth 1 on a 27-child frame is ~15k tokens otherwise.
|
|
146
|
+
// visibleOnly drops hidden layers (and their subtrees): QC scripts would
|
|
147
|
+
// otherwise report them as missing on the web.
|
|
148
|
+
function serialize(n, depth, compact, visibleOnly) {
|
|
45
149
|
const s = summarize(n);
|
|
46
|
-
if (
|
|
47
|
-
|
|
48
|
-
|
|
150
|
+
if (compact) {
|
|
151
|
+
for (const k of ["x", "y", "width", "height"]) {
|
|
152
|
+
if (typeof s[k] === "number") s[k] = Math.round(s[k] * 100) / 100;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if ("visible" in n && (!compact || !n.visible)) s.visible = n.visible;
|
|
156
|
+
if ("opacity" in n && (!compact || n.opacity !== 1)) s.opacity = n.opacity;
|
|
157
|
+
if ("fills" in n && Array.isArray(n.fills) && (!compact || n.fills.length)) {
|
|
158
|
+
s.fills = compact ? n.fills.map(paintBrief) : n.fills;
|
|
159
|
+
}
|
|
49
160
|
if ("strokes" in n && n.strokes.length) {
|
|
50
|
-
s.strokes = n.strokes;
|
|
51
|
-
s.strokeWeight = val(n.strokeWeight);
|
|
161
|
+
s.strokes = compact ? n.strokes.map(paintBrief) : n.strokes;
|
|
162
|
+
if (!compact || val(n.strokeWeight) !== 1) s.strokeWeight = val(n.strokeWeight);
|
|
163
|
+
}
|
|
164
|
+
if ("effects" in n && n.effects.length) {
|
|
165
|
+
s.effects = compact ? n.effects.map((e) => e.type) : n.effects;
|
|
52
166
|
}
|
|
53
|
-
if ("effects" in n && n.effects.length) s.effects = n.effects;
|
|
54
167
|
if ("cornerRadius" in n && n.cornerRadius !== 0) s.cornerRadius = val(n.cornerRadius);
|
|
55
168
|
if (n.type === "TEXT") {
|
|
56
169
|
s.fontSize = val(n.fontSize);
|
|
@@ -66,13 +179,109 @@ function serialize(n, depth) {
|
|
|
66
179
|
s.primaryAxisAlignItems = n.primaryAxisAlignItems;
|
|
67
180
|
s.counterAxisAlignItems = n.counterAxisAlignItems;
|
|
68
181
|
}
|
|
182
|
+
// Sizes auto layout computes (fill, hug) and layers pinned outside the flow,
|
|
183
|
+
// so diff_design reports only what the designer set. FIXED is the default, left out.
|
|
184
|
+
try {
|
|
185
|
+
if (n.layoutSizingHorizontal && n.layoutSizingHorizontal !== "FIXED") s.layoutSizingHorizontal = n.layoutSizingHorizontal;
|
|
186
|
+
if (n.layoutSizingVertical && n.layoutSizingVertical !== "FIXED") s.layoutSizingVertical = n.layoutSizingVertical;
|
|
187
|
+
if (n.layoutPositioning === "ABSOLUTE") s.layoutPositioning = "ABSOLUTE";
|
|
188
|
+
} catch (e) {}
|
|
189
|
+
// Designer notes and variant values; each getter can throw on node types or
|
|
190
|
+
// plans that lack it, which must not sink the whole tree.
|
|
191
|
+
try {
|
|
192
|
+
if ("annotations" in n && n.annotations.length) {
|
|
193
|
+
s.annotations = n.annotations.map((a) => ({
|
|
194
|
+
label: a.labelMarkdown || a.label || "",
|
|
195
|
+
properties: (a.properties || []).map((p) => p.type),
|
|
196
|
+
}));
|
|
197
|
+
}
|
|
198
|
+
} catch (e) {}
|
|
199
|
+
try {
|
|
200
|
+
if ((n.type === "INSTANCE" || n.type === "COMPONENT") && n.variantProperties) {
|
|
201
|
+
s.variant = n.variantProperties;
|
|
202
|
+
}
|
|
203
|
+
} catch (e) {}
|
|
204
|
+
if (n.type === "COMPONENT_SET") {
|
|
205
|
+
const opts = variantOptions(n);
|
|
206
|
+
if (opts) s.variantOptions = opts;
|
|
207
|
+
}
|
|
208
|
+
// Dashed vs solid borders, and the tokens/styles behind the raw values: ids
|
|
209
|
+
// here, swapped for names by resolveRefs once the (sync) walk is done.
|
|
210
|
+
if ("dashPattern" in n && n.dashPattern.length) s.dashPattern = n.dashPattern;
|
|
211
|
+
try {
|
|
212
|
+
if (n.boundVariables && Object.keys(n.boundVariables).length) s.boundVariables = Object.assign({}, n.boundVariables); // a copy: resolveRefs rewrites it
|
|
213
|
+
} catch (e) {}
|
|
214
|
+
for (const k of STYLE_KEYS) {
|
|
215
|
+
if (k in n && typeof n[k] === "string" && n[k]) s[k] = n[k];
|
|
216
|
+
}
|
|
217
|
+
// Text mixing fonts, sizes or colors (one bold word, a red asterisk) reads
|
|
218
|
+
// as "mixed" above; list the runs so nothing hides behind it.
|
|
219
|
+
if (n.type === "TEXT" && [n.fontName, n.fontSize, n.fills, n.textDecoration].includes(figma.mixed)) {
|
|
220
|
+
try {
|
|
221
|
+
s.segments = n.getStyledTextSegments(["fontName", "fontSize", "fills", "textDecoration"]).map((g) => {
|
|
222
|
+
const seg = { text: g.characters, font: g.fontName.family + " " + g.fontName.style, size: g.fontSize, fill: g.fills.map(paintBrief).join(", ") };
|
|
223
|
+
if (g.textDecoration !== "NONE") seg.decoration = g.textDecoration;
|
|
224
|
+
return seg;
|
|
225
|
+
});
|
|
226
|
+
} catch (e) {}
|
|
227
|
+
}
|
|
69
228
|
if ("children" in n) {
|
|
70
|
-
|
|
71
|
-
if (
|
|
229
|
+
const kids = visibleOnly ? n.children.filter((c) => c.visible !== false) : n.children;
|
|
230
|
+
if (!compact || kids.length) {
|
|
231
|
+
s.childCount = kids.length;
|
|
232
|
+
if (depth > 0) s.children = kids.map((c) => serialize(c, depth - 1, compact, visibleOnly));
|
|
233
|
+
}
|
|
72
234
|
}
|
|
73
235
|
return s;
|
|
74
236
|
}
|
|
75
237
|
|
|
238
|
+
const STYLE_KEYS = ["fillStyleId", "strokeStyleId", "textStyleId", "effectStyleId"];
|
|
239
|
+
|
|
240
|
+
// Replace variable and style ids in a serialized tree with their names
|
|
241
|
+
// ("color/primary/500", "Heading/H1"), so a reader can match them to tokens.
|
|
242
|
+
async function resolveRefs(root) {
|
|
243
|
+
const cache = new Map();
|
|
244
|
+
const name = async (id, style) => {
|
|
245
|
+
if (!cache.has(id)) {
|
|
246
|
+
let x = null;
|
|
247
|
+
try {
|
|
248
|
+
x = style ? await figma.getStyleByIdAsync(id) : await figma.variables.getVariableByIdAsync(id);
|
|
249
|
+
} catch (e) {}
|
|
250
|
+
cache.set(id, x ? x.name : id);
|
|
251
|
+
}
|
|
252
|
+
return cache.get(id);
|
|
253
|
+
};
|
|
254
|
+
const alias = async (v) =>
|
|
255
|
+
Array.isArray(v) ? Promise.all(v.map(alias)) : v && v.type === "VARIABLE_ALIAS" ? name(v.id) : v;
|
|
256
|
+
const walk = async (s) => {
|
|
257
|
+
if (s.boundVariables) {
|
|
258
|
+
for (const k of Object.keys(s.boundVariables)) s.boundVariables[k] = await alias(s.boundVariables[k]);
|
|
259
|
+
}
|
|
260
|
+
for (const k of STYLE_KEYS) {
|
|
261
|
+
if (s[k]) {
|
|
262
|
+
s[k.slice(0, -2)] = await name(s[k], true); // fillStyleId -> fillStyle
|
|
263
|
+
delete s[k];
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
if (s.children) for (const c of s.children) await walk(c);
|
|
267
|
+
};
|
|
268
|
+
await walk(root);
|
|
269
|
+
return root;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// {property: [values]} for a component set's variant properties, or null.
|
|
273
|
+
function variantOptions(set) {
|
|
274
|
+
try {
|
|
275
|
+
const out = {};
|
|
276
|
+
for (const [k, d] of Object.entries(set.componentPropertyDefinitions)) {
|
|
277
|
+
if (d.type === "VARIANT") out[k.replace(/#.*$/, "")] = d.variantOptions || [];
|
|
278
|
+
}
|
|
279
|
+
return Object.keys(out).length ? out : null;
|
|
280
|
+
} catch (e) {
|
|
281
|
+
return null;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
76
285
|
async function parentOf(params) {
|
|
77
286
|
if (params.parent_id) {
|
|
78
287
|
const p = await node(params.parent_id);
|
|
@@ -139,13 +348,221 @@ function buildEffects(list) {
|
|
|
139
348
|
}
|
|
140
349
|
|
|
141
350
|
function applyShapeParams(n, params) {
|
|
142
|
-
n.x = params.x;
|
|
143
|
-
n.y = params.y;
|
|
351
|
+
n.x = params.x || 0;
|
|
352
|
+
n.y = params.y || 0;
|
|
144
353
|
if (params.width > 0 && params.height > 0) n.resize(params.width, params.height);
|
|
145
354
|
if (params.name) n.name = params.name;
|
|
146
|
-
if (params.fill_color
|
|
355
|
+
if (params.fill_color && params.fill_color !== "none") {
|
|
356
|
+
n.fills = [{ type: "SOLID", color: hexToRGB(params.fill_color) }];
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// Optional extras find_nodes can attach per node, so callers can filter on
|
|
361
|
+
// style without a get_design_context round-trip per hit.
|
|
362
|
+
const FIELD_GETTERS = {
|
|
363
|
+
fills: (n) => ("fills" in n && Array.isArray(n.fills) ? n.fills.map(paintBrief) : undefined),
|
|
364
|
+
strokes: (n) => ("strokes" in n && Array.isArray(n.strokes) && n.strokes.length ? n.strokes.map(paintBrief) : undefined),
|
|
365
|
+
fontSize: (n) => (n.type === "TEXT" ? val(n.fontSize) : undefined),
|
|
366
|
+
fontName: (n) => (n.type === "TEXT" ? val(n.fontName) : undefined),
|
|
367
|
+
cornerRadius: (n) => ("cornerRadius" in n ? val(n.cornerRadius) : undefined),
|
|
368
|
+
effects: (n) => ("effects" in n && n.effects.length ? n.effects.map((e) => e.type) : undefined),
|
|
369
|
+
opacity: (n) => ("opacity" in n ? n.opacity : undefined),
|
|
370
|
+
characters: (n) => (n.type === "TEXT" ? n.characters : undefined),
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
// ---------- prototyping ----------
|
|
374
|
+
|
|
375
|
+
const TRIGGERS = ["ON_CLICK", "ON_HOVER", "ON_PRESS", "ON_DRAG"];
|
|
376
|
+
const NAVIGATIONS = ["NAVIGATE", "SWAP", "OVERLAY", "BACK", "CLOSE"];
|
|
377
|
+
// Directional transitions carry a direction; the rest only easing/duration.
|
|
378
|
+
const DIRECTIONAL_TRANSITIONS = ["MOVE_IN", "MOVE_OUT", "PUSH", "SLIDE_IN", "SLIDE_OUT"];
|
|
379
|
+
const SIMPLE_TRANSITIONS = ["DISSOLVE", "SMART_ANIMATE", "SCROLL_ANIMATE"];
|
|
380
|
+
|
|
381
|
+
function buildTransition(item) {
|
|
382
|
+
const type = (item.transition || "").toUpperCase();
|
|
383
|
+
if (!type || type === "NONE" || type === "INSTANT") return null;
|
|
384
|
+
const directional = DIRECTIONAL_TRANSITIONS.indexOf(type) !== -1;
|
|
385
|
+
if (!directional && SIMPLE_TRANSITIONS.indexOf(type) === -1) {
|
|
386
|
+
throw new Error(
|
|
387
|
+
"unsupported transition: " + type + " (use " +
|
|
388
|
+
SIMPLE_TRANSITIONS.concat(DIRECTIONAL_TRANSITIONS).join(", ") + ")",
|
|
389
|
+
);
|
|
390
|
+
}
|
|
391
|
+
const t = {
|
|
392
|
+
type,
|
|
393
|
+
easing: { type: (item.easing || "EASE_OUT").toUpperCase() },
|
|
394
|
+
duration: item.duration === undefined || item.duration === null ? 0.3 : item.duration,
|
|
395
|
+
};
|
|
396
|
+
if (directional) {
|
|
397
|
+
t.direction = (item.direction || "LEFT").toUpperCase();
|
|
398
|
+
t.matchLayers = false;
|
|
399
|
+
}
|
|
400
|
+
return t;
|
|
147
401
|
}
|
|
148
402
|
|
|
403
|
+
async function buildReaction(item) {
|
|
404
|
+
const trigger = (item.trigger || "ON_CLICK").toUpperCase();
|
|
405
|
+
if (TRIGGERS.indexOf(trigger) === -1) {
|
|
406
|
+
throw new Error("unsupported trigger: " + trigger + " (use " + TRIGGERS.join(", ") + ")");
|
|
407
|
+
}
|
|
408
|
+
const navigation = (item.navigation || "NAVIGATE").toUpperCase();
|
|
409
|
+
if (NAVIGATIONS.indexOf(navigation) === -1) {
|
|
410
|
+
throw new Error("unsupported navigation: " + navigation + " (use " + NAVIGATIONS.join(", ") + ")");
|
|
411
|
+
}
|
|
412
|
+
const needsDestination = navigation !== "BACK" && navigation !== "CLOSE";
|
|
413
|
+
if (needsDestination && !item.destination_id) {
|
|
414
|
+
throw new Error("destination_id is required for " + navigation + "; only BACK and CLOSE take none");
|
|
415
|
+
}
|
|
416
|
+
// BACK and CLOSE are action types of their own, not navigations of a NODE
|
|
417
|
+
// action; sending them as a navigation fails validation.
|
|
418
|
+
if (!needsDestination) {
|
|
419
|
+
return { trigger: { type: trigger }, actions: [{ type: navigation }] };
|
|
420
|
+
}
|
|
421
|
+
// Resolve the destination here so a stale id fails by name, not as an
|
|
422
|
+
// opaque setReactionsAsync rejection.
|
|
423
|
+
await node(item.destination_id);
|
|
424
|
+
return {
|
|
425
|
+
trigger: { type: trigger },
|
|
426
|
+
actions: [{
|
|
427
|
+
type: "NODE",
|
|
428
|
+
destinationId: item.destination_id,
|
|
429
|
+
navigation,
|
|
430
|
+
transition: buildTransition(item),
|
|
431
|
+
preserveScrollPosition: false,
|
|
432
|
+
}],
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// The page owning a node; flowStartingPoints lives on the page, which is not
|
|
437
|
+
// necessarily the open one.
|
|
438
|
+
function pageOf(n) {
|
|
439
|
+
while (n && n.type !== "PAGE") n = n.parent;
|
|
440
|
+
if (!n) throw new Error("node is not on a page");
|
|
441
|
+
return n;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
// Right of everything already on the page, top-aligned with it.
|
|
446
|
+
function placeInFreeSpace(n, page) {
|
|
447
|
+
const others = page.children.filter((c) => c !== n && "width" in c);
|
|
448
|
+
if (!others.length) return;
|
|
449
|
+
n.x = Math.max.apply(null, others.map((c) => c.x + c.width)) + 100;
|
|
450
|
+
n.y = Math.min.apply(null, others.map((c) => c.y));
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// ---------- design audit ----------
|
|
454
|
+
|
|
455
|
+
const EPS = 1; // sub-pixel noise from auto layout, rotation and vector bounds: never visible
|
|
456
|
+
|
|
457
|
+
function intersect(a, b) {
|
|
458
|
+
const x = Math.max(a.x, b.x), y = Math.max(a.y, b.y);
|
|
459
|
+
const r = Math.min(a.x + a.width, b.x + b.width), bt = Math.min(a.y + a.height, b.y + b.height);
|
|
460
|
+
return { x, y, width: Math.max(0, r - x), height: Math.max(0, bt - y) };
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// How far box a sticks out of box b, per side; null when it does not.
|
|
464
|
+
function spill(a, b) {
|
|
465
|
+
const o = {
|
|
466
|
+
left: b.x - a.x, top: b.y - a.y,
|
|
467
|
+
right: a.x + a.width - (b.x + b.width), bottom: a.y + a.height - (b.y + b.height),
|
|
468
|
+
};
|
|
469
|
+
const out = {};
|
|
470
|
+
for (const k in o) if (o[k] > EPS) out[k] = Math.round(o[k] * 10) / 10;
|
|
471
|
+
return Object.keys(out).length ? out : null;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// Topmost visible paint: an {r,g,b} color when it is an opaque solid, "unknown"
|
|
475
|
+
// for images, gradients and translucent fills (no single color to measure
|
|
476
|
+
// against), null when the node paints nothing.
|
|
477
|
+
function topFill(n) {
|
|
478
|
+
if (!("fills" in n) || !Array.isArray(n.fills)) return null;
|
|
479
|
+
for (let i = n.fills.length - 1; i >= 0; i--) {
|
|
480
|
+
const p = n.fills[i];
|
|
481
|
+
if (p.visible === false) continue;
|
|
482
|
+
if (p.type !== "SOLID" || (p.opacity !== undefined && p.opacity < 1) || ("opacity" in n && n.opacity < 1)) return "unknown";
|
|
483
|
+
return p.color;
|
|
484
|
+
}
|
|
485
|
+
return null;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// What a text layer is drawn on: the nearest thing behind it that paints,
|
|
489
|
+
// either a sibling lower in the stack that covers it (the hand-drawn
|
|
490
|
+
// "rectangle as background") or an ancestor's own fill.
|
|
491
|
+
function backgroundOf(t) {
|
|
492
|
+
const box = t.absoluteBoundingBox;
|
|
493
|
+
for (let n = t; n.parent && n.parent.type !== "DOCUMENT"; n = n.parent) {
|
|
494
|
+
const sibs = n.parent.children || [];
|
|
495
|
+
for (let i = sibs.indexOf(n) - 1; i >= 0; i--) {
|
|
496
|
+
const s = sibs[i];
|
|
497
|
+
if (s.visible === false || !s.absoluteBoundingBox || spill(box, s.absoluteBoundingBox)) continue;
|
|
498
|
+
const f = topFill(s);
|
|
499
|
+
if (f) return f;
|
|
500
|
+
}
|
|
501
|
+
const f = n.parent.type === "PAGE" ? null : topFill(n.parent);
|
|
502
|
+
if (f) return f;
|
|
503
|
+
}
|
|
504
|
+
return "unknown";
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
// WCAG 2.x relative luminance and contrast ratio.
|
|
508
|
+
function luminance(c) {
|
|
509
|
+
const f = (v) => (v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4));
|
|
510
|
+
return 0.2126 * f(c.r) + 0.7152 * f(c.g) + 0.0722 * f(c.b);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function contrastRatio(a, b) {
|
|
514
|
+
const la = luminance(a), lb = luminance(b);
|
|
515
|
+
return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
// WCAG exempts inactive controls from contrast: text inside an instance whose
|
|
519
|
+
// variant says Disabled (State=Disabled, Disabled=true, ...) is not measured.
|
|
520
|
+
function inDisabledControl(n) {
|
|
521
|
+
for (let p = n.parent; p && p.type !== "PAGE"; p = p.parent) {
|
|
522
|
+
if (p.type !== "INSTANCE") continue;
|
|
523
|
+
let v = null;
|
|
524
|
+
try {
|
|
525
|
+
v = p.variantProperties;
|
|
526
|
+
} catch (e) {}
|
|
527
|
+
for (const k in v || {}) {
|
|
528
|
+
if (/^(disabled?|inactive)$/i.test(v[k]) || (/disabled/i.test(k) && /^(true|yes|on)$/i.test(v[k]))) return true;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
return false;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// Layers a finger is expected to hit: anything wired in the prototype, or
|
|
535
|
+
// named like a control.
|
|
536
|
+
const CONTROL_NAME = /\b(button|btn|link|tab|chip|checkbox|radio|switch|toggle|icon[-_ ]?button)\b/i;
|
|
537
|
+
|
|
538
|
+
function isControl(n) {
|
|
539
|
+
if ("reactions" in n && n.reactions && n.reactions.length) return true;
|
|
540
|
+
return (n.type === "INSTANCE" || n.type === "FRAME" || n.type === "COMPONENT") && CONTROL_NAME.test(n.name);
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// "$2" in a batch op's params stands for the id of the node op 2 produced,
|
|
544
|
+
// so a frame and its children can be created in one call.
|
|
545
|
+
function resolveBatchRefs(v, results) {
|
|
546
|
+
if (Array.isArray(v)) return v.map((x) => resolveBatchRefs(x, results));
|
|
547
|
+
if (v && typeof v === "object") {
|
|
548
|
+
const out = {};
|
|
549
|
+
for (const k in v) out[k] = resolveBatchRefs(v[k], results);
|
|
550
|
+
return out;
|
|
551
|
+
}
|
|
552
|
+
const m = typeof v === "string" ? /^\$(\d+)$/.exec(v) : null;
|
|
553
|
+
if (!m) return v;
|
|
554
|
+
const r = results[+m[1]];
|
|
555
|
+
if (!r) throw new Error(v + " refers to an op that has not run yet; refs only point backwards");
|
|
556
|
+
const res = r.result || {};
|
|
557
|
+
const id = res.id || (res.ids && res.ids[0]) || (res.nodes && res.nodes[0] && res.nodes[0].id);
|
|
558
|
+
if (!id) throw new Error(v + " has no node id: op " + m[1] + (r.error ? " failed" : " did not return a node"));
|
|
559
|
+
return id;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
// These carry megabytes of base64 or need the server's filesystem/network, so
|
|
563
|
+
// they only work as their own tool call.
|
|
564
|
+
const NOT_BATCHABLE = ["batch", "download_assets", "import_image", "get_screenshot"];
|
|
565
|
+
|
|
149
566
|
// ---------- command handlers (names match MCP tool names) ----------
|
|
150
567
|
|
|
151
568
|
const handlers = {
|
|
@@ -157,22 +574,247 @@ const handlers = {
|
|
|
157
574
|
};
|
|
158
575
|
},
|
|
159
576
|
|
|
577
|
+
async list_pages() {
|
|
578
|
+
return {
|
|
579
|
+
currentPage: figma.currentPage.name,
|
|
580
|
+
pages: figma.root.children.map((p) => ({
|
|
581
|
+
id: p.id,
|
|
582
|
+
name: p.name,
|
|
583
|
+
current: p.id === figma.currentPage.id,
|
|
584
|
+
})),
|
|
585
|
+
};
|
|
586
|
+
},
|
|
587
|
+
|
|
588
|
+
async set_current_page(params) {
|
|
589
|
+
const p = await resolvePage(params.page);
|
|
590
|
+
await figma.setCurrentPageAsync(p);
|
|
591
|
+
return { id: p.id, name: p.name, childCount: p.children.length };
|
|
592
|
+
},
|
|
593
|
+
|
|
160
594
|
async get_selection() {
|
|
161
|
-
return figma.currentPage.selection.map(
|
|
595
|
+
return figma.currentPage.selection.map((n) => {
|
|
596
|
+
const s = summarize(n);
|
|
597
|
+
const link = nodeLink(n.id);
|
|
598
|
+
if (link) s.link = link;
|
|
599
|
+
return s;
|
|
600
|
+
});
|
|
162
601
|
},
|
|
163
602
|
|
|
164
603
|
async get_design_context(params) {
|
|
165
604
|
const depth = params.depth === undefined ? 2 : params.depth;
|
|
166
|
-
return serialize(await node(params.node_id), depth);
|
|
605
|
+
return resolveRefs(serialize(await node(params.node_id), depth, !!params.compact, !!params.visible_only));
|
|
606
|
+
},
|
|
607
|
+
|
|
608
|
+
// Every component used under node_id, grouped by component (set), with all
|
|
609
|
+
// the states its set defines and the state each instance is in, so testers
|
|
610
|
+
// can write a case per state. Library components resolve too when Figma
|
|
611
|
+
// has their set loaded.
|
|
612
|
+
async get_component_states(params) {
|
|
613
|
+
const root = await node(params.node_id);
|
|
614
|
+
const instances = "findAllWithCriteria" in root ? root.findAllWithCriteria({ types: ["INSTANCE"] }) : [];
|
|
615
|
+
if (root.type === "INSTANCE") instances.unshift(root);
|
|
616
|
+
const groups = new Map();
|
|
617
|
+
for (const inst of instances) {
|
|
618
|
+
if (!inst.visible) continue;
|
|
619
|
+
const main = await inst.getMainComponentAsync();
|
|
620
|
+
if (!main) continue;
|
|
621
|
+
const set = main.parent && main.parent.type === "COMPONENT_SET" ? main.parent : null;
|
|
622
|
+
const owner = set || main;
|
|
623
|
+
let g = groups.get(owner.id);
|
|
624
|
+
if (!g) {
|
|
625
|
+
g = { component: owner.name, id: owner.id, library: !!main.remote, count: 0, used: [] };
|
|
626
|
+
if (set) {
|
|
627
|
+
const opts = variantOptions(set);
|
|
628
|
+
if (opts) g.states = opts;
|
|
629
|
+
else g.statesError = "variant list not readable";
|
|
630
|
+
}
|
|
631
|
+
groups.set(owner.id, g);
|
|
632
|
+
}
|
|
633
|
+
g.count++;
|
|
634
|
+
let state = null;
|
|
635
|
+
try {
|
|
636
|
+
state = inst.variantProperties;
|
|
637
|
+
} catch (e) {}
|
|
638
|
+
if (state) {
|
|
639
|
+
g.usedStates = g.usedStates || {};
|
|
640
|
+
for (const [k, v] of Object.entries(state)) {
|
|
641
|
+
const vals = (g.usedStates[k] = g.usedStates[k] || []);
|
|
642
|
+
if (!vals.includes(v)) vals.push(v);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
if (g.used.length < 10) {
|
|
646
|
+
const u = { id: inst.id, name: inst.name };
|
|
647
|
+
if (state) u.state = state;
|
|
648
|
+
g.used.push(u);
|
|
649
|
+
}
|
|
650
|
+
// Hand edits on top of the component (a "Disabled" button recolored by
|
|
651
|
+
// hand) are what testers miss; list which layer and which fields.
|
|
652
|
+
let ovs = [];
|
|
653
|
+
try {
|
|
654
|
+
ovs = inst.overrides || [];
|
|
655
|
+
} catch (e) {}
|
|
656
|
+
if (ovs.length) {
|
|
657
|
+
g.overridden = (g.overridden || 0) + 1;
|
|
658
|
+
g.overrides = g.overrides || [];
|
|
659
|
+
if (g.overrides.length < 10) {
|
|
660
|
+
const layers = [];
|
|
661
|
+
for (const o of ovs) {
|
|
662
|
+
const n = o.id === inst.id ? inst : await figma.getNodeByIdAsync(o.id);
|
|
663
|
+
layers.push({ layer: n ? n.name : o.id, fields: o.overriddenFields });
|
|
664
|
+
}
|
|
665
|
+
g.overrides.push({ id: inst.id, name: inst.name, layers });
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
return [...groups.values()].sort((a, b) => b.count - a.count);
|
|
167
670
|
},
|
|
168
671
|
|
|
169
672
|
async create_frame(params) {
|
|
170
673
|
const f = figma.createFrame();
|
|
674
|
+
const parent = await parentOf(params);
|
|
675
|
+
const topLevel = parent.type === "PAGE" || parent.type === "SECTION";
|
|
676
|
+
// A frame inside another is almost always a layout wrapper, and Figma's
|
|
677
|
+
// white default turns every wrapper into a white slab over the design.
|
|
678
|
+
// Top-level frames are screens and keep it.
|
|
679
|
+
if (params.fill_color === "none" || (!params.fill_color && !topLevel)) f.fills = [];
|
|
171
680
|
applyShapeParams(f, params);
|
|
172
|
-
|
|
681
|
+
parent.appendChild(f);
|
|
682
|
+
// A screen created without a position goes beside the existing work
|
|
683
|
+
// instead of on top of it at 0,0.
|
|
684
|
+
if (parent.type === "PAGE" && params.x == null && params.y == null) placeInFreeSpace(f, parent);
|
|
173
685
|
return summarize(f);
|
|
174
686
|
},
|
|
175
687
|
|
|
688
|
+
// Findings only: what a screenshot shows but a model reading it tends to
|
|
689
|
+
// miss. Reads the rendered geometry, never changes the document.
|
|
690
|
+
async audit_design(params) {
|
|
691
|
+
const root = await node(params.node_id);
|
|
692
|
+
if (!root.absoluteBoundingBox) throw new Error("node " + root.id + " is " + root.type + " and has no box to audit; pass a frame, section or component");
|
|
693
|
+
const want = params.checks && params.checks.length ? params.checks : ["layout", "contrast"];
|
|
694
|
+
for (const c of want) {
|
|
695
|
+
if (["layout", "contrast"].indexOf(c) === -1) throw new Error("unknown check: " + c + " (use layout, contrast)");
|
|
696
|
+
}
|
|
697
|
+
const layout = want.indexOf("layout") !== -1, contrast = want.indexOf("contrast") !== -1;
|
|
698
|
+
const minTouch = params.min_touch > 0 ? params.min_touch : 0;
|
|
699
|
+
const max = params.max_results || 100;
|
|
700
|
+
const issues = [], summary = {};
|
|
701
|
+
let checked = 0, contrastUnknown = 0, disabledSkipped = 0;
|
|
702
|
+
const report = (n, issue, detail) => {
|
|
703
|
+
summary[issue] = (summary[issue] || 0) + 1;
|
|
704
|
+
if (issues.length < max) issues.push(Object.assign({ id: n.id, name: n.name, issue }, detail));
|
|
705
|
+
};
|
|
706
|
+
let insideInstances = 0;
|
|
707
|
+
// clip: the visible window left by every clipping ancestor, or null.
|
|
708
|
+
// inInstance: geometry inside an instance belongs to its component and
|
|
709
|
+
// cannot be fixed on this screen (an icon's vector parts poking out of its
|
|
710
|
+
// own frame), so only contrast and touch size are checked there.
|
|
711
|
+
const walk = (n, clip, parentCut, inInstance) => {
|
|
712
|
+
if (n.visible === false) return;
|
|
713
|
+
const box = n.absoluteBoundingBox;
|
|
714
|
+
if (!box) return;
|
|
715
|
+
checked++;
|
|
716
|
+
let cut = parentCut;
|
|
717
|
+
if (inInstance) insideInstances++;
|
|
718
|
+
if (layout && n !== root && !inInstance) {
|
|
719
|
+
const seen = clip ? intersect(box, clip) : box;
|
|
720
|
+
if (clip && !parentCut && (seen.width <= EPS || seen.height <= EPS)) {
|
|
721
|
+
// Nothing of it shows, so nothing inside it is worth reporting.
|
|
722
|
+
report(n, "hidden_by_clip", { clippedBy: clip.id });
|
|
723
|
+
return;
|
|
724
|
+
}
|
|
725
|
+
const over = clip && !parentCut ? spill(box, clip) : null;
|
|
726
|
+
if (over) {
|
|
727
|
+
report(n, "clipped", { clippedBy: clip.id, cutOff: over });
|
|
728
|
+
cut = true;
|
|
729
|
+
} else if (n.parent && n.parent.absoluteBoundingBox && n.parent.type !== "GROUP" && !parentCut) {
|
|
730
|
+
const out = spill(box, n.parent.absoluteBoundingBox);
|
|
731
|
+
if (out) report(n, "overflows_parent", { parent: n.parent.id, by: out });
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
if (n.type === "TEXT") {
|
|
735
|
+
if (layout && !inInstance) {
|
|
736
|
+
// A fixed-size text box does not grow with its content: the glyphs
|
|
737
|
+
// either spill out of it or are cut with an ellipsis.
|
|
738
|
+
const rb = n.absoluteRenderBounds;
|
|
739
|
+
const fixed = n.textAutoResize === "NONE" || n.textAutoResize === "TRUNCATE";
|
|
740
|
+
const out = fixed && rb ? spill(rb, box) : null;
|
|
741
|
+
if (out && (out.right || out.bottom)) report(n, "text_overflows_box", { by: out });
|
|
742
|
+
const size = typeof n.fontSize === "number" ? n.fontSize : 14;
|
|
743
|
+
const lines = n.maxLines > 0 ? n.maxLines : Math.max(1, Math.floor(box.height / (size * 1.2)));
|
|
744
|
+
// shortcut: half the font size per character is a lower bound on
|
|
745
|
+
// width, so this only catches clear cases; measuring needs a clone,
|
|
746
|
+
// and an audit must not touch the document.
|
|
747
|
+
if ((n.textTruncation === "ENDING" || n.textAutoResize === "TRUNCATE") &&
|
|
748
|
+
(n.characters || "").length * size * 0.5 > box.width * lines) {
|
|
749
|
+
report(n, "text_truncated", { text: n.characters.slice(0, 60) });
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
if (contrast && (n.characters || "").trim()) {
|
|
753
|
+
const fg = topFill(n), bg = fg && fg !== "unknown" ? backgroundOf(n) : "unknown";
|
|
754
|
+
if (!fg || inDisabledControl(n)) {
|
|
755
|
+
// paints nothing, or a disabled control's label: exempt
|
|
756
|
+
if (fg) disabledSkipped++;
|
|
757
|
+
} else if (fg === "unknown" || bg === "unknown") {
|
|
758
|
+
contrastUnknown++;
|
|
759
|
+
} else {
|
|
760
|
+
const size = typeof n.fontSize === "number" ? n.fontSize : 0;
|
|
761
|
+
const bold = n.fontName && n.fontName !== figma.mixed && /bold|black|heavy/i.test(n.fontName.style || "");
|
|
762
|
+
// WCAG AA: 3:1 for large text (24px, or 18.66px bold), else 4.5:1.
|
|
763
|
+
const need = size >= 24 || (bold && size >= 18.66) ? 3 : 4.5;
|
|
764
|
+
const ratio = contrastRatio(fg, bg);
|
|
765
|
+
if (ratio < need) {
|
|
766
|
+
report(n, "low_contrast", { ratio: Math.round(ratio * 100) / 100, required: need, text: rgbToHex(fg), background: rgbToHex(bg) });
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
if (minTouch && isControl(n) && (box.width < minTouch - EPS || box.height < minTouch - EPS)) {
|
|
772
|
+
report(n, "small_touch_target", { width: Math.round(box.width), height: Math.round(box.height), required: minTouch });
|
|
773
|
+
}
|
|
774
|
+
if (!("children" in n) || n.type === "BOOLEAN_OPERATION") return;
|
|
775
|
+
let inner = clip;
|
|
776
|
+
if (n.clipsContent) {
|
|
777
|
+
inner = clip ? intersect(box, clip) : { x: box.x, y: box.y, width: box.width, height: box.height };
|
|
778
|
+
inner.id = n.id;
|
|
779
|
+
}
|
|
780
|
+
for (const c of n.children) walk(c, inner, cut, inInstance || n.type === "INSTANCE");
|
|
781
|
+
};
|
|
782
|
+
walk(root, null, false, root.type === "INSTANCE");
|
|
783
|
+
const total = Object.keys(summary).reduce((a, k) => a + summary[k], 0);
|
|
784
|
+
const out = { scope: root.name, checks: want.concat(minTouch ? ["touch"] : []), nodesChecked: checked, total, summary, issues };
|
|
785
|
+
if (total > issues.length) out.truncated = true;
|
|
786
|
+
if (layout && insideInstances) out.layoutNotChecked = insideInstances + " layers inside instances; audit their main component to check those";
|
|
787
|
+
if (disabledSkipped) out.contrastSkippedDisabled = disabledSkipped + " text layers in disabled controls (WCAG exempts them)";
|
|
788
|
+
if (contrastUnknown) out.contrastNotMeasured = contrastUnknown + " text layers sit on an image, gradient or translucent fill; check those by screenshot";
|
|
789
|
+
return out;
|
|
790
|
+
},
|
|
791
|
+
|
|
792
|
+
// Several commands in one round-trip. A failed op is reported in place and
|
|
793
|
+
// the rest still run: what already landed in the document stays there.
|
|
794
|
+
async batch(params) {
|
|
795
|
+
const ops = params.ops || [];
|
|
796
|
+
if (!ops.length) throw new Error("ops is required");
|
|
797
|
+
const results = [];
|
|
798
|
+
let failed = 0;
|
|
799
|
+
for (let i = 0; i < ops.length; i++) {
|
|
800
|
+
const op = ops[i] || {};
|
|
801
|
+
try {
|
|
802
|
+
if (NOT_BATCHABLE.indexOf(op.command) !== -1) throw new Error(op.command + " cannot run inside batch; call it as its own tool");
|
|
803
|
+
const h = handlers[op.command];
|
|
804
|
+
if (!h) throw new Error("unknown command: " + op.command + " (batch runs the same commands as the other tools, by tool name)");
|
|
805
|
+
const r = await h(resolveBatchRefs(op.params || {}, results));
|
|
806
|
+
results.push({ result: r === undefined ? null : r });
|
|
807
|
+
} catch (e) {
|
|
808
|
+
failed++;
|
|
809
|
+
results.push({ error: String((e && e.message) || e) });
|
|
810
|
+
if (params.stop_on_error) break;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
const out = { ok: failed === 0, ran: results.length, failed, results };
|
|
814
|
+
if (results.length < ops.length) out.skipped = ops.length - results.length;
|
|
815
|
+
return out;
|
|
816
|
+
},
|
|
817
|
+
|
|
176
818
|
async create_rectangle(params) {
|
|
177
819
|
const r = figma.createRectangle();
|
|
178
820
|
applyShapeParams(r, params);
|
|
@@ -246,32 +888,39 @@ const handlers = {
|
|
|
246
888
|
},
|
|
247
889
|
|
|
248
890
|
async set_characters(params) {
|
|
249
|
-
const
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
891
|
+
const nodes = await targets(params);
|
|
892
|
+
for (const t of nodes) {
|
|
893
|
+
if (t.type !== "TEXT") throw new Error("node " + t.id + " is " + t.type + ", not TEXT");
|
|
894
|
+
if (t.characters.length > 0) {
|
|
895
|
+
const fonts = t.getRangeAllFontNames(0, t.characters.length);
|
|
896
|
+
await Promise.all(fonts.map(figma.loadFontAsync));
|
|
897
|
+
} else {
|
|
898
|
+
await figma.loadFontAsync(t.fontName);
|
|
899
|
+
}
|
|
900
|
+
t.characters = params.text;
|
|
256
901
|
}
|
|
257
|
-
|
|
258
|
-
return summarize(t);
|
|
902
|
+
return done(params, nodes);
|
|
259
903
|
},
|
|
260
904
|
|
|
261
905
|
async set_fills(params) {
|
|
262
|
-
const
|
|
263
|
-
|
|
264
|
-
let paint;
|
|
265
|
-
if (
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
906
|
+
const nodes = await targets(params);
|
|
907
|
+
const clear = params.color === "none" || params.color === null;
|
|
908
|
+
let paint = null;
|
|
909
|
+
if (!clear) {
|
|
910
|
+
if (params.gradient) {
|
|
911
|
+
paint = buildGradient(params.gradient);
|
|
912
|
+
} else if (params.color) {
|
|
913
|
+
paint = { type: "SOLID", color: hexToRGB(params.color) };
|
|
914
|
+
} else {
|
|
915
|
+
throw new Error('set_fills needs color, gradient, or color: "none" to clear');
|
|
916
|
+
}
|
|
917
|
+
if (params.opacity !== undefined && params.opacity !== null) paint.opacity = params.opacity;
|
|
271
918
|
}
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
919
|
+
for (const n of nodes) {
|
|
920
|
+
if (!("fills" in n)) throw new Error("node " + n.id + " has no fills");
|
|
921
|
+
n.fills = clear ? [] : [paint];
|
|
922
|
+
}
|
|
923
|
+
return done(params, nodes);
|
|
275
924
|
},
|
|
276
925
|
|
|
277
926
|
async move_nodes(params) {
|
|
@@ -281,9 +930,9 @@ const handlers = {
|
|
|
281
930
|
if (!("x" in n)) throw new Error("node " + item.node_id + " cannot be moved");
|
|
282
931
|
n.x = item.x;
|
|
283
932
|
n.y = item.y;
|
|
284
|
-
out.push(
|
|
933
|
+
out.push(n);
|
|
285
934
|
}
|
|
286
|
-
return out;
|
|
935
|
+
return done(params, out);
|
|
287
936
|
},
|
|
288
937
|
|
|
289
938
|
async resize_nodes(params) {
|
|
@@ -292,16 +941,16 @@ const handlers = {
|
|
|
292
941
|
const n = await node(item.node_id);
|
|
293
942
|
if (!("resize" in n)) throw new Error("node " + item.node_id + " cannot be resized");
|
|
294
943
|
n.resize(item.width, item.height);
|
|
295
|
-
out.push(
|
|
944
|
+
out.push(n);
|
|
296
945
|
}
|
|
297
|
-
return out;
|
|
946
|
+
return done(params, out);
|
|
298
947
|
},
|
|
299
948
|
|
|
300
949
|
async remove_nodes(params) {
|
|
301
950
|
const deleted = [];
|
|
302
951
|
for (const id of params.node_ids) {
|
|
303
952
|
const n = await node(id);
|
|
304
|
-
deleted.push(
|
|
953
|
+
deleted.push({ id: n.id, name: n.name, type: n.type });
|
|
305
954
|
n.remove();
|
|
306
955
|
}
|
|
307
956
|
return { deleted };
|
|
@@ -311,7 +960,7 @@ const handlers = {
|
|
|
311
960
|
const n = await node(params.node_id);
|
|
312
961
|
if (!("layoutMode" in n)) throw new Error("node " + params.node_id + " does not support auto-layout");
|
|
313
962
|
n.layoutMode = params.layout_mode;
|
|
314
|
-
if (params.layout_mode === "NONE") return
|
|
963
|
+
if (params.layout_mode === "NONE") return done(params, n);
|
|
315
964
|
if (params.item_spacing !== undefined) n.itemSpacing = params.item_spacing;
|
|
316
965
|
if (params.padding !== undefined) {
|
|
317
966
|
n.paddingTop = n.paddingRight = n.paddingBottom = n.paddingLeft = params.padding;
|
|
@@ -324,46 +973,97 @@ const handlers = {
|
|
|
324
973
|
if (params.counter_axis_align) n.counterAxisAlignItems = params.counter_axis_align;
|
|
325
974
|
if (params.primary_axis_sizing) n.primaryAxisSizingMode = params.primary_axis_sizing;
|
|
326
975
|
if (params.counter_axis_sizing) n.counterAxisSizingMode = params.counter_axis_sizing;
|
|
327
|
-
return
|
|
976
|
+
return done(params, n);
|
|
328
977
|
},
|
|
329
978
|
|
|
330
979
|
async set_corner_radius(params) {
|
|
331
|
-
const
|
|
332
|
-
|
|
333
|
-
if (
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
if (
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
980
|
+
const nodes = await targets(params);
|
|
981
|
+
for (const n of nodes) {
|
|
982
|
+
if (params.radius !== undefined) {
|
|
983
|
+
if (!("cornerRadius" in n)) throw new Error("node " + n.id + " has no corner radius");
|
|
984
|
+
n.cornerRadius = params.radius;
|
|
985
|
+
}
|
|
986
|
+
if (!("topLeftRadius" in n)) {
|
|
987
|
+
if (params.radius === undefined) throw new Error("node " + n.id + " has no per-corner radius");
|
|
988
|
+
continue;
|
|
989
|
+
}
|
|
990
|
+
if (params.top_left !== undefined) n.topLeftRadius = params.top_left;
|
|
991
|
+
if (params.top_right !== undefined) n.topRightRadius = params.top_right;
|
|
992
|
+
if (params.bottom_right !== undefined) n.bottomRightRadius = params.bottom_right;
|
|
993
|
+
if (params.bottom_left !== undefined) n.bottomLeftRadius = params.bottom_left;
|
|
994
|
+
}
|
|
995
|
+
return done(params, nodes);
|
|
345
996
|
},
|
|
346
997
|
|
|
347
998
|
async set_strokes(params) {
|
|
348
|
-
const
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
999
|
+
const nodes = await targets(params);
|
|
1000
|
+
for (const n of nodes) {
|
|
1001
|
+
if (!("strokes" in n)) throw new Error("node " + n.id + " has no strokes");
|
|
1002
|
+
if (params.color && params.color !== "none") {
|
|
1003
|
+
const paint = { type: "SOLID", color: hexToRGB(params.color) };
|
|
1004
|
+
if (params.opacity !== undefined && params.opacity !== null) paint.opacity = params.opacity;
|
|
1005
|
+
n.strokes = [paint];
|
|
1006
|
+
} else {
|
|
1007
|
+
n.strokes = [];
|
|
1008
|
+
}
|
|
1009
|
+
if (params.weight !== undefined && "strokeWeight" in n) n.strokeWeight = params.weight;
|
|
1010
|
+
if (params.align && "strokeAlign" in n) n.strokeAlign = params.align;
|
|
356
1011
|
}
|
|
357
|
-
|
|
358
|
-
if (params.align && "strokeAlign" in n) n.strokeAlign = params.align;
|
|
359
|
-
return summarize(n);
|
|
1012
|
+
return done(params, nodes);
|
|
360
1013
|
},
|
|
361
1014
|
|
|
362
1015
|
async set_effects(params) {
|
|
363
|
-
const
|
|
364
|
-
|
|
365
|
-
n
|
|
366
|
-
|
|
1016
|
+
const nodes = await targets(params);
|
|
1017
|
+
const effects = buildEffects(params.effects);
|
|
1018
|
+
for (const n of nodes) {
|
|
1019
|
+
if (!("effects" in n)) throw new Error("node " + n.id + " has no effects");
|
|
1020
|
+
n.effects = effects;
|
|
1021
|
+
}
|
|
1022
|
+
return done(params, nodes);
|
|
1023
|
+
},
|
|
1024
|
+
|
|
1025
|
+
async rename_nodes(params) {
|
|
1026
|
+
const renamed = [];
|
|
1027
|
+
for (const item of params.items) {
|
|
1028
|
+
const n = await node(item.node_id);
|
|
1029
|
+
n.name = item.name;
|
|
1030
|
+
renamed.push(n);
|
|
1031
|
+
}
|
|
1032
|
+
return done(params, renamed);
|
|
1033
|
+
},
|
|
1034
|
+
|
|
1035
|
+
// Restyle text in place. create_text sets the font once; variants (Bold vs
|
|
1036
|
+
// Regular of the same label) need this.
|
|
1037
|
+
async set_text_properties(params) {
|
|
1038
|
+
const nodes = await targets(params);
|
|
1039
|
+
for (const n of nodes) {
|
|
1040
|
+
if (n.type !== "TEXT") throw new Error("node " + n.id + " is " + n.type + ", not TEXT");
|
|
1041
|
+
// Every font already in the node must be loaded before any edit, and
|
|
1042
|
+
// the new one before it can be applied.
|
|
1043
|
+
const current = n.characters.length
|
|
1044
|
+
? n.getRangeAllFontNames(0, n.characters.length)
|
|
1045
|
+
: [n.fontName];
|
|
1046
|
+
await Promise.all(current.filter((f) => f !== figma.mixed).map(figma.loadFontAsync));
|
|
1047
|
+
if (params.font_family || params.font_style) {
|
|
1048
|
+
const base = current[0] === figma.mixed ? { family: "Inter", style: "Regular" } : current[0];
|
|
1049
|
+
const font = {
|
|
1050
|
+
family: params.font_family || base.family,
|
|
1051
|
+
style: params.font_style || base.style,
|
|
1052
|
+
};
|
|
1053
|
+
await figma.loadFontAsync(font);
|
|
1054
|
+
n.fontName = font;
|
|
1055
|
+
}
|
|
1056
|
+
if (params.font_size) n.fontSize = params.font_size;
|
|
1057
|
+
if (params.line_height !== undefined && params.line_height !== null) {
|
|
1058
|
+
n.lineHeight = { value: params.line_height, unit: "PIXELS" };
|
|
1059
|
+
}
|
|
1060
|
+
if (params.letter_spacing !== undefined && params.letter_spacing !== null) {
|
|
1061
|
+
n.letterSpacing = { value: params.letter_spacing, unit: "PIXELS" };
|
|
1062
|
+
}
|
|
1063
|
+
if (params.text_align) n.textAlignHorizontal = params.text_align;
|
|
1064
|
+
if (params.fill_color) n.fills = [{ type: "SOLID", color: hexToRGB(params.fill_color) }];
|
|
1065
|
+
}
|
|
1066
|
+
return done(params, nodes);
|
|
367
1067
|
},
|
|
368
1068
|
|
|
369
1069
|
async download_assets(params) {
|
|
@@ -382,6 +1082,7 @@ const handlers = {
|
|
|
382
1082
|
let scale = item.scale || 1;
|
|
383
1083
|
scale = Math.max(0.5, Math.min(scale, 4));
|
|
384
1084
|
settings = { format, constraint: { type: "SCALE", value: scale } };
|
|
1085
|
+
if (item.exact) settings.useAbsoluteBounds = true;
|
|
385
1086
|
} else {
|
|
386
1087
|
throw new Error("unsupported format: " + format + " (use PNG, JPG or SVG)");
|
|
387
1088
|
}
|
|
@@ -408,22 +1109,57 @@ const handlers = {
|
|
|
408
1109
|
},
|
|
409
1110
|
|
|
410
1111
|
async find_nodes(params) {
|
|
411
|
-
|
|
1112
|
+
let scope;
|
|
1113
|
+
if (params.node_id) scope = await node(params.node_id);
|
|
1114
|
+
else if (params.page) scope = await resolvePage(params.page);
|
|
1115
|
+
else scope = figma.currentPage;
|
|
412
1116
|
if (!("findAll" in scope)) throw new Error("node " + scope.id + " has no children to search");
|
|
413
1117
|
const name = params.name ? params.name.toLowerCase() : null;
|
|
414
1118
|
const text = params.text ? params.text.toLowerCase() : null;
|
|
415
1119
|
const types = params.types && params.types.length ? params.types : null;
|
|
1120
|
+
// Style filters let callers target "every white card" directly instead of
|
|
1121
|
+
// guessing a node's role from its size.
|
|
1122
|
+
const fill = params.fill ? ("#" + params.fill.replace(/^#/, "")).toLowerCase() : null;
|
|
1123
|
+
const fontSize = params.font_size;
|
|
1124
|
+
const fontStyle = params.font_style ? params.font_style.toLowerCase() : null;
|
|
416
1125
|
const matches = scope.findAll((n) => {
|
|
417
1126
|
if (types && types.indexOf(n.type) === -1) return false;
|
|
418
1127
|
if (name && n.name.toLowerCase().indexOf(name) === -1) return false;
|
|
419
1128
|
if (text && (n.type !== "TEXT" || n.characters.toLowerCase().indexOf(text) === -1)) return false;
|
|
1129
|
+
if (fill) {
|
|
1130
|
+
const hex = solidFillHex(n);
|
|
1131
|
+
if (!hex || hex.toLowerCase() !== fill) return false;
|
|
1132
|
+
}
|
|
1133
|
+
if (fontSize !== undefined && fontSize !== null) {
|
|
1134
|
+
if (n.type !== "TEXT" || val(n.fontSize) !== fontSize) return false;
|
|
1135
|
+
}
|
|
1136
|
+
if (fontStyle) {
|
|
1137
|
+
if (n.type !== "TEXT") return false;
|
|
1138
|
+
const f = val(n.fontName);
|
|
1139
|
+
if (f === "mixed" || f.style.toLowerCase() !== fontStyle) return false;
|
|
1140
|
+
}
|
|
420
1141
|
return true;
|
|
421
1142
|
});
|
|
422
1143
|
const max = params.max_results || 50;
|
|
1144
|
+
const fields = params.fields && params.fields.length ? params.fields : null;
|
|
1145
|
+
// Name the scope: with no node_id or page this searches whatever page the
|
|
1146
|
+
// user happens to have open, which silently changes under a long session.
|
|
1147
|
+
const page = (function (n) {
|
|
1148
|
+
while (n && n.type !== "PAGE") n = n.parent;
|
|
1149
|
+
return n ? n.name : undefined;
|
|
1150
|
+
})(scope);
|
|
423
1151
|
return {
|
|
1152
|
+
scope: scope.type === "PAGE" ? "page " + scope.name : scope.name + " (page " + page + ")",
|
|
424
1153
|
total: matches.length,
|
|
425
1154
|
truncated: matches.length > max,
|
|
426
|
-
nodes: matches.slice(0, max).map(
|
|
1155
|
+
nodes: matches.slice(0, max).map((n) => {
|
|
1156
|
+
const s = summarize(n);
|
|
1157
|
+
for (const f of fields || []) {
|
|
1158
|
+
const v = FIELD_GETTERS[f] ? FIELD_GETTERS[f](n) : undefined;
|
|
1159
|
+
if (v !== undefined) s[f] = v;
|
|
1160
|
+
}
|
|
1161
|
+
return s;
|
|
1162
|
+
}),
|
|
427
1163
|
};
|
|
428
1164
|
},
|
|
429
1165
|
|
|
@@ -449,18 +1185,27 @@ const handlers = {
|
|
|
449
1185
|
async append_children(params) {
|
|
450
1186
|
const parent = await node(params.parent_id);
|
|
451
1187
|
if (!("appendChild" in parent)) throw new Error("node " + params.parent_id + " cannot have children");
|
|
452
|
-
const
|
|
1188
|
+
const moved = [];
|
|
1189
|
+
const warnings = [];
|
|
453
1190
|
let index = params.index;
|
|
454
1191
|
for (const id of params.node_ids) {
|
|
455
1192
|
const n = await node(id);
|
|
1193
|
+
// Figma silently pulls a variant out of its set and renames it
|
|
1194
|
+
// "<Set>/<Variant>" — easy to miss until the variants stop working.
|
|
1195
|
+
if (n.type === "COMPONENT" && n.parent && n.parent.type === "COMPONENT_SET") {
|
|
1196
|
+
warnings.push(
|
|
1197
|
+
"node " + n.id + " (" + n.name + ") left component set " + n.parent.name +
|
|
1198
|
+
"; Figma renames detached variants to <Set>/<Variant>",
|
|
1199
|
+
);
|
|
1200
|
+
}
|
|
456
1201
|
if (index === undefined || index === null) {
|
|
457
1202
|
parent.appendChild(n);
|
|
458
1203
|
} else {
|
|
459
1204
|
parent.insertChild(index++, n);
|
|
460
1205
|
}
|
|
461
|
-
|
|
1206
|
+
moved.push(n);
|
|
462
1207
|
}
|
|
463
|
-
return
|
|
1208
|
+
return done(params, moved, warnings.length ? { warnings } : null);
|
|
464
1209
|
},
|
|
465
1210
|
|
|
466
1211
|
async clone_node(params) {
|
|
@@ -530,6 +1275,57 @@ const handlers = {
|
|
|
530
1275
|
return summarize(inst);
|
|
531
1276
|
},
|
|
532
1277
|
|
|
1278
|
+
async combine_as_variants(params) {
|
|
1279
|
+
if (!params.node_ids || !params.node_ids.length) throw new Error("node_ids is required");
|
|
1280
|
+
const nodes = await Promise.all(params.node_ids.map((id) => node(id)));
|
|
1281
|
+
for (const n of nodes) {
|
|
1282
|
+
if (n.type !== "COMPONENT") throw new Error("node " + n.id + " is " + n.type + ", not a COMPONENT");
|
|
1283
|
+
}
|
|
1284
|
+
const parent = params.parent_id ? await node(params.parent_id) : nodes[0].parent;
|
|
1285
|
+
const set = figma.combineAsVariants(nodes, parent);
|
|
1286
|
+
if (params.name) set.name = params.name;
|
|
1287
|
+
arrangeVariants(set);
|
|
1288
|
+
return summarize(set);
|
|
1289
|
+
},
|
|
1290
|
+
|
|
1291
|
+
// Component properties live on the component (or set); binding the property
|
|
1292
|
+
// to a child layer is what makes it editable from the instance panel, so do
|
|
1293
|
+
// both in one call.
|
|
1294
|
+
async add_component_property(params) {
|
|
1295
|
+
const c = await node(params.component_id);
|
|
1296
|
+
if (c.type !== "COMPONENT" && c.type !== "COMPONENT_SET") {
|
|
1297
|
+
throw new Error("node " + c.id + " is " + c.type + ", not a COMPONENT or COMPONENT_SET");
|
|
1298
|
+
}
|
|
1299
|
+
const type = (params.type || "TEXT").toUpperCase();
|
|
1300
|
+
// Figma requires a default of the matching kind; pick the empty one
|
|
1301
|
+
// rather than failing a call that only omitted it.
|
|
1302
|
+
let def = params.default_value;
|
|
1303
|
+
if (def === undefined || def === null) def = type === "BOOLEAN" ? false : "";
|
|
1304
|
+
const t = params.bind_node_id ? await node(params.bind_node_id) : null;
|
|
1305
|
+
const key = c.addComponentProperty(params.name, type, def);
|
|
1306
|
+
if (t) {
|
|
1307
|
+
const field = type === "TEXT" ? "characters" : type === "BOOLEAN" ? "visible" : "mainComponent";
|
|
1308
|
+
const refs = {};
|
|
1309
|
+
for (const k in t.componentPropertyReferences || {}) refs[k] = t.componentPropertyReferences[k];
|
|
1310
|
+
refs[field] = key;
|
|
1311
|
+
t.componentPropertyReferences = refs;
|
|
1312
|
+
}
|
|
1313
|
+
return { key, name: params.name, type, boundTo: params.bind_node_id || null };
|
|
1314
|
+
},
|
|
1315
|
+
|
|
1316
|
+
async set_instance_properties(params) {
|
|
1317
|
+
const inst = await node(params.instance_id);
|
|
1318
|
+
if (inst.type !== "INSTANCE") throw new Error("node " + params.instance_id + " is " + inst.type + ", not an INSTANCE");
|
|
1319
|
+
const known = Object.keys(inst.componentProperties || {});
|
|
1320
|
+
for (const k in params.properties) {
|
|
1321
|
+
if (known.indexOf(k) === -1) {
|
|
1322
|
+
throw new Error("unknown property " + k + "; this instance accepts: " + (known.join(", ") || "(none)"));
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
inst.setProperties(params.properties);
|
|
1326
|
+
return { id: inst.id, properties: inst.componentProperties };
|
|
1327
|
+
},
|
|
1328
|
+
|
|
533
1329
|
async swap_component(params) {
|
|
534
1330
|
const inst = await node(params.instance_id);
|
|
535
1331
|
if (inst.type !== "INSTANCE") throw new Error("node " + params.instance_id + " is " + inst.type + ", not an INSTANCE");
|
|
@@ -590,27 +1386,29 @@ const handlers = {
|
|
|
590
1386
|
},
|
|
591
1387
|
|
|
592
1388
|
async apply_style(params) {
|
|
593
|
-
const
|
|
1389
|
+
const nodes = await targets(params);
|
|
594
1390
|
const style = await figma.getStyleByIdAsync(params.style_id);
|
|
595
1391
|
if (!style) throw new Error("style not found: " + params.style_id);
|
|
596
|
-
if (style.type === "
|
|
597
|
-
|
|
598
|
-
|
|
1392
|
+
if (style.type === "TEXT") await figma.loadFontAsync(style.fontName);
|
|
1393
|
+
for (const n of nodes) {
|
|
1394
|
+
if (style.type === "PAINT") {
|
|
1395
|
+
if (params.target === "stroke") {
|
|
1396
|
+
await n.setStrokeStyleIdAsync(style.id);
|
|
1397
|
+
} else {
|
|
1398
|
+
await n.setFillStyleIdAsync(style.id);
|
|
1399
|
+
}
|
|
1400
|
+
} else if (style.type === "TEXT") {
|
|
1401
|
+
if (n.type !== "TEXT") throw new Error("node " + n.id + " is " + n.type + ", not TEXT");
|
|
1402
|
+
await n.setTextStyleIdAsync(style.id);
|
|
1403
|
+
} else if (style.type === "EFFECT") {
|
|
1404
|
+
await n.setEffectStyleIdAsync(style.id);
|
|
1405
|
+
} else if (style.type === "GRID") {
|
|
1406
|
+
await n.setGridStyleIdAsync(style.id);
|
|
599
1407
|
} else {
|
|
600
|
-
|
|
601
|
-
}
|
|
602
|
-
} else if (style.type === "TEXT") {
|
|
603
|
-
if (n.type !== "TEXT") throw new Error("node " + params.node_id + " is " + n.type + ", not TEXT");
|
|
604
|
-
await figma.loadFontAsync(style.fontName);
|
|
605
|
-
await n.setTextStyleIdAsync(style.id);
|
|
606
|
-
} else if (style.type === "EFFECT") {
|
|
607
|
-
await n.setEffectStyleIdAsync(style.id);
|
|
608
|
-
} else if (style.type === "GRID") {
|
|
609
|
-
await n.setGridStyleIdAsync(style.id);
|
|
610
|
-
} else {
|
|
611
|
-
throw new Error("unsupported style type: " + style.type);
|
|
1408
|
+
throw new Error("unsupported style type: " + style.type);
|
|
1409
|
+
}
|
|
612
1410
|
}
|
|
613
|
-
return
|
|
1411
|
+
return done(params, nodes);
|
|
614
1412
|
},
|
|
615
1413
|
|
|
616
1414
|
// ---------- variables (design tokens) ----------
|
|
@@ -675,18 +1473,107 @@ const handlers = {
|
|
|
675
1473
|
},
|
|
676
1474
|
|
|
677
1475
|
async set_bound_variable(params) {
|
|
678
|
-
const
|
|
1476
|
+
const nodes = await targets(params);
|
|
679
1477
|
const v = await figma.variables.getVariableByIdAsync(params.variable_id);
|
|
680
1478
|
if (!v) throw new Error("variable not found: " + params.variable_id);
|
|
681
1479
|
const field = params.field;
|
|
682
|
-
|
|
683
|
-
if (
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
1480
|
+
for (const n of nodes) {
|
|
1481
|
+
if (field === "fills" || field === "strokes") {
|
|
1482
|
+
if (!(field in n)) throw new Error("node " + n.id + " has no " + field);
|
|
1483
|
+
const paints = n[field].length ? n[field] : [{ type: "SOLID", color: { r: 0, g: 0, b: 0 } }];
|
|
1484
|
+
n[field] = [figma.variables.setBoundVariableForPaint(paints[0], "color", v)].concat(paints.slice(1));
|
|
1485
|
+
} else {
|
|
1486
|
+
n.setBoundVariable(field, v);
|
|
1487
|
+
}
|
|
688
1488
|
}
|
|
689
|
-
return
|
|
1489
|
+
return done(params, nodes);
|
|
1490
|
+
},
|
|
1491
|
+
|
|
1492
|
+
// ---------- prototyping ----------
|
|
1493
|
+
|
|
1494
|
+
// setReactionsAsync replaces a node's reactions wholesale, so items for the
|
|
1495
|
+
// same node are grouped and written once instead of overwriting each other.
|
|
1496
|
+
async set_prototype_links(params) {
|
|
1497
|
+
const items = params.items || [];
|
|
1498
|
+
if (!items.length) throw new Error("items is required");
|
|
1499
|
+
const order = [];
|
|
1500
|
+
const groups = {};
|
|
1501
|
+
for (const item of items) {
|
|
1502
|
+
if (!item.node_id) throw new Error("node_id is required for every item");
|
|
1503
|
+
if (!groups[item.node_id]) {
|
|
1504
|
+
groups[item.node_id] = [];
|
|
1505
|
+
order.push(item.node_id);
|
|
1506
|
+
}
|
|
1507
|
+
groups[item.node_id].push(await buildReaction(item));
|
|
1508
|
+
}
|
|
1509
|
+
const out = [];
|
|
1510
|
+
for (const id of order) {
|
|
1511
|
+
const n = await node(id);
|
|
1512
|
+
if (!("setReactionsAsync" in n)) {
|
|
1513
|
+
throw new Error("node " + id + " is " + n.type + " and cannot carry prototype reactions");
|
|
1514
|
+
}
|
|
1515
|
+
await n.setReactionsAsync(groups[id]);
|
|
1516
|
+
out.push(n);
|
|
1517
|
+
}
|
|
1518
|
+
return done(params, out);
|
|
1519
|
+
},
|
|
1520
|
+
|
|
1521
|
+
async get_prototype_links(params) {
|
|
1522
|
+
const scope = params.node_id ? await node(params.node_id) : figma.currentPage;
|
|
1523
|
+
const withReactions = [];
|
|
1524
|
+
const has = (n) => "reactions" in n && n.reactions && n.reactions.length;
|
|
1525
|
+
if (has(scope)) withReactions.push(scope);
|
|
1526
|
+
if ("findAll" in scope) withReactions.push(...scope.findAll(has));
|
|
1527
|
+
const names = {};
|
|
1528
|
+
const nameOf = async (id) => {
|
|
1529
|
+
if (!(id in names)) {
|
|
1530
|
+
const d = await figma.getNodeByIdAsync(id);
|
|
1531
|
+
names[id] = d ? d.name : null;
|
|
1532
|
+
}
|
|
1533
|
+
return names[id];
|
|
1534
|
+
};
|
|
1535
|
+
const links = [];
|
|
1536
|
+
for (const n of withReactions) {
|
|
1537
|
+
for (const r of n.reactions) {
|
|
1538
|
+
for (const a of r.actions || []) {
|
|
1539
|
+
const link = { id: n.id, name: n.name, trigger: r.trigger ? r.trigger.type : null, action: a.type };
|
|
1540
|
+
if (a.navigation) link.navigation = a.navigation;
|
|
1541
|
+
if (a.url) link.url = a.url;
|
|
1542
|
+
if (a.destinationId) {
|
|
1543
|
+
link.destinationId = a.destinationId;
|
|
1544
|
+
const dn = await nameOf(a.destinationId);
|
|
1545
|
+
if (dn) link.destinationName = dn;
|
|
1546
|
+
}
|
|
1547
|
+
if (a.transition) link.transition = a.transition.type;
|
|
1548
|
+
links.push(link);
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
return {
|
|
1553
|
+
scope: scope.type === "PAGE" ? "page " + scope.name : scope.name,
|
|
1554
|
+
total: links.length,
|
|
1555
|
+
links,
|
|
1556
|
+
};
|
|
1557
|
+
},
|
|
1558
|
+
|
|
1559
|
+
// flowStartingPoints is a page-level array, so read-modify-write it.
|
|
1560
|
+
async set_flow_starting_point(params) {
|
|
1561
|
+
const n = await node(params.node_id);
|
|
1562
|
+
const page = pageOf(n);
|
|
1563
|
+
const kept = page.flowStartingPoints.filter((p) => p.nodeId !== n.id);
|
|
1564
|
+
const changed = params.remove
|
|
1565
|
+
? kept.length !== page.flowStartingPoints.length
|
|
1566
|
+
: true;
|
|
1567
|
+
page.flowStartingPoints = params.remove
|
|
1568
|
+
? kept
|
|
1569
|
+
: kept.concat([{ nodeId: n.id, name: params.name || n.name }]);
|
|
1570
|
+
return {
|
|
1571
|
+
ok: true,
|
|
1572
|
+
id: n.id,
|
|
1573
|
+
page: page.name,
|
|
1574
|
+
changed,
|
|
1575
|
+
flowStartingPoints: page.flowStartingPoints.map((p) => ({ nodeId: p.nodeId, name: p.name })),
|
|
1576
|
+
};
|
|
690
1577
|
},
|
|
691
1578
|
|
|
692
1579
|
async get_screenshot(params) {
|
|
@@ -699,31 +1586,121 @@ const handlers = {
|
|
|
699
1586
|
target = figma.currentPage;
|
|
700
1587
|
}
|
|
701
1588
|
if (!("exportAsync" in target)) throw new Error("node " + target.id + " cannot be exported");
|
|
702
|
-
|
|
703
|
-
|
|
1589
|
+
// With dynamic-page access a node can be reachable before its page is
|
|
1590
|
+
// loaded, and exporting then yields a blank image with no error.
|
|
1591
|
+
let owner = target;
|
|
1592
|
+
while (owner && owner.type !== "PAGE") owner = owner.parent;
|
|
1593
|
+
if (owner && typeof owner.loadAsync === "function") await owner.loadAsync();
|
|
1594
|
+
const requested = Math.max(0.5, Math.min(params.scale || 1, 4));
|
|
1595
|
+
let scale = requested;
|
|
704
1596
|
// Cap the output size: huge pages at high scale produce multi-MB base64
|
|
705
1597
|
// payloads that are slow to ship and waste the AI's context.
|
|
1598
|
+
const cap = params.max_dimension > 0 ? Math.min(params.max_dimension, 4096) : 2000;
|
|
706
1599
|
const maxDim = Math.max("width" in target ? target.width : 0, "height" in target ? target.height : 0);
|
|
707
|
-
|
|
1600
|
+
const clamped = maxDim * scale > cap;
|
|
1601
|
+
if (clamped) scale = cap / maxDim;
|
|
708
1602
|
const bytes = await target.exportAsync({ format: "PNG", constraint: { type: "SCALE", value: scale } });
|
|
709
1603
|
return {
|
|
710
1604
|
data: figma.base64Encode(bytes),
|
|
711
1605
|
width: ("width" in target ? target.width : 0) * scale,
|
|
712
1606
|
height: ("height" in target ? target.height : 0) * scale,
|
|
1607
|
+
scale,
|
|
1608
|
+
clamped,
|
|
1609
|
+
sourceHeight: "height" in target ? target.height : 0,
|
|
713
1610
|
};
|
|
714
1611
|
},
|
|
715
1612
|
};
|
|
716
1613
|
|
|
1614
|
+
// ---------- live selection panel ----------
|
|
1615
|
+
// Mirror the current selection into the plugin window so the user can grab a
|
|
1616
|
+
// frame's name and shareable link without going through the AI. Refreshes on
|
|
1617
|
+
// every selection change and resizes the window to fit the list.
|
|
1618
|
+
// selectionGen guards against stale posts: SVG export is async, so a newer
|
|
1619
|
+
// selection change may land while an older one is still exporting.
|
|
1620
|
+
let selectionGen = 0;
|
|
1621
|
+
|
|
1622
|
+
async function postSelection() {
|
|
1623
|
+
const gen = ++selectionGen;
|
|
1624
|
+
const sel = figma.currentPage.selection;
|
|
1625
|
+
const items = [];
|
|
1626
|
+
for (const n of sel) {
|
|
1627
|
+
const item = { id: n.id, name: n.name, type: n.type, link: nodeLink(n.id) };
|
|
1628
|
+
// Frames are copied as links; every other element (vectors, instances, …)
|
|
1629
|
+
// is copied as SVG, so pre-export it now to keep the UI copy synchronous
|
|
1630
|
+
// (clipboard writes must happen inside the click gesture). Skip huge
|
|
1631
|
+
// selections to avoid stalling on a big export the user won't copy.
|
|
1632
|
+
if (n.type !== "FRAME" && sel.length <= 50 && typeof n.exportAsync === "function") {
|
|
1633
|
+
try {
|
|
1634
|
+
item.svg = await n.exportAsync({ format: "SVG_STRING" });
|
|
1635
|
+
} catch (e) {
|
|
1636
|
+
item.svgError = String((e && e.message) || e);
|
|
1637
|
+
}
|
|
1638
|
+
if (gen !== selectionGen) return; // superseded by a newer selection
|
|
1639
|
+
}
|
|
1640
|
+
items.push(item);
|
|
1641
|
+
}
|
|
1642
|
+
figma.ui.postMessage({ selection: items });
|
|
1643
|
+
}
|
|
1644
|
+
figma.on("selectionchange", postSelection);
|
|
1645
|
+
postSelection();
|
|
1646
|
+
|
|
1647
|
+
// ---------- activity log clicks ----------
|
|
1648
|
+
|
|
1649
|
+
async function uiAction(msg) {
|
|
1650
|
+
if (msg.uiAction !== "select") throw new Error("unknown action: " + msg.uiAction);
|
|
1651
|
+
const n = await node(msg.nodeId);
|
|
1652
|
+
figma.currentPage.selection = [n];
|
|
1653
|
+
figma.viewport.scrollAndZoomIntoView([n]);
|
|
1654
|
+
return null;
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
// ---------- read-only switch ----------
|
|
1658
|
+
// Commands that leave the document as it is (selection and the open page are
|
|
1659
|
+
// view state). With the switch on, everything else is refused, so a tester can
|
|
1660
|
+
// let AI read a file it must not change. On at every start and never
|
|
1661
|
+
// remembered, so AI edits only while the user has this window unlocked.
|
|
1662
|
+
const READ_COMMANDS = /^(get_|list_|find_|audit_|download_assets$|set_selection$|set_current_page$)/;
|
|
1663
|
+
let readOnly = true;
|
|
1664
|
+
register();
|
|
1665
|
+
// Checkpoint buttons are for people who can edit this file. Dev Mode and
|
|
1666
|
+
// view-only windows (should the plugin ever run there) do not get them.
|
|
1667
|
+
figma.ui.postMessage({ canEdit: figma.editorType === "figma" && figma.mode !== "inspect" });
|
|
1668
|
+
|
|
717
1669
|
// ---------- dispatch ----------
|
|
718
1670
|
|
|
719
1671
|
figma.ui.onmessage = async (msg) => {
|
|
720
|
-
if (!msg
|
|
1672
|
+
if (!msg) return;
|
|
1673
|
+
// The window measures its content after every render.
|
|
1674
|
+
if (msg.resize) {
|
|
1675
|
+
figma.ui.resize(280, Math.max(104, Math.min(600, Math.round(msg.resize))));
|
|
1676
|
+
return;
|
|
1677
|
+
}
|
|
1678
|
+
if (msg.uiAction) {
|
|
1679
|
+
// A log row whose layer was deleted since: nothing to select.
|
|
1680
|
+
await uiAction(msg).catch(() => {});
|
|
1681
|
+
return;
|
|
1682
|
+
}
|
|
1683
|
+
if (msg.setReadOnly !== undefined) {
|
|
1684
|
+
readOnly = !!msg.setReadOnly;
|
|
1685
|
+
register();
|
|
1686
|
+
return;
|
|
1687
|
+
}
|
|
1688
|
+
if (!msg.id || !msg.command) return;
|
|
721
1689
|
const h = handlers[msg.command];
|
|
1690
|
+
const p = msg.params || {};
|
|
1691
|
+
const act = { command: msg.command, write: !READ_COMMANDS.test(msg.command), node: p.node_id || (p.node_ids && p.node_ids[0]) || null };
|
|
722
1692
|
try {
|
|
723
1693
|
if (!h) throw new Error("unknown command: " + msg.command);
|
|
724
|
-
|
|
1694
|
+
if (readOnly && act.write) {
|
|
1695
|
+
figma.notify("AI tried to edit this file (" + msg.command + ") and was blocked. Untick Read-only in Figma MCP Console to allow edits.", { timeout: 8000 });
|
|
1696
|
+
throw new Error(msg.command + " was blocked: read-only mode is on in this file's Figma MCP Console window. " +
|
|
1697
|
+
"Tell the user; they can turn it off there if the edit is intended.");
|
|
1698
|
+
}
|
|
1699
|
+
const result = await h(p);
|
|
725
1700
|
figma.ui.postMessage({ id: msg.id, result: result === undefined ? null : result });
|
|
726
1701
|
} catch (e) {
|
|
727
|
-
|
|
1702
|
+
act.error = String((e && e.message) || e);
|
|
1703
|
+
figma.ui.postMessage({ id: msg.id, error: act.error });
|
|
728
1704
|
}
|
|
1705
|
+
figma.ui.postMessage({ activity: act });
|
|
729
1706
|
};
|