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,684 @@
1
+ import { BLOCK_LEVEL, round, type Box, type El, type FrameEl, type Pseudo, type Style } from "./snapshot";
2
+
3
+ export type Sizing = "FIXED" | "HUG" | "FILL";
4
+
5
+ export type Align = "MIN" | "CENTER" | "MAX";
6
+
7
+ type Axis = "x" | "y";
8
+
9
+ type Pad = [top: number, right: number, bottom: number, left: number];
10
+
11
+ export type Track = { type: "FLEX" | "FIXED"; px: number };
12
+
13
+ export type Container =
14
+ | {
15
+ mode: "HORIZONTAL" | "VERTICAL";
16
+ gap: number;
17
+ main: Align | "SPACE_BETWEEN";
18
+ cross: Align | "BASELINE";
19
+ wrap: boolean;
20
+ /** The gap between wrapped lines. */
21
+ rowGap?: number;
22
+ pad: Pad;
23
+ }
24
+ | { mode: "GRID"; cols: Track[]; rows: Track[]; gap: [row: number, col: number]; pad: Pad };
25
+
26
+ export type Cell = { row: number; col: number; rowSpan: number; colSpan: number; h: Align; v: Align };
27
+
28
+ type Constraint = "MIN" | "MAX" | "STRETCH";
29
+
30
+ export type Place =
31
+ | { positioning: "AUTO"; w: Sizing; h: Sizing; cell?: Cell }
32
+ | {
33
+ positioning: "ABSOLUTE";
34
+ w: Sizing;
35
+ h: Sizing;
36
+ x: number;
37
+ y: number;
38
+ constraints: { horizontal: Constraint; vertical: Constraint };
39
+ };
40
+
41
+ export type Layout = { container?: Container; place: Place; maxWidth?: number; minHeight?: number; rotation: number };
42
+
43
+ export type Parent = { el: FrameEl; container: Container; w: Sizing; h: Sizing };
44
+
45
+ const TOL = 1.5;
46
+
47
+ /** Gaps within this of the tightest gap are one gap. Wider gaps split the stack. Sub-pixel layout makes an exact 3px read as 3.01. */
48
+ const GAP_SPREAD = 3.5;
49
+ const near = (a: number, b: number, tol = TOL) => Math.abs(a - b) <= tol;
50
+ const px = (v: string) => (v.endsWith("px") ? parseFloat(v) : undefined);
51
+
52
+ export const isAbsolute = (el: El) => el.style.position === "absolute" || el.style.position === "fixed";
53
+ const flowOf = (el: FrameEl) => el.children.filter((c) => !isAbsolute(c));
54
+ const start = (b: Box, a: Axis) => (a === "x" ? b[0] : b[1]);
55
+ const size = (b: Box, a: Axis) => (a === "x" ? b[2] : b[3]);
56
+ const end = (b: Box, a: Axis) => start(b, a) + size(b, a);
57
+ const mean = (xs: number[]) => xs.reduce((s, x) => s + x, 0) / xs.length;
58
+
59
+ function contentBox(el: El): Box {
60
+ const [x, y, w, h] = el.box;
61
+ const { pad, border } = el.style;
62
+
63
+ return [
64
+ x + border[3] + pad[3],
65
+ y + border[0] + pad[0],
66
+ w - border[1] - border[3] - pad[1] - pad[3],
67
+ h - border[0] - border[2] - pad[0] - pad[2],
68
+ ];
69
+ }
70
+
71
+ function alignIn(b: Box, within: Box, a: Axis): Align {
72
+ const lead = start(b, a) - start(within, a);
73
+ const trail = end(within, a) - end(b, a);
74
+
75
+ if (near(lead, 0)) return "MIN";
76
+
77
+ if (near(lead, trail)) return "CENTER";
78
+
79
+ if (near(trail, 0)) return "MAX";
80
+
81
+ return lead < trail ? "MIN" : "MAX";
82
+ }
83
+
84
+ const gapsOf = (els: El[], a: Axis) => els.slice(1).map((c, i) => start(c.box, a) - end(els[i].box, a));
85
+
86
+ const overlaps = (p: Box, n: Box, a: Axis) => start(n, a) < end(p, a) && end(n, a) > start(p, a);
87
+
88
+ /** Gaps between neighbors on one line of a wrapped row or column, never across a line break. */
89
+ const lineGapsOf = (els: El[], a: Axis) => {
90
+ const cross: Axis = a === "x" ? "y" : "x";
91
+
92
+ return els
93
+ .slice(1)
94
+ .flatMap((c, i) =>
95
+ overlaps(els[i].box, c.box, cross) && start(c.box, a) >= start(els[i].box, a)
96
+ ? [start(c.box, a) - end(els[i].box, a)]
97
+ : [],
98
+ );
99
+ };
100
+
101
+ type Direction = "HORIZONTAL" | "VERTICAL" | "GRID";
102
+
103
+ const tracksOf = (v: string) =>
104
+ v === "none"
105
+ ? []
106
+ : v
107
+ .split(" ")
108
+ .map((t) => parseFloat(t))
109
+ .filter((n) => !Number.isNaN(n));
110
+
111
+ function directionOf(el: FrameEl): Direction {
112
+ const s = el.style;
113
+
114
+ if (s.display.endsWith("grid") && tracksOf(s.gridCols).length && tracksOf(s.gridRows).length) return "GRID";
115
+
116
+ if (s.display.endsWith("flex")) return s.flexDirection.startsWith("column") ? "VERTICAL" : "HORIZONTAL";
117
+ const flow = flowOf(el);
118
+ const [first] = flow;
119
+
120
+ const oneLine =
121
+ flow.length > 1 &&
122
+ flow.every((c) => c.box[1] < first.box[1] + first.box[3] - 1 && c.box[1] + c.box[3] > first.box[1] + 1);
123
+
124
+ return oneLine ? "HORIZONTAL" : "VERTICAL";
125
+ }
126
+
127
+ const JUSTIFY = new Map(
128
+ Object.entries({
129
+ "flex-start": "MIN",
130
+ start: "MIN",
131
+ left: "MIN",
132
+ normal: "MIN",
133
+ center: "CENTER",
134
+ "flex-end": "MAX",
135
+ end: "MAX",
136
+ right: "MAX",
137
+ "space-between": "SPACE_BETWEEN",
138
+ "space-around": "SPACE_BETWEEN",
139
+ "space-evenly": "SPACE_BETWEEN",
140
+ } as const),
141
+ );
142
+
143
+ const ALIGN = new Map(
144
+ Object.entries({
145
+ normal: "MIN",
146
+ stretch: "MIN",
147
+ "flex-start": "MIN",
148
+ start: "MIN",
149
+ "self-start": "MIN",
150
+ center: "CENTER",
151
+ "flex-end": "MAX",
152
+ end: "MAX",
153
+ "self-end": "MAX",
154
+ baseline: "BASELINE",
155
+ } as const),
156
+ );
157
+
158
+ const TEXT_ALIGN = new Map(
159
+ Object.entries({
160
+ start: "MIN",
161
+ left: "MIN",
162
+ center: "CENTER",
163
+ end: "MAX",
164
+ right: "MAX",
165
+ justify: "MIN",
166
+ } as const),
167
+ );
168
+
169
+ function mainAlignOf(el: FrameEl, dir: Direction) {
170
+ if (el.style.display.endsWith("flex")) return JUSTIFY.get(el.style.justify) ?? "MIN";
171
+
172
+ return dir === "HORIZONTAL" ? (TEXT_ALIGN.get(el.style.textAlign) ?? "MIN") : "MIN";
173
+ }
174
+
175
+ function looseAlign(el: FrameEl, dir: Direction): Align {
176
+ const a: Axis = dir === "HORIZONTAL" ? "y" : "x";
177
+ const cb = contentBox(el);
178
+
179
+ const votes = flowOf(el)
180
+ .filter((c) => !near(size(c.box, a), size(cb, a)))
181
+ .map((c) => alignIn(c.box, cb, a));
182
+
183
+ const counts = (["MIN", "CENTER", "MAX"] as const).map((v) => [v, votes.filter((x) => x === v).length] as const);
184
+
185
+ return counts.reduce((best, c) => (c[1] > best[1] ? c : best))[0];
186
+ }
187
+
188
+ function crossAlignOf(el: FrameEl, dir: Direction) {
189
+ return el.style.display.endsWith("flex") ? (ALIGN.get(el.style.align) ?? "MIN") : looseAlign(el, dir);
190
+ }
191
+
192
+ function trackSpans(sizes: number[], gap: number, from: number) {
193
+ let at = from;
194
+
195
+ return sizes.map((s) => {
196
+ const span: [number, number] = [at, at + s];
197
+ at += s + gap;
198
+
199
+ return span;
200
+ });
201
+ }
202
+
203
+ type GridInfo = {
204
+ cols: [number, number][];
205
+ rows: [number, number][];
206
+ cells: Map<El, { box: Box; cell: Cell }>;
207
+ collisions: Set<El>;
208
+ };
209
+
210
+ const gridCache = new WeakMap<FrameEl, GridInfo>();
211
+
212
+ function spanIndex(spans: [number, number][], at: number) {
213
+ const i = spans.findIndex(([, e]) => at < e);
214
+
215
+ return i < 0 ? spans.length - 1 : i;
216
+ }
217
+
218
+ function measureCell(c: El, cols: [number, number][], rows: [number, number][]) {
219
+ const [x, y, w, h] = c.box;
220
+
221
+ const col = spanIndex(cols, x + 1),
222
+ colEnd = Math.max(col, spanIndex(cols, x + w - 1));
223
+
224
+ const row = spanIndex(rows, y + 1),
225
+ rowEnd = Math.max(row, spanIndex(rows, y + h - 1));
226
+
227
+ const box: Box = [cols[col][0], rows[row][0], cols[colEnd][1] - cols[col][0], rows[rowEnd][1] - rows[row][0]];
228
+
229
+ return {
230
+ box,
231
+ cell: {
232
+ row,
233
+ col,
234
+ rowSpan: rowEnd - row + 1,
235
+ colSpan: colEnd - col + 1,
236
+ h: alignIn(c.box, box, "x"),
237
+ v: alignIn(c.box, box, "y"),
238
+ },
239
+ };
240
+ }
241
+
242
+ function gridInfoOf(grid: FrameEl): GridInfo {
243
+ const cached = gridCache.get(grid);
244
+
245
+ if (cached) return cached;
246
+ const cb = contentBox(grid);
247
+ const cols = trackSpans(tracksOf(grid.style.gridCols), grid.style.gap[1], cb[0]);
248
+ const rows = trackSpans(tracksOf(grid.style.gridRows), grid.style.gap[0], cb[1]);
249
+ const cells = new Map<El, { box: Box; cell: Cell }>();
250
+ const collisions = new Set<El>();
251
+ const occupied = new Set<string>();
252
+
253
+ if (cols.length && rows.length) {
254
+ for (const child of flowOf(grid)) {
255
+ const measured = measureCell(child, cols, rows);
256
+ cells.set(child, measured);
257
+ const { row, col, rowSpan, colSpan } = measured.cell;
258
+ let clash = false;
259
+
260
+ for (let r = row; r < row + rowSpan && !clash; r++) {
261
+ for (let k = col; k < col + colSpan; k++) {
262
+ if (occupied.has(`${r},${k}`)) {
263
+ clash = true;
264
+ break;
265
+ }
266
+ }
267
+ }
268
+
269
+ if (clash) {
270
+ collisions.add(child);
271
+ continue;
272
+ }
273
+
274
+ for (let r = row; r < row + rowSpan; r++) {
275
+ for (let k = col; k < col + colSpan; k++) occupied.add(`${r},${k}`);
276
+ }
277
+ }
278
+ }
279
+
280
+ const info: GridInfo = { cols, rows, cells, collisions };
281
+ gridCache.set(grid, info);
282
+
283
+ return info;
284
+ }
285
+
286
+ function cellOf(c: El, grid: FrameEl) {
287
+ const info = gridInfoOf(grid);
288
+
289
+ return info.cells.get(c) ?? measureCell(c, info.cols, info.rows);
290
+ }
291
+
292
+ /**
293
+ * Flow children of a CSS Grid whose cell span overlaps an earlier child.
294
+ * Figma's Grid auto layout refuses two children in the same cell, so colliding items fall back to absolute positioning.
295
+ */
296
+ export function gridCellCollisions(grid: FrameEl): Set<El> {
297
+ return directionOf(grid) === "GRID" ? gridInfoOf(grid).collisions : new Set();
298
+ }
299
+
300
+ function wantsFill(c: El, parent: FrameEl, a: Axis): boolean {
301
+ if (isAbsolute(c)) return false;
302
+ const dir = directionOf(parent);
303
+
304
+ if (dir === "GRID") {
305
+ if (gridCellCollisions(parent).has(c)) return false;
306
+
307
+ return near(size(c.box, a), size(cellOf(c, parent).box, a));
308
+ }
309
+
310
+ const primary = (dir === "HORIZONTAL") === (a === "x");
311
+ const flex = parent.style.display.endsWith("flex");
312
+
313
+ if (primary) return flex && parseFloat(c.style.flexGrow) > 0;
314
+
315
+ if (c.kind === "text" && (a === "y" || (singleLine(c) && near(c.content[2], c.box[2], 2)))) return false;
316
+ const avail = size(contentBox(parent), a);
317
+
318
+ if (flex)
319
+ return (
320
+ /^(normal|stretch)$/.test(parent.style.align) &&
321
+ /^(auto|normal|stretch)$/.test(c.style.alignSelf) &&
322
+ near(size(c.box, a), avail)
323
+ );
324
+
325
+ if (dir === "HORIZONTAL") return false;
326
+
327
+ return BLOCK_LEVEL.test(c.style.display) && near(c.box[2], Math.min(avail, px(c.style.maxWidth) ?? Infinity));
328
+ }
329
+
330
+ function hugs(el: FrameEl, container: Container, a: Axis): boolean {
331
+ const flow = flowOf(el);
332
+
333
+ if (!flow.length) return false;
334
+ const { pad } = container;
335
+ const { border } = el.style;
336
+ const edges = a === "x" ? pad[1] + pad[3] + border[1] + border[3] : pad[0] + pad[2] + border[0] + border[2];
337
+ let content: number;
338
+
339
+ if (container.mode === "GRID") {
340
+ const tracks = a === "x" ? container.cols : container.rows;
341
+
342
+ if (tracks.some((t) => t.type === "FLEX")) return false;
343
+ content = tracks.reduce((s, t) => s + t.px, 0) + container.gap[a === "x" ? 1 : 0] * (tracks.length - 1);
344
+ } else if ((container.mode === "HORIZONTAL") === (a === "x")) {
345
+ if (container.main === "SPACE_BETWEEN" && flow.length > 1) return false;
346
+ content = flow.reduce((s, c) => s + size(c.box, a), 0) + container.gap * (flow.length - 1);
347
+ } else {
348
+ content = Math.max(...flow.map((c) => size(c.box, a)));
349
+ }
350
+
351
+ return near(content + edges, size(el.box, a));
352
+ }
353
+
354
+ const singleLine = (el: Extract<El, { kind: "text" }>) =>
355
+ !el.runs.some((r) => r.text.includes("\n")) && el.box[3] <= Math.max(...el.runs.map((r) => r.lineHeight)) * 1.5;
356
+
357
+ function containerOf(el: FrameEl): Container {
358
+ const s = el.style;
359
+ const dir = directionOf(el);
360
+
361
+ if (dir === "GRID") {
362
+ const cols = tracksOf(s.gridCols);
363
+ const equal = cols.every((c) => near(c, cols[0], 0.5));
364
+
365
+ return {
366
+ mode: "GRID",
367
+ gap: s.gap,
368
+ pad: [...s.pad],
369
+ cols: cols.map((v) => ({ type: equal ? "FLEX" : "FIXED", px: v })),
370
+ rows: tracksOf(s.gridRows).map((v) => ({ type: "FIXED", px: v })),
371
+ };
372
+ }
373
+
374
+ const a: Axis = dir === "HORIZONTAL" ? "x" : "y";
375
+ const flow = flowOf(el);
376
+ const main = mainAlignOf(el, dir);
377
+ const wrap = s.flexWrap.startsWith("wrap");
378
+ const gaps = wrap ? lineGapsOf(flow, a) : gapsOf(flow, a);
379
+
380
+ const gap =
381
+ main === "SPACE_BETWEEN" ? 0 : gaps.length ? Math.round(mean(gaps) * 2) / 2 : s.gap[dir === "HORIZONTAL" ? 1 : 0];
382
+
383
+ const pad: Pad = [...s.pad];
384
+ const [startSide, endSide] = dir === "HORIZONTAL" ? [3, 1] : [0, 2];
385
+
386
+ if (main === "MIN" && flow.length) {
387
+ // Margins on the first and last child read as padding, which is what the browser laid out.
388
+ const lead = start(flow[0].box, a) - start(el.box, a) - s.border[startSide];
389
+
390
+ if (lead > pad[startSide]) pad[startSide] = round(lead);
391
+ const last = flow[flow.length - 1];
392
+ const trail = end(el.box, a) - s.border[endSide] - end(last.box, a);
393
+
394
+ if (trail >= 0 && near(trail, pad[endSide] + last.style.margin[endSide])) pad[endSide] = round(trail);
395
+ }
396
+
397
+ return {
398
+ mode: dir,
399
+ gap,
400
+ main,
401
+ cross: crossAlignOf(el, dir),
402
+ wrap,
403
+ rowGap: wrap ? s.gap[dir === "HORIZONTAL" ? 0 : 1] : undefined,
404
+ pad,
405
+ };
406
+ }
407
+
408
+ const matrixOf = (t: string) => (t.startsWith("matrix(") ? t.slice(7, -1).split(",").map(Number) : undefined);
409
+
410
+ function rotationOf(t: string) {
411
+ const m = matrixOf(t);
412
+
413
+ return m && m[1] !== 0 ? Math.round((-Math.atan2(m[1], m[0]) * 180) / Math.PI) : 0;
414
+ }
415
+
416
+ export function layoutOf(el: El, parent?: Parent): Layout {
417
+ const container = el.kind === "frame" ? containerOf(el) : undefined;
418
+ const rotation = rotationOf(el.style.transform);
419
+
420
+ const sizing = (a: Axis): Sizing => {
421
+ if (parent && parent[a === "x" ? "w" : "h"] !== "HUG" && wantsFill(el, parent.el, a)) return "FILL";
422
+
423
+ if (el.kind === "text") return a === "y" || singleLine(el) ? "HUG" : "FIXED";
424
+
425
+ if (el.kind === "frame" && container && !flowOf(el).some((c) => wantsFill(c, el, a)) && hugs(el, container, a))
426
+ return "HUG";
427
+
428
+ return "FIXED";
429
+ };
430
+
431
+ const w = sizing("x"),
432
+ h = sizing("y");
433
+
434
+ const gridClash =
435
+ !!parent && !isAbsolute(el) && parent.container.mode === "GRID" && gridCellCollisions(parent.el).has(el);
436
+
437
+ if (parent && (isAbsolute(el) || gridClash)) {
438
+ const [px0, py0, pw, ph] = parent.el.box;
439
+ const [x, y, cw, ch] = el.box;
440
+
441
+ const constraint = (lead: number, trail: number): Constraint =>
442
+ near(lead, 0) && near(trail, 0) ? "STRETCH" : near(trail, 0) ? "MAX" : "MIN";
443
+
444
+ return {
445
+ container,
446
+ rotation,
447
+ place: {
448
+ positioning: "ABSOLUTE",
449
+ w,
450
+ h,
451
+ x: round(x - px0),
452
+ y: round(y - py0),
453
+ constraints: {
454
+ horizontal: constraint(x - px0, px0 + pw - x - cw),
455
+ vertical: constraint(y - py0, py0 + ph - y - ch),
456
+ },
457
+ },
458
+ };
459
+ }
460
+
461
+ const cap = px(el.style.maxWidth);
462
+ const reserved = el.kind === "text" && el.box[3] - el.content[3] > Math.max(...el.runs.map((r) => r.lineHeight)) / 2;
463
+
464
+ return {
465
+ container,
466
+ rotation,
467
+ maxWidth: w === "FILL" ? cap : undefined,
468
+ minHeight: reserved ? el.box[3] : undefined,
469
+ place: {
470
+ positioning: "AUTO",
471
+ w,
472
+ h,
473
+ cell: parent?.container.mode === "GRID" ? cellOf(el, parent.el).cell : undefined,
474
+ },
475
+ };
476
+ }
477
+
478
+ /** CSS paint order: positioned boxes (and flex/grid items with explicit z-index) above static ones, DOM order breaking ties. */
479
+ export function paintOrder(el: El, flexOrGrid = false) {
480
+ const z = parseInt(el.style.zIndex);
481
+ const positioned = el.style.position !== "static" || (flexOrGrid && !Number.isNaN(z));
482
+
483
+ return !positioned ? -0.5 : Number.isNaN(z) ? 0 : z;
484
+ }
485
+
486
+ /**
487
+ * The layer order of a frame's children, bottom first, as indexes into `children`. Only `movable` children change places: in a
488
+ * stack, moving a flow child would reflow its siblings, so only absolute ones move, while a grid pins every child to its cell.
489
+ */
490
+ export function layerOrder(children: El[], movable: (i: number) => boolean, flexOrGrid: boolean) {
491
+ const order = children.flatMap((_, i) => (movable(i) ? [] : [i]));
492
+ const rank = (i: number) => paintOrder(children[i], flexOrGrid);
493
+ const above = (a: number, b: number) => rank(a) > rank(b) || (rank(a) === rank(b) && a > b);
494
+
495
+ for (const i of children.flatMap((_, idx) => (movable(idx) ? [idx] : []))) {
496
+ let pos = order.length;
497
+
498
+ while (pos > 0 && above(order[pos - 1], i)) pos--;
499
+ order.splice(pos, 0, i);
500
+ }
501
+
502
+ return order;
503
+ }
504
+
505
+ const SYNTHETIC: Style = {
506
+ display: "block",
507
+ position: "static",
508
+ zIndex: "auto",
509
+ flexDirection: "row",
510
+ flexWrap: "nowrap",
511
+ justify: "normal",
512
+ align: "normal",
513
+ alignSelf: "auto",
514
+ flexGrow: "0",
515
+ gap: [0, 0],
516
+ pad: [0, 0, 0, 0],
517
+ margin: [0, 0, 0, 0],
518
+ maxWidth: "none",
519
+ gridCols: "none",
520
+ gridRows: "none",
521
+ textAlign: "start",
522
+ bg: "rgba(0, 0, 0, 0)",
523
+ bgImage: "none",
524
+ bgSize: "auto",
525
+ bgPos: "0% 0%",
526
+ radius: [0, 0, 0, 0],
527
+ border: [0, 0, 0, 0],
528
+ borderColor: "rgba(0, 0, 0, 0)",
529
+ borderStyle: "none",
530
+ shadow: "none",
531
+ opacity: 1,
532
+ overflow: "visible",
533
+ transform: "none",
534
+ backdrop: "none",
535
+ objectFit: "fill",
536
+ };
537
+
538
+ export const SYNTHETIC_TAGS = { stack: "Stack", offset: "Offset", align: "Wrapper" } as const;
539
+
540
+ /** A wrapper paints where the element it wraps did, so a z-index survives the wrapping. */
541
+ const paintedAs = (c: El): Partial<Style> => ({ position: c.style.position, zIndex: c.style.zIndex });
542
+
543
+ const synthetic = (
544
+ tag: keyof typeof SYNTHETIC_TAGS,
545
+ box: Box,
546
+ children: El[],
547
+ style: Partial<Style> = {},
548
+ ): FrameEl => ({
549
+ kind: "frame",
550
+ tag,
551
+ cls: [],
552
+ box: [round(box[0]), round(box[1]), round(box[2]), round(box[3])],
553
+ style: { ...SYNTHETIC, ...style },
554
+ children,
555
+ pseudos: [],
556
+ bgImages: [],
557
+ });
558
+
559
+ const pseudoEl = (p: Pseudo): FrameEl => ({
560
+ kind: "frame",
561
+ tag: `::${p.which}`,
562
+ cls: [],
563
+ box: p.box,
564
+ style: { ...p.style, position: p.flow ? "static" : "absolute" },
565
+ children: [],
566
+ pseudos: [],
567
+ bgImages: [],
568
+ vars: p.vars,
569
+ });
570
+
571
+ /** A flow child moved by translateY: wrap it in a box whose padding reproduces the offset under the parent's alignment. */
572
+ function offsetWrapper(c: El, parent: FrameEl): El {
573
+ const m = matrixOf(c.style.transform);
574
+
575
+ if (!m || isAbsolute(c) || m[0] !== 1 || m[1] !== 0 || m[2] !== 0 || m[3] !== 1 || Math.abs(m[5]) < 0.5) return c;
576
+ const ty = m[5];
577
+ const [x, y, w, h] = c.box;
578
+ const origin = y - ty;
579
+ const cb = contentBox(parent);
580
+ const centered = near(origin + h / 2, cb[1] + cb[3] / 2);
581
+
582
+ if (!centered && ty < 0) return c;
583
+ const grow = centered ? 2 * Math.abs(ty) : ty;
584
+
585
+ return synthetic(
586
+ "offset",
587
+ [x, centered ? origin - Math.abs(ty) : origin, w, h + grow],
588
+ [{ ...c, style: { ...c.style, transform: "none" } }],
589
+ { ...paintedAs(c), pad: [ty > 0 ? grow : 0, 0, ty < 0 ? grow : 0, 0] },
590
+ );
591
+ }
592
+
593
+ /**
594
+ * Measured gaps already hold the margins of a start-aligned stack. Grid cells and centered or spread rows have no such gap,
595
+ * so there a child's margins become the padding of a wrapper that takes its place.
596
+ */
597
+ function marginWrapper(c: El, parent: FrameEl): El {
598
+ const [t, r, b, l] = c.style.margin;
599
+ const dir = directionOf(parent);
600
+
601
+ if (
602
+ isAbsolute(c) ||
603
+ (dir !== "GRID" && mainAlignOf(parent, dir) === "MIN") ||
604
+ [t, r, b, l].every((m) => Math.abs(m) < 0.5)
605
+ )
606
+ return c;
607
+ const [x, y, w, h] = c.box;
608
+
609
+ return synthetic(
610
+ "offset",
611
+ [x - l, y - t, w + l + r, h + t + b],
612
+ [{ ...c, style: { ...c.style, margin: [0, 0, 0, 0] } }],
613
+ { ...paintedAs(c), pad: [t, r, b, l] },
614
+ );
615
+ }
616
+
617
+ function alignWrappers(el: FrameEl): El[] {
618
+ if (directionOf(el) !== "VERTICAL" || el.style.display.endsWith("flex")) return el.children;
619
+ const majority = looseAlign(el, "VERTICAL");
620
+ const cb = contentBox(el);
621
+
622
+ return el.children.map((c) =>
623
+ isAbsolute(c) || near(c.box[2], cb[2]) || alignIn(c.box, cb, "x") === majority
624
+ ? c
625
+ : synthetic("align", [cb[0], c.box[1], cb[2], c.box[3]], [c], paintedAs(c)),
626
+ );
627
+ }
628
+
629
+ function groupByGaps(el: FrameEl): El[] {
630
+ const dir = directionOf(el);
631
+ const flow = flowOf(el);
632
+
633
+ if (dir === "GRID" || mainAlignOf(el, dir) !== "MIN" || el.style.flexWrap.startsWith("wrap") || flow.length < 3)
634
+ return el.children;
635
+ const a: Axis = dir === "HORIZONTAL" ? "x" : "y";
636
+ const gaps = gapsOf(flow, a);
637
+ const tight = Math.min(...gaps) + GAP_SPREAD;
638
+
639
+ if (Math.max(...gaps) <= tight) return el.children;
640
+ const segments: El[][] = [[flow[0]]];
641
+ gaps.forEach((g, i) => (g > tight ? segments.push([flow[i + 1]]) : segments[segments.length - 1].push(flow[i + 1])));
642
+ const cb = contentBox(el);
643
+
644
+ const stacks = segments.map((seg) => {
645
+ if (seg.length === 1) return seg[0];
646
+
647
+ const top = Math.min(...seg.map((c) => c.box[1])),
648
+ bottom = Math.max(...seg.map((c) => c.box[1] + c.box[3]));
649
+
650
+ const stack =
651
+ dir === "VERTICAL"
652
+ ? synthetic("stack", [cb[0], top, cb[2], bottom - top], seg)
653
+ : synthetic(
654
+ "stack",
655
+ [seg[0].box[0], top, end(seg[seg.length - 1].box, "x") - seg[0].box[0], bottom - top],
656
+ seg,
657
+ { display: "flex", align: el.style.align },
658
+ );
659
+
660
+ return restructure(stack);
661
+ });
662
+
663
+ return [...stacks, ...el.children.filter(isAbsolute)];
664
+ }
665
+
666
+ function restructure(el: FrameEl): FrameEl {
667
+ const aligned: FrameEl = { ...el, children: alignWrappers(el) };
668
+
669
+ return { ...aligned, children: groupByGaps(aligned) };
670
+ }
671
+
672
+ export function normalize(el: El): El {
673
+ if (el.kind !== "frame") return el;
674
+ const children = el.children.map(normalize);
675
+
676
+ for (const p of el.pseudos) {
677
+ if (p.flow && p.which === "before") children.unshift(pseudoEl(p));
678
+ else children.push(pseudoEl(p));
679
+ }
680
+
681
+ const self: FrameEl = { ...el, children, pseudos: [] };
682
+
683
+ return restructure({ ...self, children: children.map((c) => offsetWrapper(marginWrapper(c, self), self)) });
684
+ }