figdriver 0.0.0-stage → 0.4.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,181 @@
1
+ export type Asset = { url: string; mime: string; size: [number, number] };
2
+
3
+ export type Box = [x: number, y: number, w: number, h: number];
4
+
5
+ /** Computed CSS, kept as the browser reports it. */
6
+ export type Style = {
7
+ display: string;
8
+ position: string;
9
+ zIndex: string;
10
+ flexDirection: string;
11
+ flexWrap: string;
12
+ justify: string;
13
+ align: string;
14
+ alignSelf: string;
15
+ flexGrow: string;
16
+ /** [row, column] */
17
+ gap: [number, number];
18
+ /** [top, right, bottom, left] */
19
+ pad: [number, number, number, number];
20
+ /** [top, right, bottom, left] */
21
+ margin: [number, number, number, number];
22
+ maxWidth: string;
23
+ gridCols: string;
24
+ gridRows: string;
25
+ textAlign: string;
26
+ bg: string;
27
+ bgImage: string;
28
+ bgSize: string;
29
+ bgPos: string;
30
+ /** [topLeft, topRight, bottomRight, bottomLeft], percentages resolved to px. */
31
+ radius: [number, number, number, number];
32
+ /** [top, right, bottom, left] */
33
+ border: [number, number, number, number];
34
+ borderColor: string;
35
+ borderStyle: string;
36
+ shadow: string;
37
+ opacity: number;
38
+ overflow: string;
39
+ transform: string;
40
+ backdrop: string;
41
+ objectFit: string;
42
+ /** CSS `filter`, absent when `none`. A `blur()` becomes a layer blur. */
43
+ filter?: string;
44
+ /** CSS `mix-blend-mode`, absent when `normal`. */
45
+ mixBlendMode?: string;
46
+ };
47
+
48
+ export type Run = {
49
+ text: string;
50
+ weight: number;
51
+ size: number;
52
+ lineHeight: number;
53
+ letterSpacing: number;
54
+ color: string;
55
+ upper: boolean;
56
+ underline: boolean;
57
+ italic: boolean;
58
+ /** The first family of `font-family`, unquoted. */
59
+ fontFamily?: string;
60
+ strike?: boolean;
61
+ /** The `href` of the link the run sits in. */
62
+ href?: string;
63
+ };
64
+
65
+ /** The `:root` token each color an element paints came from, keyed by the color as captured, for tokens that share a value. */
66
+ export type Vars = Record<string, string>;
67
+
68
+ /** A ::before or ::after box that paints something, resolved to a box in page space. */
69
+ export type Pseudo = { which: "before" | "after"; box: Box; style: Style; flow: boolean; vars?: Vars };
70
+
71
+ type Common = { tag: string; cls: string[]; box: Box; style: Style; label?: string; vars?: Vars };
72
+
73
+ /** One element of the captured page. Coordinates are CSS px in page space. */
74
+ export type El =
75
+ | (Common & { kind: "frame"; children: El[]; pseudos: Pseudo[]; bgImages: string[] })
76
+ | (Common & {
77
+ kind: "text";
78
+ runs: Run[];
79
+ /** Bounds of the glyph lines, narrower than `box` when a block stretches. */
80
+ content: Box;
81
+ })
82
+ | (Common & {
83
+ kind: "image";
84
+ /** The asset drawn, and for a `<video>` or moving `<canvas>` the frame it showed at capture. */
85
+ image: string;
86
+ /** The video asset of a `<video>`, or a clip of a moving `<canvas>`, which Figma plays where a file can hold video. */
87
+ video?: string;
88
+ })
89
+ | (Common & { kind: "svg"; svg: string });
90
+
91
+ export type FrameEl = Extract<El, { kind: "frame" }>;
92
+
93
+ export type TextEl = Extract<El, { kind: "text" }>;
94
+
95
+ export type SvgEl = Extract<El, { kind: "svg" }>;
96
+
97
+ export type ImageEl = Extract<El, { kind: "image" }>;
98
+
99
+ export type Snapshot = {
100
+ url: string;
101
+ viewport: [number, number];
102
+ tokens: Record<string, string>;
103
+ root: El;
104
+ assets: Record<string, Asset>;
105
+ embed?: string;
106
+ /** Token overrides by color mode, such as `{ Dark: { background: "#0b1b2b" } }`, from `[data-theme]` and `prefers-color-scheme: dark` rules. */
107
+ themes?: Record<string, Record<string, string>>;
108
+ };
109
+
110
+ export type Capture = {
111
+ snapshot: Snapshot;
112
+ bytes: Record<string, string>;
113
+ skipped: { url: string; reason: string }[];
114
+ notes?: string[];
115
+ /** Whether the page has `<video>` or `<canvas>` elements waiting for `designClips()`. */
116
+ hasClips?: boolean;
117
+ };
118
+
119
+ /** What `designClips()` records once motion is back on: assets and bytes by name, as a capture holds them. */
120
+ export type Clips = Pick<Capture, "bytes" | "skipped"> & { assets: Snapshot["assets"] };
121
+
122
+ /** `parent` is the parent in the normalized tree, so synthetic stacks can sit between an element and its DOM parent. */
123
+ export type Match = (el: El, parent?: El) => boolean;
124
+
125
+ export type ComponentRule = {
126
+ /** The component's name in Figma. A slash groups it, as in "Form/Input". */
127
+ name: string;
128
+ /** Every element this matches becomes an instance. The first one seen, per variant value, becomes the main. */
129
+ match: Match;
130
+ /** One variant property. Elements that give the same value share a variant. */
131
+ variant?: { property: string; value: (el: El) => string };
132
+ description?: string;
133
+ /**
134
+ * Placeholder text for the component's TEXT properties, such as `{ Label: "Button" }`, so instances keep their own labels. A
135
+ * property is named after its layer's BEM element (`card__title` gives "Title"), else Heading, Paragraph or Label, and " 2" for a repeat.
136
+ */
137
+ text?: Record<string, string>;
138
+ /** Optional children: each matching child gets a BOOLEAN component property of this name that toggles its visibility. */
139
+ booleans?: Record<string, Match>;
140
+ };
141
+
142
+ export type ImportSpec = {
143
+ /** Names the import and owns its output: a rerun replaces what an earlier run of the same name built. */
144
+ name: string;
145
+ snapshot: Snapshot;
146
+ /** Base64 bytes by asset name, from the design's assets.gen.ts. */
147
+ images: Record<string, string>;
148
+ /**
149
+ * Base64 video bytes by asset name, from the design's assets.gen.ts. Figma plays them only in a paid team's file, so elsewhere
150
+ * each video shows its still frame from `images`.
151
+ */
152
+ videos?: Record<string, string>;
153
+ /** The page's top-level parts, in order. Each becomes a component under "Section/", and the rebuilt page stacks their instances. */
154
+ sections: { name: string; match: Match }[];
155
+ /** Reusable parts. When two rules match one element, the first listed wins, and every rule here wins over `sections`. */
156
+ components: ComponentRule[];
157
+ /** Icon names keyed by a fragment of their normalized SVG markup. Icons that match none are named after their context. */
158
+ icons?: Record<string, string>;
159
+ /** Font family for every text node and style. Weights map to the family's own style names. Defaults to Inter. */
160
+ font?: string;
161
+ /** Each section becomes its own top-level frame, side by side, instead of one page that stacks them. */
162
+ screens?: boolean;
163
+ /** Put the rebuilt page in place of the Figma Make embed it was captured from, and hide the embed. Defaults to true for a Make capture. */
164
+ replace?: boolean;
165
+ /** Dimension variables by name. Paddings and gaps bind to the spacing variable of equal value, corners to the radius of equal value. */
166
+ spacing?: Record<string, number>;
167
+ radii?: Record<string, number>;
168
+ /** A column layout grid on each rebuilt page or screen. */
169
+ grid?: { count: number; gutter: number; margin: number };
170
+ /** Prototype links: clicking an element with this class navigates to the screen of this name. Needs `screens`. */
171
+ links?: Record<string, string>;
172
+ /**
173
+ * Renamed parts, old name to new, so a rerun moves what used the old part to the renamed one instead of refusing. Keys are part keys
174
+ * such as `component:Button/Style=Primary`, `variable:Color/accent` or `style:TEXT/Heading`, or bare names such as `Button/Style=Primary`.
175
+ */
176
+ renames?: Record<string, string>;
177
+ /** Dev Mode annotations on rebuilt layers, recording their source selector and the CSS Figma could only approximate or had to drop. */
178
+ annotations?: boolean;
179
+ /** In a Figma Slides file, each section becomes a slide. */
180
+ slides?: boolean;
181
+ };
@@ -0,0 +1,17 @@
1
+ import type { ActiveUserRef } from "./protocol";
2
+
3
+ /**
4
+ * Other active sessions in the file, excluding the current tab's own sessionId.
5
+ * Another tab under the same account is tagged so agents can tell a collaborator from the user's own window.
6
+ */
7
+ export function otherUsers(me: ActiveUserRef | null, active: readonly ActiveUserRef[] | null): string[] | null {
8
+ if (!active) return null;
9
+ const out: string[] = [];
10
+
11
+ for (const user of active) {
12
+ if (me && user.sessionId === me.sessionId) continue;
13
+ out.push(me && me.id !== null && user.id === me.id ? `${user.name} (another session)` : user.name);
14
+ }
15
+
16
+ return out;
17
+ }
@@ -0,0 +1,238 @@
1
+ import { textSpan, type TextTarget } from "../core/text";
2
+ import { propertyValues } from "./read";
3
+
4
+ // `fd` in `figdriver eval` scripts: the Plugin API edits that are easy to get subtly wrong, done the way figma-api.md says.
5
+
6
+ type NodeType = BaseNode["type"];
7
+
8
+ type NodeOf<T extends NodeType> = Extract<BaseNode, { type: T }>;
9
+
10
+ type SlotContent = SceneNode | SceneNode[] | void;
11
+
12
+ type PlaceOptions = { index?: number; fillX?: boolean; fillY?: boolean; props?: Record<string, string | boolean> };
13
+
14
+ type BindOptions = { field?: "fills" | "strokes"; index?: number; force?: boolean };
15
+
16
+ const describe = (n: BaseNode) => `"${n.name}" (${n.id})`;
17
+
18
+ async function nodeOf(ref: BaseNode | string): Promise<BaseNode> {
19
+ if (ref instanceof Object) return ref;
20
+ const n = await figma.getNodeByIdAsync(ref);
21
+
22
+ if (!n) throw new Error(`No node with id ${ref}.`);
23
+
24
+ return n;
25
+ }
26
+
27
+ async function nodeOfType<T extends NodeType>(ref: BaseNode | string, ...types: T[]): Promise<NodeOf<T>> {
28
+ const n = await nodeOf(ref);
29
+ const isType = (x: BaseNode): x is NodeOf<T> => types.some((t) => t === x.type);
30
+
31
+ if (!isType(n)) throw new Error(`${describe(n)} is a ${n.type}, not a ${types.join(" or ")}.`);
32
+
33
+ return n;
34
+ }
35
+
36
+ /** Every descendant of `root` (the current page by default) that `predicate` accepts, in document order. */
37
+ async function find(root: SceneNode | PageNode | string | null | undefined, predicate: (n: SceneNode) => boolean) {
38
+ const start = await nodeOf(root ?? figma.currentPage);
39
+
40
+ if (start.type === "DOCUMENT") throw new Error("Pass a page or a layer to search, not the document.");
41
+
42
+ if (start.type === "PAGE") await start.loadAsync();
43
+ const out: SceneNode[] = [];
44
+
45
+ const visit = (n: SceneNode | PageNode) => {
46
+ if (!("children" in n)) return;
47
+
48
+ for (const child of n.children) {
49
+ if (predicate(child)) out.push(child);
50
+ visit(child);
51
+ }
52
+ };
53
+
54
+ visit(start);
55
+
56
+ return out;
57
+ }
58
+
59
+ /** The instance's main component, read without the deprecated `mainComponent` getter. */
60
+ async function mainOf(ref: InstanceNode | string) {
61
+ return (await nodeOfType(ref, "INSTANCE")).getMainComponentAsync();
62
+ }
63
+
64
+ /**
65
+ * Replaces the text `target` names (all of it by default) and keeps every other styled span: the new text takes the style of the first
66
+ * character it replaces, or of the character before it when it only inserts.
67
+ */
68
+ async function replaceText(ref: TextNode | string, next: string, target?: TextTarget) {
69
+ const node = await nodeOfType(ref, "TEXT");
70
+ const length = node.characters.length;
71
+ const fonts = length ? node.getRangeAllFontNames(0, length) : node.fontName === figma.mixed ? [] : [node.fontName];
72
+ await Promise.all(fonts.map((font) => figma.loadFontAsync(font)));
73
+ const [start, end] = textSpan(node.characters, target);
74
+
75
+ if (!length) {
76
+ node.characters = next;
77
+
78
+ return node.characters;
79
+ }
80
+
81
+ if (next) node.insertCharacters(start, next, end > start || start === 0 ? "AFTER" : "BEFORE");
82
+
83
+ if (end > start) node.deleteCharacters(start + next.length, end + next.length);
84
+
85
+ return node.characters;
86
+ }
87
+
88
+ /** Sets instance properties and returns each property's value afterwards. */
89
+ async function setProps(ref: InstanceNode | string, props: Record<string, string | boolean | VariableAlias>) {
90
+ const instance = await nodeOfType(ref, "INSTANCE");
91
+ instance.setProperties(props);
92
+
93
+ return propertyValues(instance);
94
+ }
95
+
96
+ /**
97
+ * Fills the instance's slot named `name` (a SLOT property key such as `Content#1:2` also works) with what `build` returns or appends,
98
+ * after clearing it. A `null` build resets the slot to its component's content. setProperties cannot set SLOT properties.
99
+ */
100
+ async function setSlot(
101
+ ref: InstanceNode | string,
102
+ name: string,
103
+ build: ((slot: SlotNode) => SlotContent | Promise<SlotContent>) | null,
104
+ ) {
105
+ const instance = await nodeOfType(ref, "INSTANCE");
106
+ const slots = instance.findAllWithCriteria({ types: ["SLOT"] });
107
+ const slot = slots.find((s) => s.name === name || s.name === name.split("#")[0]);
108
+
109
+ if (!slot)
110
+ throw new Error(
111
+ `${describe(instance)} has no slot named "${name}". Its slots: ${slots.map((s) => `"${s.name}"`).join(", ") || "none"}.`,
112
+ );
113
+
114
+ if (build === null) {
115
+ slot.resetSlot();
116
+
117
+ return slot;
118
+ }
119
+
120
+ while (slot.children.length) slot.children[0].remove();
121
+ const made = await build(slot);
122
+
123
+ for (const n of made === undefined ? [] : Array.isArray(made) ? made : [made])
124
+ if (n.parent !== slot) slot.appendChild(n);
125
+
126
+ return slot;
127
+ }
128
+
129
+ /**
130
+ * Places an instance of the component (a set's default variant) in `parent`, at `index` or last, and only then sets FILL sizing, which
131
+ * throws outside an auto layout parent, and `props`.
132
+ */
133
+ async function placeInstance(
134
+ componentRef: ComponentNode | ComponentSetNode | string,
135
+ parentRef: BaseNode | string,
136
+ opts: PlaceOptions = {},
137
+ ) {
138
+ const found = await nodeOfType(componentRef, "COMPONENT", "COMPONENT_SET");
139
+ const component = found.type === "COMPONENT_SET" ? found.defaultVariant : found;
140
+ const parent = await nodeOf(parentRef);
141
+
142
+ if (parent.type === "DOCUMENT" || !("insertChild" in parent))
143
+ throw new Error(`${describe(parent)} is a ${parent.type}, which cannot hold layers.`);
144
+ const instance = component.createInstance();
145
+
146
+ if (opts.index === undefined) parent.appendChild(instance);
147
+ else parent.insertChild(opts.index, instance);
148
+
149
+ if (opts.fillX) instance.layoutSizingHorizontal = "FILL";
150
+
151
+ if (opts.fillY) instance.layoutSizingVertical = "FILL";
152
+
153
+ if (opts.props) instance.setProperties(opts.props);
154
+
155
+ return instance;
156
+ }
157
+
158
+ /** A node's fills or strokes, and how to replace them. */
159
+ type PaintField = { paints: readonly Paint[] | PluginAPI["mixed"]; set: (paints: Paint[]) => void };
160
+
161
+ function paintsOf(node: SceneNode, field: "fills" | "strokes"): PaintField {
162
+ if (field === "fills" && "fills" in node)
163
+ return {
164
+ paints: node.fills,
165
+ set: (p: Paint[]) => {
166
+ node.fills = p;
167
+ },
168
+ };
169
+
170
+ if (field === "strokes" && "strokes" in node)
171
+ return {
172
+ paints: node.strokes,
173
+ set: (p: Paint[]) => {
174
+ node.strokes = p;
175
+ },
176
+ };
177
+
178
+ throw new Error(`${describe(node)} has no ${field}.`);
179
+ }
180
+
181
+ /**
182
+ * Binds the paint at `index` (a new one at the end of the list) to a color variable, with the variable's resolved color as its base. Keeps
183
+ * the paint's opacity, visibility and blend mode, and refuses translucent or non-solid paints unless `force` is set.
184
+ */
185
+ async function bindColor(ref: SceneNode | string, variableRef: Variable | string, opts: BindOptions = {}) {
186
+ const { field = "fills", index = 0, force = false } = opts;
187
+ const node = await nodeOf(ref);
188
+
189
+ if (node.type === "DOCUMENT" || node.type === "PAGE") throw new Error(`${describe(node)} is a ${node.type}.`);
190
+ const { paints, set } = paintsOf(node, field);
191
+
192
+ if (paints === figma.mixed) throw new Error(`${describe(node)} has mixed ${field}. Bind each text range instead.`);
193
+
194
+ if (!Number.isInteger(index) || index < 0 || index > paints.length)
195
+ throw new Error(`${describe(node)} has ${paints.length} ${field}, so index ${index} is out of range.`);
196
+
197
+ const variable =
198
+ variableRef instanceof Object ? variableRef : await figma.variables.getVariableByIdAsync(variableRef);
199
+
200
+ if (!variable) throw new Error(`No variable with id ${String(variableRef)}.`);
201
+
202
+ if (variable.resolvedType !== "COLOR") throw new Error(`${variable.name} is a ${variable.resolvedType} variable.`);
203
+ const { value } = variable.resolveForConsumer(node);
204
+
205
+ if (!(value instanceof Object) || !("r" in value))
206
+ throw new Error(`${variable.name} does not resolve to a color for ${describe(node)}.`);
207
+ const color = { r: value.r, g: value.g, b: value.b };
208
+ const existing = paints[index];
209
+
210
+ if (existing && existing.type !== "SOLID" && !force)
211
+ throw new Error(`${field}[${index}] of ${describe(node)} is ${existing.type}. Pass force: true to replace it.`);
212
+
213
+ if (existing?.type === "SOLID" && (existing.opacity ?? 1) < 1 && !force)
214
+ throw new Error(
215
+ `${field}[${index}] of ${describe(node)} is translucent (opacity ${existing.opacity}). A bound color renders opaque inside instances, so keep translucent tints raw, or pass force: true.`,
216
+ );
217
+
218
+ const base: SolidPaint = existing?.type === "SOLID" ? { ...existing, color } : { type: "SOLID", color };
219
+ const next = [...paints];
220
+ next[index] = figma.variables.setBoundVariableForPaint(base, "color", variable);
221
+ set(next);
222
+
223
+ return { id: node.id, field, index, variable: variable.id };
224
+ }
225
+
226
+ export const fd = {
227
+ /** The page `eval` runs on: --page's, or the current one. */
228
+ get page() {
229
+ return figma.currentPage;
230
+ },
231
+ find,
232
+ mainOf,
233
+ replaceText,
234
+ setProps,
235
+ setSlot,
236
+ placeInstance,
237
+ bindColor,
238
+ };