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,387 @@
1
+ import type { Audit, HookKey, Imported, ImportSummary } from "../core/protocol";
2
+ import { blockers, cleanup, decide, drafted, renamer, transact, why, type Outcome, type Step } from "../core/rerun";
3
+ import { messageOf } from "../core/snapshot";
4
+ import { migrate, partsOf, usesOf } from "./migrate";
5
+ import { hasAncestor, ownedBy, ownedItems, outputOf, read, write } from "./owned";
6
+ import { auditOf, editedLayers, fingerprintOf, recordLayers } from "./review";
7
+
8
+ export type Hook = (key: HookKey, summary?: ImportSummary) => void | Promise<void>;
9
+
10
+ /** `renames` maps old part names to new ones, from the spec, so a rerun moves what used a renamed part. */
11
+ export type Options = { force: boolean; page?: string; hook?: Hook; renames?: Record<string, string> };
12
+
13
+ type Draw = (others: SceneNode[], kept?: Vector) => Promise<{ summary: ImportSummary; source?: SceneNode }>;
14
+
15
+ const NOTHING: ImportSummary = {
16
+ variables: 0,
17
+ textStyles: 0,
18
+ effectStyles: 0,
19
+ components: 0,
20
+ componentSets: 0,
21
+ instances: 0,
22
+ fallbacks: 0,
23
+ fallbackRules: [],
24
+ fallbackReasons: [],
25
+ unknownTextProperties: [],
26
+ dropped: [],
27
+ lost: [],
28
+ warnings: [],
29
+ };
30
+
31
+ const NO_AUDIT: Audit = {
32
+ frames: 0,
33
+ texts: 0,
34
+ instances: 0,
35
+ problems: {
36
+ framesWithoutAutoLayout: [],
37
+ textsWithoutStyle: [],
38
+ detachedInstances: [],
39
+ rawPaintsOnTokenColors: [],
40
+ negativeSpacing: [],
41
+ overlappingSiblings: [],
42
+ brokenLinks: [],
43
+ },
44
+ rawPaints: { translucentTokenColors: 0, offToken: 0, offTokenColors: [] },
45
+ };
46
+
47
+ /** An error's message without its closing period, to sit inside a sentence of ours. */
48
+ const clause = (message: string) => message.replace(/[.\s]+$/, "");
49
+
50
+ function addPage(name: string) {
51
+ const count = figma.root.children.length;
52
+
53
+ try {
54
+ const page = figma.createPage();
55
+ page.name = name;
56
+
57
+ return page;
58
+ } catch (e) {
59
+ throw new Error(
60
+ `Figma could not add a page: ${clause(messageOf(e))}. A run builds on a page of its own, so it needs one page more than the ` +
61
+ `${count} this file has, and Figma's Starter plan allows 3. Delete a page you no longer need, or build in another file, and run again.`,
62
+ );
63
+ }
64
+ }
65
+
66
+ const unedited = async (roots: SceneNode[], owner: string, skip?: ReadonlySet<string>) =>
67
+ read(roots[0], "fingerprint") === (await fingerprintOf(roots, owner, skip));
68
+
69
+ async function otherPageOf(owner: string, home?: PageNode) {
70
+ for (const page of figma.root.children) {
71
+ if (page === home) continue;
72
+ await page.loadAsync();
73
+
74
+ if (page.children.some(outputOf(owner))) return page.name;
75
+ }
76
+ }
77
+
78
+ async function draftsOf(owner: string) {
79
+ const drafts = [];
80
+
81
+ for (const page of figma.root.children.filter(ownedBy(owner)))
82
+ drafts.push({
83
+ page,
84
+ unchanged:
85
+ page.children.every(outputOf(owner)) && (!page.children.length || (await unedited([...page.children], owner))),
86
+ });
87
+ const parts = await ownedItems(owner);
88
+ const unchanged = drafts.flatMap((d) => (d.unchanged ? [d.page] : []));
89
+
90
+ const used =
91
+ unchanged.length > 0 && (await usesOf([...unchanged.flatMap((p) => p.children), ...parts], unchanged)).length > 0;
92
+
93
+ return { drafts, parts, used };
94
+ }
95
+
96
+ export async function run(
97
+ name: string,
98
+ { force, page, hook = () => {}, renames }: Options,
99
+ draw: Draw,
100
+ ): Promise<Imported> {
101
+ const draftName = drafted(name);
102
+ const start = figma.currentPage;
103
+ const home = page === undefined ? start : undefined;
104
+
105
+ if (ownedBy(draftName)(start))
106
+ throw new Error(
107
+ `"${start.name}" holds a draft. Open the page with ${name}'s output, or another page, and run again.`,
108
+ );
109
+ const previous = await ownedItems(name, home);
110
+ const anchored = previous.find((x) => read(x, "anchor"));
111
+ const anchor: Vector | undefined = anchored && JSON.parse(read(anchored, "anchor"));
112
+ const otherPage = await otherPageOf(name, home);
113
+ const ids = new Set(previous.map((x) => x.id));
114
+ // Earlier drafts go before the build page is made, so they make room for it.
115
+ const earlier = await draftsOf(draftName);
116
+ const { remove, letGo, removeParts } = cleanup(earlier.drafts, earlier.used);
117
+
118
+ const committed: string[] = [];
119
+ const warnings: string[] = [];
120
+ const stageName = `${name} (figdriver build in progress)`;
121
+ let stage: PageNode | undefined;
122
+ let built: Awaited<ReturnType<Draw>> | undefined;
123
+ let audit: Audit | undefined;
124
+ let output: SceneNode[] = [];
125
+ let fresh: Awaited<ReturnType<typeof ownedItems>> = [];
126
+ let landed = false;
127
+
128
+ const pageRef = () =>
129
+ home
130
+ ? { name: home.name, id: home.id }
131
+ : landed && stage
132
+ ? { name: stage.name, id: stage.id }
133
+ : { name: page!, id: null };
134
+
135
+ const result = (outcome: Outcome, message: string | undefined, draft: PageNode | null): Imported => {
136
+ const summary = built?.summary ?? NOTHING;
137
+ const live = output.filter((n) => !n.removed);
138
+
139
+ return {
140
+ ...summary,
141
+ warnings: [...warnings, ...summary.warnings],
142
+ design: name,
143
+ owner: draft ? draftName : name,
144
+ outcome,
145
+ committed,
146
+ message,
147
+ page: pageRef(),
148
+ output: live.map((n) => n.id),
149
+ draft: draft && { name: draft.name, id: draft.id },
150
+ audit: { owners: live.length ? [draft ? draftName : name] : [], ...(audit ?? NO_AUDIT) },
151
+ };
152
+ };
153
+
154
+ const toDraft = async (p: PageNode) => {
155
+ p.name = draftName;
156
+ write(p, "owner", draftName);
157
+
158
+ for (const x of fresh) write(x, "owner", draftName);
159
+ const fingerprint = await fingerprintOf(output, draftName);
160
+
161
+ for (const n of output) write(n, "fingerprint", fingerprint);
162
+ await recordLayers(output);
163
+ };
164
+
165
+ try {
166
+ if (remove.length) {
167
+ for (const p of remove) p.remove();
168
+ committed.push(`removed the earlier draft page "${draftName}"`);
169
+ }
170
+
171
+ if (removeParts) for (const x of earlier.parts) x.remove();
172
+ else {
173
+ for (const p of letGo) if (p.name === draftName) p.name = `${name} (edited draft)`;
174
+
175
+ for (const x of [...letGo, ...letGo.flatMap((p) => p.children.filter(outputOf(draftName))), ...earlier.parts])
176
+ write(x, "owner", "");
177
+ committed.push(
178
+ `let go of the earlier draft, kept as page "${name} (edited draft)", since someone edited it or uses its parts`,
179
+ );
180
+
181
+ if (earlier.used)
182
+ warnings.push(
183
+ `Layers, variables or styles elsewhere in the file use parts of the earlier draft, so it stays, as page "${name} (edited draft)", and is no longer figdriver's.`,
184
+ );
185
+ }
186
+
187
+ const build = (stage = addPage(stageName));
188
+ await figma.setCurrentPageAsync(build);
189
+ built = await draw(home?.children.filter((n) => !outputOf(name)(n)) ?? [], anchor);
190
+ await figma.setCurrentPageAsync(start);
191
+ const { summary, source } = built;
192
+
193
+ fresh = (await ownedItems(name, build)).filter((x) => !ids.has(x.id));
194
+ output = build.children.filter(outputOf(name));
195
+ audit = await auditOf(output);
196
+ // Checked after the build, so an edit made while it ran counts.
197
+ await hook("check", summary);
198
+
199
+ const clean =
200
+ !summary.fallbacks &&
201
+ !summary.unknownTextProperties.length &&
202
+ !summary.dropped.length &&
203
+ !summary.lost.length &&
204
+ Object.values(audit.problems).every((p) => !p.length);
205
+
206
+ const roots = home?.children.filter(outputOf(name)) ?? [];
207
+ const edited = roots.length > 0 && !(await unedited(roots, name, new Set(fresh.map((x) => x.id))));
208
+ const edits = edited ? await editedLayers(roots) : [];
209
+ const uses = previous.length ? await usesOf(previous, [build]) : [];
210
+ const keys = async (items: typeof fresh) => (await partsOf(items)).map(([key]) => key);
211
+ const [forward, back] = [renamer(renames), renamer(renames, true)];
212
+
213
+ const observed = {
214
+ otherPage,
215
+ edited,
216
+ edits,
217
+ ...blockers(uses, await keys(fresh), await keys(previous), forward),
218
+ clean,
219
+ force,
220
+ };
221
+
222
+ const decided = decide(observed);
223
+
224
+ if (decided !== "replace") {
225
+ await toDraft(build);
226
+ const message = why(decided, name, observed);
227
+ figma.notify(message, { error: true });
228
+
229
+ return result(decided, message, build);
230
+ }
231
+
232
+ const flows = build.flowStartingPoints;
233
+ const homeFlows = home?.flowStartingPoints ?? [];
234
+ const parts = ["component", "variable", "style"];
235
+
236
+ const inPrevious = (n: BaseNode) => hasAncestor(n, (p) => ids.has(p.id));
237
+
238
+ const steps: (Step | false | undefined)[] = [
239
+ previous.length > 0 && {
240
+ key: "migrate",
241
+ done: "moved the layers, variables and styles that used the old output to the new one",
242
+ run: () => migrate(previous, fresh, [build], parts, forward, () => hook("moved")),
243
+ undo: () => migrate(fresh, previous, [build], parts, back),
244
+ },
245
+ !home && {
246
+ key: "place",
247
+ done: `made the build page into page "${page}"`,
248
+ run: () => {
249
+ build.name = page!;
250
+ },
251
+ undo: () => {
252
+ build.name = stageName;
253
+ },
254
+ },
255
+ home && {
256
+ key: "place",
257
+ done: "placed the new output on the page",
258
+ run: () => output.forEach((n) => home.appendChild(n)),
259
+ undo: () => {
260
+ output.forEach((n) => build.appendChild(n));
261
+ build.flowStartingPoints = flows;
262
+ },
263
+ },
264
+ // Prototype links reach only layers on their own page, so they move once the new screens are on it.
265
+ home &&
266
+ previous.length > 0 && {
267
+ key: "links",
268
+ done: "moved the prototype links and flows that led to the old screens to the new ones",
269
+ run: () => migrate(previous, fresh, [build], ["screen"], forward),
270
+ undo: () => migrate(fresh, previous, [build], ["screen"], back),
271
+ },
272
+ home && {
273
+ key: "flows",
274
+ done: "merged its prototype flows into the page's",
275
+ async run() {
276
+ // Only the flows an earlier run made go: each starts at a screen of its output that carries the flow's name. A page holds one
277
+ // flow per start, so at a screen where this run starts one, its own takes the place of a flow moved there.
278
+ const kept = [];
279
+
280
+ for (const f of home.flowStartingPoints) {
281
+ const start = await figma.getNodeByIdAsync(f.nodeId);
282
+
283
+ if (
284
+ start &&
285
+ !(inPrevious(start) && read(start, "flow") === f.name) &&
286
+ !flows.some((g) => g.nodeId === f.nodeId)
287
+ )
288
+ kept.push(f);
289
+ }
290
+
291
+ home.flowStartingPoints = [...kept, ...flows];
292
+ },
293
+ undo: () => {
294
+ home.flowStartingPoints = homeFlows;
295
+ },
296
+ },
297
+ home &&
298
+ source && {
299
+ key: "hide",
300
+ done: "hid the Figma Make embed it rebuilt",
301
+ run: () => {
302
+ source.visible = false;
303
+ },
304
+ undo: () => {
305
+ source.visible = true;
306
+ },
307
+ },
308
+ ];
309
+
310
+ const replaced = await transact(
311
+ steps.filter((s) => !!s),
312
+ hook,
313
+ async () => {
314
+ // Fingerprinted before the old output goes, without the old variables and styles, so little that can fail is left after it goes.
315
+ const fingerprint = await fingerprintOf(output, name, ids);
316
+
317
+ for (const n of output) write(n, "fingerprint", fingerprint);
318
+ await recordLayers(output);
319
+ await hook("remove");
320
+ },
321
+ );
322
+
323
+ committed.push(...replaced.stayed);
324
+
325
+ if ("error" in replaced) throw replaced.error;
326
+ landed = true;
327
+
328
+ for (const [i, x] of previous.entries()) {
329
+ try {
330
+ x.remove();
331
+ } catch (e) {
332
+ if (i)
333
+ committed.push(`removed ${i} of the old output's ${previous.length} layers, variable collections and styles`);
334
+
335
+ throw e;
336
+ }
337
+ }
338
+
339
+ if (previous.length) committed.push("removed the old output");
340
+ await hook("removed");
341
+
342
+ if (home) build.remove();
343
+ await figma.setCurrentPageAsync(home ?? build);
344
+ figma.viewport.scrollAndZoomIntoView(output);
345
+ figma.notify(`${name} imported: ${summary.components} components, ${summary.instances} instances`);
346
+
347
+ return result("replace", undefined, null);
348
+ } catch (e) {
349
+ const failure = clause(messageOf(e));
350
+
351
+ const recover = async () => {
352
+ await figma.setCurrentPageAsync(landed && !home && stage ? stage : start);
353
+
354
+ if (!stage || stage.removed) return null;
355
+
356
+ if (!built) {
357
+ for (const x of (await ownedItems(name, stage)).filter((x) => !ids.has(x.id))) x.remove();
358
+ stage.remove();
359
+ } else if (!landed && output.some((n) => n.parent === stage)) {
360
+ await toDraft(stage);
361
+
362
+ return stage;
363
+ } else if (home && !stage.children.length) stage.remove();
364
+
365
+ return null;
366
+ };
367
+
368
+ const draft = await recover().catch(() => null);
369
+
370
+ const where = draft
371
+ ? ` The new build is on page "${draftName}".`
372
+ : landed
373
+ ? ` The new output is on page "${pageRef().name}".`
374
+ : "";
375
+
376
+ const message =
377
+ `${built ? `Replacing ${name}'s output` : `Building ${name}`} failed: ${failure}. ` +
378
+ (committed.length
379
+ ? `What stayed changed: ${committed.join("; ")}.`
380
+ : "Every change was undone, so the file is as it was.") +
381
+ where;
382
+
383
+ figma.notify(message, { error: true });
384
+
385
+ return result("failed", message, draft);
386
+ }
387
+ }