blockout-editor 0.0.0-stage → 0.2.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/engine.js ADDED
@@ -0,0 +1,2839 @@
1
+ /* ---------------------------------------------------------------------------
2
+ * Blockout's file editor, inside the page. Blockout's file view adds it to an HTML file it shows (the page runs in a
3
+ * sandboxed frame with an origin of its own, so Blockout can't reach in); a project's dev page loads it itself. It
4
+ * draws in the page what has to follow the page (the outline of what is pointed at and picked, its margin, padding
5
+ * and gap bands to drag, the rulers and guides), reads what an element's styles are and how each stands against the
6
+ * page's own tokens, and changes them live when the panel asks. The panel (Blockout's, beside the page) draws
7
+ * everything else. They talk only by postMessage: the page's own scripts can read what is sent, and nothing sent is
8
+ * private (values, token names, labels).
9
+ *
10
+ * Plain JS that runs as it is in any page: no imports, no build. scripts/editor-engine.mjs turns it into the string
11
+ * Blockout puts in the page (lib/editor/engine.gen.ts).
12
+ *
13
+ * Reading the tokens and the cascade (which rule's value an element shows, and whether it is a token, a match or rogue)
14
+ * is adapted from Scootch (https://github.com/saniaio/scootch), under its licence:
15
+ *
16
+ * MIT License
17
+ *
18
+ * Copyright (c) 2026 Sania Saleh
19
+ *
20
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
21
+ * of this software and associated documentation files (the "Software"), to deal
22
+ * in the Software without restriction, including without limitation the rights
23
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
24
+ * copies of the Software, and to permit persons to whom the Software is
25
+ * furnished to do so, subject to the following conditions:
26
+ *
27
+ * The above copyright notice and this permission notice shall be included in all
28
+ * copies or substantial portions of the Software.
29
+ *
30
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
31
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
32
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
33
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
34
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
35
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
36
+ * SOFTWARE.
37
+ * --------------------------------------------------------------------------- */
38
+ /* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-unused-expressions -- plain JS that runs in any page as it is */
39
+ (function () {
40
+ if (window.__blockoutEditor) return;
41
+ window.__blockoutEditor = true;
42
+
43
+ // In a project, the page says where Blockout's panel is: { origin }. In Blockout, the panel is this frame's parent.
44
+ var cfg = window.__blockoutEditorConfig || {};
45
+ // Its panels: in a project, every frame from Blockout's origin that has spoken (the design panel and the layers). In
46
+ // a frame of the kit's canvas (cfg.frame), the project's own page around it, which passes messages on to the panels.
47
+ var peers = cfg.frame ? [window.parent] : cfg.origin ? [] : window.parent !== window ? [window.parent] : [];
48
+ var peerOrigin = cfg.frame ? location.origin : cfg.origin || "*";
49
+ // The kit's canvas, open in a project's page: the frame being worked in, which the panels talk to through this page.
50
+ var relay = null;
51
+ var panelOn = false;
52
+ // Open: the page itself stands still under the canvas. Closed: the page is worked on again, with what was changed in
53
+ // the canvas's frames made the same here.
54
+ // The kit switches editing off itself when its panel is put away, without waiting on the panel to say so.
55
+ window.__blockoutEditorSetOn = function (on) {
56
+ panelOn = !!on;
57
+ if (!relay) setOn(!!on);
58
+ };
59
+ // The element picked now, for the kit's comment box to sit beside.
60
+ window.__blockoutEditorPicked = function () {
61
+ return S.sel || null;
62
+ };
63
+ window.__blockoutEditorRelay = function (w, changesThere) {
64
+ relay = w || null;
65
+ if (relay) return setOn(false);
66
+ if (changesThere) mirror(changesThere);
67
+ setOn(panelOn);
68
+ send({ type: "ready", tokens: tokens() });
69
+ reportChanges();
70
+ report();
71
+ };
72
+ function send(msg) {
73
+ msg.blockoutEditor = 1;
74
+ // Zooms are the kit's canvas's, in this same page.
75
+ if (cfg.origin && !cfg.frame && (msg.type === "zoom" || msg.type === "zoomKey")) window.dispatchEvent(new CustomEvent("blockout-editor:zoom", { detail: msg }));
76
+ peers.forEach(function (p) {
77
+ try {
78
+ p.postMessage(msg, peerOrigin);
79
+ } catch (e) {}
80
+ });
81
+ }
82
+
83
+ // The brand's colours, written out: the page has none of Blockout's tokens.
84
+ var ACCENT = "#ff4d2e";
85
+ // Distances, held on ⌥: a red apart from the selection's orange, as Figma's are apart from its blue.
86
+ var MEASURE = "#e0245e";
87
+ var INK = "#101010";
88
+ var RS = 20; // the rulers' depth
89
+
90
+ var S = {
91
+ on: false,
92
+ rulers: false,
93
+ block: { links: true, buttons: true, hovers: true },
94
+ hover: null,
95
+ sel: null,
96
+ guides: { x: [], y: [] },
97
+ drag: null,
98
+ dirty: false,
99
+ };
100
+
101
+ /* ---------------------------------------------------------------- elements, and what they were */
102
+ var keys = new WeakMap();
103
+ var byKey = new Map();
104
+ var nextKey = 1;
105
+ function keyOf(el) {
106
+ var k = keys.get(el);
107
+ if (!k) {
108
+ k = nextKey++;
109
+ keys.set(el, k);
110
+ byKey.set(k, el);
111
+ }
112
+ return k;
113
+ }
114
+ // What each changed element was before its first change: its style and class attributes, and each property's value
115
+ // as it showed then.
116
+ var originals = new Map();
117
+ var scratch = document.createElement("div");
118
+ function remember(el) {
119
+ if (!originals.has(el)) originals.set(el, { style: el.getAttribute("style"), cls: el.getAttribute("class"), before: {} });
120
+ return originals.get(el);
121
+ }
122
+ function styleOf(text) {
123
+ scratch.setAttribute("style", text || "");
124
+ return scratch.style;
125
+ }
126
+
127
+ /* ---------------------------------------------------------------- tokens (after Scootch's tokens.js) */
128
+ var PREFIX = {
129
+ space: ["--space-", "--spacing-", "--spacing", "--gap-", "--size-"],
130
+ fontSize: ["--font-size-", "--text-", "--fs-"],
131
+ lineHeight: ["--line-height-", "--leading-", "--lh-"],
132
+ weight: ["--weight-", "--font-weight-", "--fw-"],
133
+ tracking: ["--tracking-", "--letter-spacing-"],
134
+ radius: ["--radius-", "--rounded-", "--radius"],
135
+ borderWidth: ["--border-width", "--border-"],
136
+ shadow: ["--shadow", "--elevation-", "--box-shadow"],
137
+ notColour: ["--shadow", "--tw-", "--sc-", "--scootch-"],
138
+ internal: ["--tw-"],
139
+ };
140
+ if (cfg.tokens) for (var g in cfg.tokens) PREFIX[g] = cfg.tokens[g];
141
+ var TYPE_CLASS = /^(text|type|font|t)-[a-z0-9-]+$/;
142
+ var TYPE_PROPS = ["font-family", "font-size", "line-height", "font-weight", "letter-spacing"];
143
+ function starts(name, list) {
144
+ for (var i = 0; i < list.length; i++) if (name === list[i] || name.indexOf(list[i]) === 0) return true;
145
+ return false;
146
+ }
147
+ function eachRule(fn) {
148
+ var walk = function (rules) {
149
+ for (var i = 0; i < rules.length; i++) {
150
+ fn(rules[i]);
151
+ if (rules[i].cssRules && rules[i].cssRules.length) walk(rules[i].cssRules);
152
+ }
153
+ };
154
+ for (var i = 0; i < document.styleSheets.length; i++) {
155
+ var rules = null;
156
+ try {
157
+ rules = document.styleSheets[i].cssRules;
158
+ } catch (e) {
159
+ continue; // another origin's sheet (a web font's): nothing to read
160
+ }
161
+ if (rules) walk(rules);
162
+ }
163
+ }
164
+ var root = function () {
165
+ return getComputedStyle(document.documentElement);
166
+ };
167
+ var probe = null;
168
+ function measure(name) {
169
+ if (!probe) {
170
+ probe = document.createElement("div");
171
+ probe.setAttribute("aria-hidden", "true");
172
+ probe.style.cssText = "position:absolute;visibility:hidden;pointer-events:none;height:0;";
173
+ }
174
+ if (!probe.isConnected) document.documentElement.appendChild(probe);
175
+ probe.style.width = "0px";
176
+ probe.style.width = "var(" + name + ")";
177
+ var w = parseFloat(getComputedStyle(probe).width);
178
+ return isFinite(w) && probe.style.width ? w : null;
179
+ }
180
+ function pxOf(v, name) {
181
+ var s = (v || "").trim();
182
+ if (!s) return null;
183
+ var n = parseFloat(s);
184
+ if (/^-?[\d.]+px$/.test(s)) return n;
185
+ if (/^-?[\d.]+r?em$/.test(s)) return n * parseFloat(root().fontSize);
186
+ if (s === "0") return 0;
187
+ if (name && /(calc|min|max|clamp|var)\(/.test(s)) return measure(name);
188
+ return null;
189
+ }
190
+ var tokenCache = null;
191
+ function tokens() {
192
+ if (tokenCache) return tokenCache;
193
+ var names = {};
194
+ var classes = {};
195
+ eachRule(function (r) {
196
+ var s = r.style;
197
+ if (s) for (var i = 0; i < s.length; i++) if (s[i].indexOf("--") === 0 && !starts(s[i], PREFIX.internal)) names[s[i]] = 1;
198
+ if (r.selectorText && s && (s.font || s.fontSize || s.fontFamily)) {
199
+ // Which type values the class itself sets: those, and only those, are written out when it is detached.
200
+ var sets = TYPE_PROPS.filter(function (p) {
201
+ return s.font || s.getPropertyValue(p);
202
+ });
203
+ r.selectorText.split(",").forEach(function (sel) {
204
+ var m = sel.trim().match(/^\.([a-zA-Z0-9_-]+)$/);
205
+ if (m && TYPE_CLASS.test(m[1])) classes[m[1]] = (classes[m[1]] || []).concat(sets);
206
+ });
207
+ }
208
+ });
209
+ var all = Object.keys(names);
210
+ var rs = root();
211
+ var px = function (group) {
212
+ return all
213
+ .filter(function (n) {
214
+ return starts(n, PREFIX[group]);
215
+ })
216
+ .map(function (n) {
217
+ return { name: n, px: pxOf(rs.getPropertyValue(n), n) };
218
+ })
219
+ .filter(function (t) {
220
+ return t.px !== null && t.px >= 0;
221
+ })
222
+ .sort(function (a, b) {
223
+ return a.px - b.px;
224
+ });
225
+ };
226
+ var val = function (group) {
227
+ return all
228
+ .filter(function (n) {
229
+ return starts(n, PREFIX[group]);
230
+ })
231
+ .map(function (n) {
232
+ return { name: n, value: rs.getPropertyValue(n).trim() };
233
+ })
234
+ .filter(function (t) {
235
+ return t.value;
236
+ });
237
+ };
238
+ // Colours: any token whose value is one, resolved to rgb() for matching a computed colour.
239
+ var cp = document.createElement("div");
240
+ cp.style.display = "none";
241
+ document.documentElement.appendChild(cp);
242
+ var colour = all
243
+ .filter(function (n) {
244
+ if (starts(n, PREFIX.notColour)) return false;
245
+ var v = rs.getPropertyValue(n).trim();
246
+ return v && !/^-?[\d.]/.test(v) && CSS.supports("color", v);
247
+ })
248
+ .map(function (n) {
249
+ cp.style.color = "";
250
+ cp.style.color = "var(" + n + ")";
251
+ return { name: n, value: getComputedStyle(cp).color };
252
+ })
253
+ .sort(function (a, b) {
254
+ return a.name.localeCompare(b.name, undefined, { numeric: true });
255
+ });
256
+ // Type styles: each class measured on a probe, so its values follow the live CSS.
257
+ var tp = document.createElement("span");
258
+ tp.style.cssText = "position:absolute;visibility:hidden";
259
+ tp.textContent = "x";
260
+ document.body && document.body.appendChild(tp);
261
+ var types = Object.keys(classes).map(function (cls) {
262
+ tp.className = cls;
263
+ var c = getComputedStyle(tp);
264
+ return {
265
+ name: cls,
266
+ sets: classes[cls],
267
+ fontSize: c.fontSize,
268
+ lineHeight: c.lineHeight,
269
+ fontWeight: c.fontWeight,
270
+ letterSpacing: c.letterSpacing,
271
+ fontFamily: c.fontFamily,
272
+ };
273
+ });
274
+ tp.remove();
275
+ var GENERIC = /(^|,\s*)(serif|sans-serif|monospace|cursive|fantasy|system-ui|ui-serif|ui-sans-serif|ui-monospace|ui-rounded)\s*(,|$)/;
276
+ var font = all
277
+ .map(function (n) {
278
+ return { name: n, value: rs.getPropertyValue(n).trim() };
279
+ })
280
+ .filter(function (t) {
281
+ return t.value && !/^[\d.+-]/.test(t.value) && (/["',]/.test(t.value) || GENERIC.test(t.value)) && CSS.supports("font-family", t.value);
282
+ });
283
+ var fonts = {};
284
+ try {
285
+ document.fonts.forEach(function (f) {
286
+ fonts[firstFamily(f.family)] = 1;
287
+ });
288
+ } catch (e) {}
289
+ cp.remove();
290
+ tokenCache = {
291
+ space: px("space"),
292
+ fontSize: px("fontSize"),
293
+ lineHeight: px("lineHeight"),
294
+ radius: px("radius"),
295
+ borderWidth: px("borderWidth"),
296
+ weight: val("weight"),
297
+ tracking: val("tracking"),
298
+ colour: colour,
299
+ font: font,
300
+ shadow: val("shadow"),
301
+ fonts: Object.keys(fonts).filter(Boolean).sort(),
302
+ types: types,
303
+ };
304
+ return tokenCache;
305
+ }
306
+ function firstFamily(stack) {
307
+ return (stack || "").split(",")[0].trim().replace(/^["']|["']$/g, "");
308
+ }
309
+
310
+ /* ---------------------------------------------------------------- the cascade (after Scootch's inspect.js) */
311
+ function splitList(value) {
312
+ var parts = [];
313
+ var depth = 0;
314
+ var cur = "";
315
+ for (var i = 0; i < value.length; i++) {
316
+ var ch = value[i];
317
+ if (ch === "(" || ch === "[") depth++;
318
+ if (ch === ")" || ch === "]") depth--;
319
+ if (ch === "," && depth === 0) {
320
+ parts.push(cur.trim());
321
+ cur = "";
322
+ } else cur += ch;
323
+ }
324
+ if (cur.trim()) parts.push(cur.trim());
325
+ return parts;
326
+ }
327
+ function specificity(s) {
328
+ var out = [0, 0, 0];
329
+ var i = 0;
330
+ var ident = function () {
331
+ var m = s.slice(i).match(/^(?:\\.|[\w-]|[^\x00-\x7f])+/);
332
+ i += m ? m[0].length : 1;
333
+ return m ? m[0] : "";
334
+ };
335
+ var inside = function (open, close) {
336
+ var depth = 0;
337
+ var from = i + 1;
338
+ for (; i < s.length; i++) {
339
+ if (s[i] === open) depth++;
340
+ else if (s[i] === close && --depth === 0) break;
341
+ }
342
+ return s.slice(from, i++);
343
+ };
344
+ var compoundStart = true;
345
+ while (i < s.length) {
346
+ var ch = s[i];
347
+ if (ch === "#") (i++, ident(), out[0]++);
348
+ else if (ch === ".") (i++, ident(), out[1]++);
349
+ else if (ch === "[") (inside("[", "]"), out[1]++);
350
+ else if (ch === ":") {
351
+ var element = s[i + 1] === ":";
352
+ i += element ? 2 : 1;
353
+ var name = ident().toLowerCase();
354
+ var args = s[i] === "(" ? inside("(", ")") : null;
355
+ if (element || /^(before|after|first-line|first-letter)$/.test(name)) out[2]++;
356
+ else if (name === "where") {
357
+ // counts for nothing
358
+ } else if (/^(is|not|has|matches)$/.test(name) && args !== null) {
359
+ var best = splitList(args).map(specificity).sort(cmpSpec).pop();
360
+ if (best) best.forEach(function (n, k) {
361
+ out[k] += n;
362
+ });
363
+ } else out[1]++;
364
+ } else if (/[\s>+~]/.test(ch)) {
365
+ i++;
366
+ compoundStart = true;
367
+ continue;
368
+ } else if (ch === "*" || ch === "&" || ch === "|") i++;
369
+ else if (compoundStart) (ident(), out[2]++);
370
+ else i++;
371
+ compoundStart = false;
372
+ }
373
+ return out;
374
+ }
375
+ function cmpSpec(a, b) {
376
+ return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
377
+ }
378
+ var ruleCache = null;
379
+ var sheetCount = -1;
380
+ function collect(list, out, layer, parent) {
381
+ for (var i = 0; i < list.length; i++) {
382
+ var rule = list[i];
383
+ if (rule.selectorText !== undefined && rule.style) {
384
+ var sel = parent
385
+ ? splitList(rule.selectorText)
386
+ .map(function (p) {
387
+ return p.indexOf("&") >= 0 ? p.split("&").join(":is(" + parent + ")") : ":is(" + parent + ") " + p;
388
+ })
389
+ .join(", ")
390
+ : rule.selectorText;
391
+ out.push({
392
+ style: rule.style,
393
+ layer: layer,
394
+ parts: splitList(sel).map(function (x) {
395
+ return { sel: x, spec: specificity(x) };
396
+ }),
397
+ });
398
+ if (rule.cssRules && rule.cssRules.length) collect(rule.cssRules, out, layer, sel);
399
+ } else if (rule.cssRules) {
400
+ if (rule.media && rule.conditionText && !window.matchMedia(rule.conditionText).matches) continue;
401
+ if (rule.constructor && rule.constructor.name === "CSSSupportsRule" && !CSS.supports(rule.conditionText)) continue;
402
+ // A layer counts as later than none, in the order layers come; enough to rank the rules a page's own CSS has.
403
+ collect(rule.cssRules, out, rule.constructor && rule.constructor.name === "CSSLayerBlockRule" ? layer + 1 : layer, parent);
404
+ }
405
+ }
406
+ }
407
+ function allRules() {
408
+ if (ruleCache && document.styleSheets.length === sheetCount) return ruleCache;
409
+ var out = [];
410
+ for (var i = 0; i < document.styleSheets.length; i++) {
411
+ try {
412
+ collect(document.styleSheets[i].cssRules, out, 0, null);
413
+ } catch (e) {}
414
+ }
415
+ out.forEach(function (r, n) {
416
+ r.order = n;
417
+ });
418
+ ruleCache = out;
419
+ sheetCount = document.styleSheets.length;
420
+ return out;
421
+ }
422
+ // The rules that match an element depend only on its classes and attributes and the sheets: kept per element.
423
+ var matchCache = new WeakMap();
424
+ function matched(el) {
425
+ var sig = sheetCount + "|" + el.getAttribute("class") + "|" + el.attributes.length;
426
+ var hit = matchCache.get(el);
427
+ allRules();
428
+ if (hit && hit.sig === sheetCount + "|" + el.getAttribute("class") + "|" + el.attributes.length) return hit.rules;
429
+ var rules = [];
430
+ allRules().forEach(function (rule) {
431
+ var spec = null;
432
+ rule.parts.forEach(function (part) {
433
+ try {
434
+ if (el.matches(part.sel) && (!spec || cmpSpec(part.spec, spec) > 0)) spec = part.spec;
435
+ } catch (e) {}
436
+ });
437
+ if (spec) rules.push({ style: rule.style, layer: rule.layer, spec: spec, order: rule.order });
438
+ });
439
+ // Layered rules lose to unlayered ones; then specificity, then source order.
440
+ rules.sort(function (a, b) {
441
+ return (a.layer === 0) - (b.layer === 0) || a.layer - b.layer || cmpSpec(a.spec, b.spec) || a.order - b.order;
442
+ });
443
+ matchCache.set(el, { sig: sig, rules: rules });
444
+ return rules;
445
+ }
446
+ function splitTop(value) {
447
+ var parts = [];
448
+ var depth = 0;
449
+ var cur = "";
450
+ var v = value.trim();
451
+ for (var i = 0; i < v.length; i++) {
452
+ var ch = v[i];
453
+ if (ch === "(") depth++;
454
+ if (ch === ")") depth--;
455
+ if (ch === " " && depth === 0) {
456
+ if (cur) parts.push(cur);
457
+ cur = "";
458
+ } else cur += ch;
459
+ }
460
+ if (cur) parts.push(cur);
461
+ return parts;
462
+ }
463
+ var BOX = { top: [0, 0, 0, 0], right: [0, 1, 1, 1], bottom: [0, 0, 2, 2], left: [0, 1, 1, 3] };
464
+ function pickSide(v, side) {
465
+ var p = splitTop(v);
466
+ return p[BOX[side][p.length - 1]] || v;
467
+ }
468
+ function pickPair(v, i) {
469
+ var p = splitTop(v);
470
+ return p[Math.min(i, p.length - 1)] || v;
471
+ }
472
+ var BSTYLE = /^(none|hidden|solid|dashed|dotted|double|groove|ridge|inset|outset)$/;
473
+ function isWidth(p) {
474
+ return /^(\d|\.|thin|medium|thick|calc\(|var\(--(border-width|space-|size-))/.test(p);
475
+ }
476
+ function pickBorder(v, part) {
477
+ var p = splitTop(v);
478
+ if (part === "style") return p.find(function (x) {
479
+ return BSTYLE.test(x);
480
+ }) || null;
481
+ if (part === "width") return p.find(isWidth) || null;
482
+ return p.find(function (x) {
483
+ return !BSTYLE.test(x) && !isWidth(x);
484
+ }) || null;
485
+ }
486
+ var CORNERS = ["top-left", "top-right", "bottom-right", "bottom-left"];
487
+ function sources(prop) {
488
+ var m = prop.match(/^(padding|margin)-(top|right|bottom|left)$/);
489
+ if (m) {
490
+ var axis = m[2] === "top" || m[2] === "bottom" ? "block" : "inline";
491
+ var idx = m[2] === "top" || m[2] === "left" ? 0 : 1;
492
+ return [
493
+ [prop, null],
494
+ [m[1] + "-" + axis + "-" + (idx === 0 ? "start" : "end"), null],
495
+ [m[1] + "-" + axis, function (v) {
496
+ return pickPair(v, idx);
497
+ }],
498
+ [m[1], function (v) {
499
+ return pickSide(v, m[2]);
500
+ }],
501
+ ];
502
+ }
503
+ m = prop.match(/^border-(top|right|bottom|left)-(width|style|color)$/);
504
+ if (m) {
505
+ var side = m[1];
506
+ var part = m[2];
507
+ return [
508
+ [prop, null],
509
+ ["border-" + part, function (v) {
510
+ return pickSide(v, side);
511
+ }],
512
+ ["border-" + side, function (v) {
513
+ return pickBorder(v, part);
514
+ }],
515
+ ["border", function (v) {
516
+ return pickBorder(v, part);
517
+ }],
518
+ ];
519
+ }
520
+ m = prop.match(/^border-(top-left|top-right|bottom-right|bottom-left)-radius$/);
521
+ if (m) {
522
+ var corner = CORNERS.indexOf(m[1]);
523
+ return [
524
+ [prop, null],
525
+ ["border-radius", function (v) {
526
+ var p = splitTop(v.split("/")[0]);
527
+ var at = [[0, 0, 0, 0], [0, 1, 0, 1], [0, 1, 2, 1], [0, 1, 2, 3]][p.length - 1] || [0, 0, 0, 0];
528
+ return p[at[corner]] || v;
529
+ }],
530
+ ];
531
+ }
532
+ if (prop === "background-color")
533
+ return [
534
+ [prop, null],
535
+ ["background", function (v) {
536
+ return splitTop(v).find(function (p) {
537
+ return !/^(url|linear|radial|conic|repeating)/.test(p);
538
+ }) || null;
539
+ }],
540
+ ];
541
+ if (prop === "flex-grow")
542
+ return [[prop, null], ["flex", function (v) {
543
+ if (v === "none") return "0";
544
+ if (v === "auto") return "1";
545
+ var first = splitTop(v)[0];
546
+ return /^[\d.]+$/.test(first) ? first : null;
547
+ }]];
548
+ m = prop.match(/^overflow-(x|y)$/);
549
+ if (m) {
550
+ var oi = m[1] === "x" ? 0 : 1;
551
+ return [[prop, null], ["overflow", function (v) {
552
+ return pickPair(v, oi);
553
+ }]];
554
+ }
555
+ if (prop === "text-decoration-line")
556
+ return [[prop, null], ["text-decoration", function (v) {
557
+ return splitTop(v).find(function (p) {
558
+ return /^(none|underline|overline|line-through)$/.test(p);
559
+ }) || null;
560
+ }]];
561
+ if (prop === "row-gap") return [[prop, null], ["gap", function (v) {
562
+ return pickPair(v, 0);
563
+ }]];
564
+ if (prop === "column-gap") return [[prop, null], ["gap", function (v) {
565
+ return pickPair(v, 1);
566
+ }]];
567
+ return [[prop, null]];
568
+ }
569
+ // The value this element's CSS writes for a property (inline, or the strongest matching rule), e.g.
570
+ // "var(--space-4)" or "12px"; null when nothing sets it directly.
571
+ function declared(el, prop) {
572
+ var srcs = sources(prop);
573
+ var read = function (style) {
574
+ for (var i = 0; i < srcs.length; i++) {
575
+ var v = style.getPropertyValue(srcs[i][0]);
576
+ if (v) return { value: srcs[i][1] ? srcs[i][1](v.trim()) : v.trim(), important: style.getPropertyPriority(srcs[i][0]) === "important" };
577
+ }
578
+ return null;
579
+ };
580
+ var inline = read(el.style);
581
+ if (inline && inline.important) return inline.value;
582
+ var found = null;
583
+ var forced = null;
584
+ matched(el).forEach(function (rule) {
585
+ var hit = read(rule.style);
586
+ if (!hit) return;
587
+ if (!hit.important) found = hit.value;
588
+ else forced = hit.value;
589
+ });
590
+ return forced || (inline && inline.value) || found;
591
+ }
592
+ function varsIn(d) {
593
+ var out = [];
594
+ var re = /var\(\s*(--[\w-]+)/g;
595
+ var m;
596
+ while (d && (m = re.exec(d))) if (!starts(m[1], PREFIX.internal)) out.push(m[1]);
597
+ return out;
598
+ }
599
+ // How a value stands against the page's tokens: token (written with one), match (a raw value equal to one), rogue
600
+ // (no token), custom (a variable that isn't one of the listed tokens), none (not set).
601
+ // Tailwind's spacing: one base token (--spacing) whose multiples are the scale (p-4 is calc(var(--spacing) * 4)), so
602
+ // a multiple of it counts as on the scale and a drag catches on its steps.
603
+ var STEPS = [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 72, 80, 96];
604
+ function baseStep(list) {
605
+ return list.find(function (t) {
606
+ return t.name === "--spacing" && t.px > 0;
607
+ }) || null;
608
+ }
609
+ function pxStatus(d, px, list) {
610
+ var vars = varsIn(d);
611
+ if (vars.length) {
612
+ var hit = vars.find(function (n) {
613
+ return list.some(function (t) {
614
+ return t.name === n;
615
+ });
616
+ });
617
+ return hit ? { kind: "token", token: hit } : { kind: "custom", token: vars[0] };
618
+ }
619
+ if (!px && !d) return { kind: "none" };
620
+ // Against no tokens at all, a value is neither a match nor rogue: it is just set. Nor is nothing (0) ever rogue.
621
+ if (!list.length || px === 0) return { kind: d ? "set" : "none" };
622
+ if (px === null) return { kind: "rogue" };
623
+ var m = list.find(function (t) {
624
+ return Math.abs(t.px - px) < 0.01;
625
+ });
626
+ if (m) return { kind: "match", token: m.name };
627
+ var b = baseStep(list);
628
+ var k = b ? px / b.px : 0;
629
+ if (b && k > 0 && Math.abs(k * 2 - Math.round(k * 2)) < 0.001) return { kind: "match", token: b.name, times: Math.round(k * 2) / 2 };
630
+ return { kind: "rogue" };
631
+ }
632
+ function valueStatus(d, value, list, same) {
633
+ var vars = varsIn(d);
634
+ if (vars.length) {
635
+ var hit = vars.find(function (n) {
636
+ return list.some(function (t) {
637
+ return t.name === n;
638
+ });
639
+ });
640
+ return hit ? { kind: "token", token: hit } : { kind: "custom", token: vars[0] };
641
+ }
642
+ if (!d) return { kind: "none" };
643
+ if (!list.length) return { kind: "set" };
644
+ var m = list.find(function (t) {
645
+ return same(t.value, value);
646
+ });
647
+ return m ? { kind: "match", token: m.name } : { kind: "rogue" };
648
+ }
649
+
650
+ /* ---------------------------------------------------------------- reading an element */
651
+ var GROUPS = {
652
+ spacing: ["margin-top", "margin-right", "margin-bottom", "margin-left", "padding-top", "padding-right", "padding-bottom", "padding-left"],
653
+ size: ["width", "height", "min-width", "max-width", "min-height", "max-height"],
654
+ layout: ["display", "flex-direction", "flex-wrap", "justify-content", "align-items", "row-gap", "column-gap", "grid-template-columns"],
655
+ type: ["font-family", "font-size", "line-height", "font-weight", "letter-spacing", "text-transform", "text-align", "color", "font-style", "text-decoration-line"],
656
+ fill: ["background-color", "fill", "opacity"],
657
+ // Where it sits, and how it takes its size, in its parent (Figma's position, and fixed, hug or fill).
658
+ place: ["position", "top", "left", "right", "bottom", "rotate", "translate", "align-self", "justify-self", "flex-grow"],
659
+ look: ["visibility", "mix-blend-mode", "overflow-x", "overflow-y", "box-shadow", "filter", "backdrop-filter"],
660
+ border: [
661
+ "border-top-width",
662
+ "border-right-width",
663
+ "border-bottom-width",
664
+ "border-left-width",
665
+ "border-top-style",
666
+ "border-right-style",
667
+ "border-bottom-style",
668
+ "border-left-style",
669
+ "border-top-color",
670
+ "border-right-color",
671
+ "border-bottom-color",
672
+ "border-left-color",
673
+ "border-top-left-radius",
674
+ "border-top-right-radius",
675
+ "border-bottom-right-radius",
676
+ "border-bottom-left-radius",
677
+ ],
678
+ };
679
+ var COLOUR = { color: 1, "background-color": 1, fill: 1, "border-top-color": 1, "border-right-color": 1, "border-bottom-color": 1, "border-left-color": 1 };
680
+ function groupOf(prop) {
681
+ if (/^(margin|padding)-|gap$/.test(prop) || /^(min-|max-)?(width|height)$/.test(prop)) return "space";
682
+ if (prop === "font-size") return "fontSize";
683
+ if (prop === "line-height") return "lineHeight";
684
+ if (/radius$/.test(prop)) return "radius";
685
+ if (/^border-.*-width$/.test(prop)) return "borderWidth";
686
+ return null;
687
+ }
688
+ function sameColour(a, b) {
689
+ return a.replace(/\s/g, "") === b.replace(/\s/g, "");
690
+ }
691
+ function propInfo(el, cs, prop) {
692
+ var value = cs.getPropertyValue(prop).trim();
693
+ var d = declared(el, prop);
694
+ var T = tokens();
695
+ var st;
696
+ var group = groupOf(prop);
697
+ if (COLOUR[prop]) {
698
+ st = /^(transparent|rgba\(0, 0, 0, 0\))$/.test(value) && !d ? { kind: "none" } : valueStatus(d || value, value, T.colour, sameColour);
699
+ if (!d && st.kind !== "none") st = valueStatus(value, value, T.colour, sameColour);
700
+ } else if (group) st = pxStatus(d, /px$/.test(value) ? parseFloat(value) : null, T[group]);
701
+ else if (prop === "font-weight") st = valueStatus(d, value, T.weight, function (a, b) {
702
+ return String(a) === String(b);
703
+ });
704
+ else if (prop === "letter-spacing") st = valueStatus(d, value, T.tracking, function (a, b) {
705
+ return a === b;
706
+ });
707
+ else if (prop === "font-family") st = valueStatus(d, value, T.font, function (a, b) {
708
+ return firstFamily(a) === firstFamily(b);
709
+ });
710
+ else if (prop === "box-shadow") st = value === "none" && !d ? { kind: "none" } : valueStatus(d, value, T.shadow, function () {
711
+ return false;
712
+ });
713
+ else st = { kind: d ? "set" : "none" };
714
+ var out = { value: value, declared: d, kind: st.kind, token: st.token || null, changed: changedProp(el, prop) };
715
+ if (st.times) out.times = st.times;
716
+ return out;
717
+ }
718
+ function changedProp(el, prop) {
719
+ var o = originals.get(el);
720
+ if (!o) return false;
721
+ return styleOf(o.style).getPropertyValue(prop) !== el.style.getPropertyValue(prop);
722
+ }
723
+ // React's useId ids (":r1:", "_r_12_") change from render to render: no use for finding an element again.
724
+ function stableId(el) {
725
+ return el.id && !/^(:r|_r_|«r)/.test(el.id) ? el.id : "";
726
+ }
727
+ function label(el) {
728
+ var tag = el.localName;
729
+ var cls = [].slice.call(el.classList).filter(function (c) {
730
+ return /^[a-z][\w-]*$/i.test(c);
731
+ }).slice(0, 2);
732
+ return (stableId(el) ? tag + "#" + el.id : tag) + (cls.length ? "." + cls.join(".") : "");
733
+ }
734
+ // A CSS path from the nearest id, as short as it can be and still point at this one element, so a note can say where
735
+ // it is (after Scootch's cssPath).
736
+ function cssPath(el) {
737
+ var parts = [];
738
+ var n = el;
739
+ while (n && n.nodeType === 1 && n !== document.body && parts.length < 12) {
740
+ if (stableId(n)) {
741
+ parts.unshift("#" + (window.CSS && CSS.escape ? CSS.escape(n.id) : n.id));
742
+ break;
743
+ }
744
+ var tag = n.localName;
745
+ var cls = [].slice.call(n.classList).filter(function (c) {
746
+ return /^[a-z][\w-]*$/i.test(c) && c.indexOf("__") < 0;
747
+ })[0];
748
+ var step = tag + (cls ? "." + cls : "");
749
+ var parent = n.parentElement;
750
+ if (parent) {
751
+ var same = [].filter.call(parent.children, function (c) {
752
+ return c.localName === tag && (!cls || c.classList.contains(cls));
753
+ });
754
+ if (same.length > 1) step += ":nth-of-type(" + ([].filter.call(parent.children, function (c) {
755
+ return c.localName === tag;
756
+ }).indexOf(n) + 1) + ")";
757
+ }
758
+ parts.unshift(step);
759
+ try {
760
+ if (document.querySelectorAll(parts.join(" > ")).length === 1) break;
761
+ } catch (e) {}
762
+ n = parent;
763
+ }
764
+ return parts.join(" > ");
765
+ }
766
+ // The React components around an element, nearest first, from React's own fiber (dev builds only): where to look in
767
+ // the code (after Scootch's componentPath).
768
+ var REACT_INTERNAL = /^(Inner|Outer|Fragment|Suspense|Provider|Consumer|LinkComponent|Segment|Router|Layout|Redirect|Error|NotFound|HTTPAccess|Loading|Scroll|RenderFromTemplate|Template|ClientPageRoot|ClientSegmentRoot|AppRouter|HotReload|Head|Server|Dev|Root|Metadata|Viewport|AppDev)|Boundary$/;
769
+ function components(el) {
770
+ var key = Object.keys(el).find(function (k) {
771
+ return k.indexOf("__reactFiber$") === 0;
772
+ });
773
+ var fiber = key ? el[key] : null;
774
+ var names = [];
775
+ while (fiber && names.length < 4) {
776
+ var t = fiber.type;
777
+ var name = typeof t === "function" ? t.displayName || t.name : null;
778
+ if (name && /^[A-Z]/.test(name) && !REACT_INTERNAL.test(name) && names[names.length - 1] !== name) names.push(name);
779
+ fiber = fiber.return;
780
+ }
781
+ return names;
782
+ }
783
+ function typeClassOf(el) {
784
+ var list = tokens().types;
785
+ for (var i = 0; i < list.length; i++) if (el.classList.contains(list[i].name)) return list[i].name;
786
+ return null;
787
+ }
788
+ function info(el) {
789
+ var cs = getComputedStyle(el);
790
+ var props = {};
791
+ for (var g in GROUPS) GROUPS[g].forEach(function (p) {
792
+ props[p] = propInfo(el, cs, p);
793
+ });
794
+ var crumbs = [];
795
+ for (var a = el.parentElement; a && a !== document.documentElement; a = a.parentElement) crumbs.unshift({ key: keyOf(a), label: label(a) });
796
+ var r = el.getBoundingClientRect();
797
+ var o = originals.get(el);
798
+ var par = el.parentElement;
799
+ var pcs = par && par !== document.documentElement ? getComputedStyle(par) : null;
800
+ var pr = par ? par.getBoundingClientRect() : { left: 0, top: 0 };
801
+ var out = /^(absolute|fixed)$/.test(cs.position) && "offsetLeft" in el;
802
+ var own = [].some.call(el.childNodes, function (n) {
803
+ return n.nodeType === 3 && n.textContent.trim();
804
+ });
805
+ return {
806
+ key: keyOf(el),
807
+ id: el.getAttribute("data-bo-e"),
808
+ label: label(el),
809
+ path: cssPath(el),
810
+ components: components(el),
811
+ tag: el.localName,
812
+ text: (el.innerText || el.textContent || "").trim().replace(/\s+/g, " ").slice(0, 60),
813
+ svg: el instanceof SVGElement,
814
+ crumbs: crumbs,
815
+ children: el.children.length,
816
+ typeClass: typeClassOf(el),
817
+ typeDetached: !!(o && o.cls !== el.getAttribute("class") && o.detached),
818
+ width: Math.round(r.width * 100) / 100,
819
+ height: Math.round(r.height * 100) / 100,
820
+ x: Math.round((out ? el.offsetLeft : r.left - pr.left) * 100) / 100,
821
+ y: Math.round((out ? el.offsetTop : r.top - pr.top) * 100) / 100,
822
+ parent: pcs
823
+ ? { display: pcs.display, direction: pcs.flexDirection, wrap: pcs.flexWrap, alignItems: pcs.alignItems, justifyItems: pcs.justifyItems }
824
+ : null,
825
+ ownText: own || /^(input|textarea)$/.test(el.localName),
826
+ textLayer: isTextLayer(el),
827
+ editing: S.editing === el,
828
+ props: props,
829
+ };
830
+ }
831
+
832
+ /* ---------------------------------------------------------------- changing it */
833
+ function setProp(el, prop, value) {
834
+ var o = remember(el);
835
+ if (!(prop in o.before)) o.before[prop] = getComputedStyle(el).getPropertyValue(prop).trim();
836
+ if (value === null || value === "") el.style.removeProperty(prop);
837
+ else el.style.setProperty(prop, value);
838
+ tidy(el);
839
+ }
840
+ // A style attribute emptied back to nothing goes, if the element had none.
841
+ function tidy(el) {
842
+ var o = originals.get(el);
843
+ if (o && !o.style && el.getAttribute("style") === "") el.removeAttribute("style");
844
+ }
845
+ function resetProps(el, props) {
846
+ var o = originals.get(el);
847
+ if (!o) return;
848
+ var was = styleOf(o.style);
849
+ props.forEach(function (p) {
850
+ var v = was.getPropertyValue(p);
851
+ if (v) el.style.setProperty(p, v, was.getPropertyPriority(p));
852
+ else el.style.removeProperty(p);
853
+ });
854
+ tidy(el);
855
+ if (!isChanged(el)) originals.delete(el);
856
+ }
857
+ function resetEl(el) {
858
+ var o = originals.get(el);
859
+ if (!o) return;
860
+ if (o.copyOf) {
861
+ el.remove();
862
+ originals.delete(el);
863
+ return;
864
+ }
865
+ if (o.content) restore(o.content);
866
+ if (o.style === null) el.removeAttribute("style");
867
+ else el.setAttribute("style", o.style);
868
+ if (o.cls === null) el.removeAttribute("class");
869
+ else el.setAttribute("class", o.cls);
870
+ originals.delete(el);
871
+ }
872
+ // Undo and redo, as in a design tool: each step is the style and class attributes of what it changed, as they were
873
+ // before. Steps of one kind on one element close together (a scrub, a field's arrows) are one step.
874
+ var past = [];
875
+ var future = [];
876
+ // A step's content, when it changes what is inside an element: "text" keeps every node and text inside it, "order"
877
+ // only the element's own children. Restoring puts the same nodes back, so a page's framework keeps its references.
878
+ function contentSnap(el, mode) {
879
+ var pairs = [[el, [].slice.call(el.childNodes)]];
880
+ var texts = [];
881
+ if (mode === "text") {
882
+ el.querySelectorAll("*").forEach(function (n) {
883
+ pairs.push([n, [].slice.call(n.childNodes)]);
884
+ });
885
+ var w = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
886
+ while (w.nextNode()) texts.push([w.currentNode, w.currentNode.nodeValue]);
887
+ }
888
+ return { pairs: pairs, texts: texts };
889
+ }
890
+ function restore(c) {
891
+ c.pairs.forEach(function (p) {
892
+ p[0].replaceChildren.apply(p[0], p[1]);
893
+ });
894
+ c.texts.forEach(function (t) {
895
+ t[0].nodeValue = t[1];
896
+ });
897
+ }
898
+ function snapshot(list, mode) {
899
+ return list.map(function (el) {
900
+ return { el: el, style: el.getAttribute("style"), cls: el.getAttribute("class"), content: mode ? contentSnap(el, mode) : null };
901
+ });
902
+ }
903
+ function record(list, tag, mode) {
904
+ var now = Date.now();
905
+ var last = past[past.length - 1];
906
+ var same = last && tag && last.tag === tag && now - last.at < 800 && last.items.length === list.length && last.items.every(function (it, i) {
907
+ return it.el === list[i];
908
+ });
909
+ if (same) last.at = now;
910
+ else {
911
+ past.push({ items: snapshot(list, mode), tag: tag || null, at: now, mode: mode || null, runs: mode === "text" ? JSON.stringify(runsOf(list[0], true)) : null });
912
+ if (past.length > 200) past.shift();
913
+ }
914
+ future = [];
915
+ }
916
+ function step(from, to) {
917
+ var e = from.pop();
918
+ if (!e) return;
919
+ if (S.editing) stopText();
920
+ to.push({ items: snapshot(e.items.map(function (it) {
921
+ return it.el;
922
+ }), e.mode), tag: null, at: 0, mode: e.mode });
923
+ e.items.forEach(function (it) {
924
+ // How it is before this step, content too, so a redo after an undo still shows as a change.
925
+ if (it.content) rememberContent(it.el, e.mode);
926
+ else remember(it.el);
927
+ if (it.content) restore(it.content);
928
+ if (it.style === null) it.el.removeAttribute("style");
929
+ else it.el.setAttribute("style", it.style);
930
+ if (it.cls === null) it.el.removeAttribute("class");
931
+ else it.el.setAttribute("class", it.cls);
932
+ if (!isChanged(it.el)) originals.delete(it.el);
933
+ });
934
+ if (e.mode) send({ type: "dom" });
935
+ reportChanges();
936
+ report();
937
+ }
938
+
939
+ /* ---------------------------------------------------------------- copies: ⌘D, ⌘C and ⌘V */
940
+ // A copy is the element cloned, without the file's numbers (it isn't in the file), marked as a copy of its source.
941
+ function notCopy(el) {
942
+ return !el.hasAttribute("data-bo-copy");
943
+ }
944
+ function refOf(el) {
945
+ var src = el.getAttribute("data-bo-copy");
946
+ return { id: el.getAttribute("data-bo-e"), path: cssPath(el), label: label(el), copy: src ? true : undefined };
947
+ }
948
+ function cloneOf(el) {
949
+ var c = el.cloneNode(true);
950
+ var src = el.getAttribute("data-bo-e") || el.getAttribute("data-bo-copy") || "";
951
+ [c].concat([].slice.call(c.querySelectorAll("[data-bo-e]"))).forEach(function (n) {
952
+ n.removeAttribute("data-bo-e");
953
+ });
954
+ c.setAttribute("data-bo-copy", src);
955
+ if (c.id) c.removeAttribute("id");
956
+ return c;
957
+ }
958
+ var clip = [];
959
+ // Each into the page after where it goes, as Figma pastes: the copies are picked after.
960
+ function addCopies(sources, after) {
961
+ var made = [];
962
+ var parents = [];
963
+ sources.forEach(function (src, i) {
964
+ var at = after ? after[i] || after[after.length - 1] : src;
965
+ if (!at || !at.isConnected || !at.parentElement || at === document.body) return;
966
+ if (parents.indexOf(at.parentElement) < 0) parents.push(at.parentElement);
967
+ });
968
+ if (!parents.length) return;
969
+ record(parents, null, "order");
970
+ sources.forEach(function (src, i) {
971
+ var at = after ? after[i] || after[after.length - 1] : src;
972
+ if (!at || !at.isConnected || !at.parentElement || at === document.body) return;
973
+ var c = cloneOf(src);
974
+ at.parentElement.insertBefore(c, at.nextSibling);
975
+ originals.set(c, { style: c.getAttribute("style"), cls: c.getAttribute("class"), before: {}, copyOf: src });
976
+ made.push(c);
977
+ });
978
+ parents.forEach(sendChildren);
979
+ if (made.length) {
980
+ select(made[0], false);
981
+ S.extra = made.slice(1);
982
+ }
983
+ reportChanges();
984
+ report();
985
+ }
986
+ function duplicate() {
987
+ var list = picked();
988
+ if (list.length) addCopies(list, null);
989
+ }
990
+ function copySel() {
991
+ clip = picked();
992
+ }
993
+ function paste() {
994
+ var list = clip.filter(function (x) {
995
+ return x.isConnected;
996
+ });
997
+ if (!list.length) return;
998
+ var at = picked();
999
+ addCopies(list, at.length ? [at[at.length - 1]] : null);
1000
+ }
1001
+
1002
+ /* ---------------------------------------------------------------- content: text, order, deletion */
1003
+ // An element's content as the file gets it back (protocol.ts Run): its text, its <br>s and its numbered elements;
1004
+ // what the page's script made isn't in the file, so it is left out.
1005
+ function runsOf(el, deep) {
1006
+ var out = [];
1007
+ el.childNodes.forEach(function (n) {
1008
+ if (n.nodeType === 3) {
1009
+ if (n.nodeValue) out.push(n.nodeValue);
1010
+ } else if (n.nodeType === 1) {
1011
+ if (n.localName === "br") return out.push({ br: 1 });
1012
+ var mk = n.getAttribute("data-bo-mark");
1013
+ if (mk && MARK_TAG[mk]) return out.push({ mark: mk, runs: runsOf(n, deep) });
1014
+ var id = n.getAttribute("data-bo-e");
1015
+ if (id && !isRemoved(n)) out.push(deep ? { el: id, runs: runsOf(n, true) } : { el: id });
1016
+ }
1017
+ });
1018
+ return out;
1019
+ }
1020
+ // Part of a text bold, italic or underlined, as Figma styles a range: wrapped in its own element, marked as the
1021
+ // editor's (it isn't in the file). Again on a marked part, the mark comes off.
1022
+ var MARK_TAG = { b: "strong", i: "em", u: "u" };
1023
+ function unwrap(n) {
1024
+ while (n.firstChild) n.parentNode.insertBefore(n.firstChild, n);
1025
+ n.remove();
1026
+ }
1027
+ function markText(kind) {
1028
+ var el = S.editing;
1029
+ var sel = window.getSelection();
1030
+ if (!el || !sel || !sel.rangeCount) return;
1031
+ var r = sel.getRangeAt(0);
1032
+ if (r.collapsed || !el.contains(r.commonAncestorContainer)) return;
1033
+ var at = r.commonAncestorContainer.nodeType === 3 ? r.commonAncestorContainer.parentElement : r.commonAncestorContainer;
1034
+ var on = at.closest('[data-bo-mark="' + kind + '"]');
1035
+ if (on && el.contains(on)) {
1036
+ unwrap(on);
1037
+ el.normalize();
1038
+ return reportChanges();
1039
+ }
1040
+ // Only across the text itself and the editor's own marks: cutting through the file's elements would copy them.
1041
+ var ends = [r.startContainer, r.endContainer].map(function (n) {
1042
+ return n.nodeType === 3 ? n.parentElement : n;
1043
+ });
1044
+ var plain = ends.every(function (n) {
1045
+ for (; n && n !== el; n = n.parentElement) if (!n.hasAttribute("data-bo-mark")) return false;
1046
+ return true;
1047
+ });
1048
+ if (!plain) return;
1049
+ var w = document.createElement(MARK_TAG[kind]);
1050
+ w.setAttribute("data-bo-mark", kind);
1051
+ w.appendChild(r.extractContents());
1052
+ w.querySelectorAll('[data-bo-mark="' + kind + '"]').forEach(unwrap);
1053
+ r.insertNode(w);
1054
+ var nr = document.createRange();
1055
+ nr.selectNodeContents(w);
1056
+ sel.removeAllRanges();
1057
+ sel.addRange(nr);
1058
+ reportChanges();
1059
+ }
1060
+ function textOf(el) {
1061
+ return (el.innerText || el.textContent || "").trim().replace(/\s+/g, " ").slice(0, 500);
1062
+ }
1063
+ // Before its content first changes: how it was, to show, compare and reset.
1064
+ function rememberContent(el, mode) {
1065
+ var o = remember(el);
1066
+ if (!o.content) {
1067
+ o.content = contentSnap(el, "text");
1068
+ o.runs = JSON.stringify(runsOf(el, true));
1069
+ o.kids = [].slice.call(el.children);
1070
+ o.textWas = textOf(el);
1071
+ }
1072
+ if (mode === "text" || !o.mode) o.mode = mode;
1073
+ return o;
1074
+ }
1075
+ function contentChanged(el, o) {
1076
+ if (!o || !o.content) return false;
1077
+ if (JSON.stringify(runsOf(el, true)) !== o.runs) return true;
1078
+ var kids = [].slice.call(el.children).filter(notCopy);
1079
+ var was = o.kids.filter(notCopy);
1080
+ return kids.length !== was.length || kids.some(function (k, i) {
1081
+ return k !== was[i];
1082
+ });
1083
+ }
1084
+ // Deleted, as Figma deletes: gone from the page, kept in it (hidden) so undo and the page's framework still have it.
1085
+ function isRemoved(el) {
1086
+ var o = originals.get(el);
1087
+ return !!(o && o.removed && el.style.getPropertyValue("display") === "none" && el.style.getPropertyPriority("display") === "important");
1088
+ }
1089
+ function removeEls(list) {
1090
+ if (!list.length) return;
1091
+ record(list, null);
1092
+ list.forEach(function (el) {
1093
+ var o = remember(el);
1094
+ if (!("display" in o.before)) o.before.display = getComputedStyle(el).display;
1095
+ o.removed = true;
1096
+ el.style.setProperty("display", "none", "important");
1097
+ });
1098
+ select(null);
1099
+ reportChanges();
1100
+ list.forEach(function (el) {
1101
+ if (el.parentElement) sendChildren(el.parentElement);
1102
+ });
1103
+ }
1104
+ function sendChildren(el) {
1105
+ send({ type: "children", key: el === document.body ? null : keyOf(el), nodes: layerKids(el).slice(0, 400).map(layerOf) });
1106
+ }
1107
+ // Out of the layout where it is now, as Figma's absolute position: the same place and size, set as left and top in
1108
+ // its containing block. Back in, it is relative, so what is absolute inside it stays where it was.
1109
+ function setAbsolute(el, on) {
1110
+ if (!on) {
1111
+ setProp(el, "position", "relative");
1112
+ ["left", "top", "right", "bottom"].forEach(function (p) {
1113
+ setProp(el, p, null);
1114
+ });
1115
+ return;
1116
+ }
1117
+ var r = el.getBoundingClientRect();
1118
+ setProp(el, "position", "absolute");
1119
+ setProp(el, "right", "auto");
1120
+ setProp(el, "bottom", "auto");
1121
+ setProp(el, "left", "0px");
1122
+ setProp(el, "top", "0px");
1123
+ var at = el.getBoundingClientRect();
1124
+ var left = Math.round((r.left - at.left) * 100) / 100;
1125
+ var top = Math.round((r.top - at.top) * 100) / 100;
1126
+ setProp(el, "left", left + "px");
1127
+ setProp(el, "top", top + "px");
1128
+ var now = el.getBoundingClientRect();
1129
+ if (Math.abs(now.width - r.width) > 0.5) setProp(el, "width", Math.round(r.width * 100) / 100 + "px");
1130
+ if (Math.abs(now.height - r.height) > 0.5) setProp(el, "height", Math.round(r.height * 100) / 100 + "px");
1131
+ }
1132
+ function norm(s) {
1133
+ return (s || "").replace(/\s+/g, " ").replace(/;\s*$/, "").trim();
1134
+ }
1135
+ function isChanged(el) {
1136
+ var o = originals.get(el);
1137
+ if (o && o.copyOf) return true;
1138
+ if (o && o.home && el.parentElement !== o.home) return true;
1139
+ return !!o && (norm(styleOf(o.style).cssText) !== norm(el.style.cssText) || (o.cls || "") !== (el.getAttribute("class") || "") || contentChanged(el, o));
1140
+ }
1141
+ function changes() {
1142
+ var out = [];
1143
+ originals.forEach(function (o, el) {
1144
+ if (!el.isConnected || !isChanged(el)) return;
1145
+ var was = styleOf(o.style);
1146
+ var props = [];
1147
+ var seen = {};
1148
+ for (var i = 0; i < el.style.length; i++) {
1149
+ var p = el.style[i];
1150
+ seen[p] = 1;
1151
+ var from = was.getPropertyValue(p);
1152
+ var to = el.style.getPropertyValue(p);
1153
+ if (from !== to) props.push({ prop: p, from: from || o.before[p] || null, to: to });
1154
+ }
1155
+ for (var j = 0; j < was.length; j++) if (!seen[was[j]]) props.push({ prop: was[j], from: was.getPropertyValue(was[j]), to: null });
1156
+ var cls = el.getAttribute("class");
1157
+ var moved = contentChanged(el, o);
1158
+ var now = moved ? textOf(el) : "";
1159
+ if (isRemoved(el)) props = [];
1160
+ if (o.copyOf) {
1161
+ // A copy is new: where it goes and what it is a copy of; deleted again, it isn't a change.
1162
+ if (isRemoved(el)) return;
1163
+ var prev = el.previousElementSibling;
1164
+ while (prev && (isRemoved(prev) || prev === host)) prev = prev.previousElementSibling;
1165
+ out.push({
1166
+ key: keyOf(el),
1167
+ id: null,
1168
+ label: label(el),
1169
+ path: cssPath(el),
1170
+ components: components(el),
1171
+ props: props,
1172
+ style: el.getAttribute("style"),
1173
+ copyOf: refOf(o.copyOf),
1174
+ after: prev ? refOf(prev) : null,
1175
+ parent: refOf(el.parentElement),
1176
+ });
1177
+ return;
1178
+ }
1179
+ var away = o.home && el.parentElement !== o.home;
1180
+ var prevEl = null;
1181
+ if (away) {
1182
+ prevEl = el.previousElementSibling;
1183
+ while (prevEl && (isRemoved(prevEl) || prevEl === host)) prevEl = prevEl.previousElementSibling;
1184
+ }
1185
+ out.push({
1186
+ movedFrom: away ? refOf(o.home) : undefined,
1187
+ parent: away ? refOf(el.parentElement) : undefined,
1188
+ after: away ? (prevEl ? refOf(prevEl) : null) : undefined,
1189
+ content: moved ? runsOf(el, o.mode === "text") : undefined,
1190
+ // Its text, when that was edited: children only moved in or out don't change it.
1191
+ text: moved && o.mode === "text" && now !== o.textWas ? { from: o.textWas, to: now } : undefined,
1192
+ removed: isRemoved(el) || undefined,
1193
+ key: keyOf(el),
1194
+ id: el.getAttribute("data-bo-e"),
1195
+ label: label(el),
1196
+ path: cssPath(el),
1197
+ components: components(el),
1198
+ props: props,
1199
+ style: el.getAttribute("style"),
1200
+ cls: (o.cls || "") !== (cls || "") ? cls : undefined,
1201
+ clsWas: (o.cls || "") !== (cls || "") ? o.cls : undefined,
1202
+ });
1203
+ });
1204
+ return out;
1205
+ }
1206
+ // A type style's values written onto the element, and the class taken off, so each can be changed on its own.
1207
+ function detach(el) {
1208
+ var tc = typeClassOf(el);
1209
+ if (!tc) return;
1210
+ var o = remember(el);
1211
+ var cs = getComputedStyle(el);
1212
+ var t = tokens().types.find(function (x) {
1213
+ return x.name === tc;
1214
+ });
1215
+ (t && t.sets && t.sets.length ? t.sets : TYPE_PROPS).forEach(function (p) {
1216
+ if (!(p in o.before)) o.before[p] = cs.getPropertyValue(p).trim();
1217
+ el.style.setProperty(p, cs.getPropertyValue(p));
1218
+ });
1219
+ el.classList.remove(tc);
1220
+ o.detached = true;
1221
+ }
1222
+ // A type style put on: the element's other type classes and its own type values give way to it.
1223
+ function applyType(el, name) {
1224
+ var o = remember(el);
1225
+ tokens().types.forEach(function (t) {
1226
+ el.classList.remove(t.name);
1227
+ });
1228
+ if (name) el.classList.add(name);
1229
+ TYPE_PROPS.forEach(function (p) {
1230
+ if (!styleOf(o.style).getPropertyValue(p)) el.style.removeProperty(p);
1231
+ });
1232
+ o.detached = false;
1233
+ tidy(el);
1234
+ }
1235
+
1236
+ /* ---------------------------------------------------------------- drawing in the page */
1237
+ var host = document.createElement("blockout-editor");
1238
+ // Under a project kit's docked panels (2147483646), so what is picked never covers them or takes their clicks.
1239
+ host.style.cssText = "position:fixed;inset:0;z-index:2147483645;pointer-events:none;display:block;margin:0;padding:0;border:0;background:none";
1240
+ var shadow = host.attachShadow({ mode: "closed" });
1241
+ var css = document.createElement("style");
1242
+ css.textContent =
1243
+ ":host{all:initial}" +
1244
+ ".box{position:absolute;left:0;top:0;box-sizing:border-box;pointer-events:none}" +
1245
+ ".hover{outline:1px solid " + ACCENT + ";outline-offset:-1px}" +
1246
+ ".sel{outline:1.5px solid " + ACCENT + ";outline-offset:-1.5px;box-shadow:0 0 0 1px rgba(255,255,255,.85)}" +
1247
+ ".tag{position:absolute;left:0;top:0;padding:2px 6px;border-radius:6px;background:" + INK + ";color:#fff;white-space:nowrap;" +
1248
+ "font:500 11px/16px ui-sans-serif,system-ui,sans-serif;letter-spacing:0;pointer-events:none;font-variant-numeric:tabular-nums}" +
1249
+ ".tag.accent{background:" + ACCENT + "}" +
1250
+ ".band{position:absolute;left:0;top:0;pointer-events:auto;box-sizing:border-box}" +
1251
+ ".band.m{background:rgba(255,77,46,.14)}.band.p{background:rgba(101,163,13,.16)}" +
1252
+ ".band.g{background:repeating-linear-gradient(45deg,rgba(255,77,46,.32) 0 1.5px,transparent 1.5px 6px)}" +
1253
+ ".band.zero{background:none}" +
1254
+ ".band:hover,.band.live{outline:1px dashed " + ACCENT + ";outline-offset:-1px}" +
1255
+ ".band.m:hover,.band.m.live{background:rgba(255,77,46,.26)}.band.p:hover,.band.p.live{background:rgba(101,163,13,.3)}" +
1256
+ ".y{cursor:ns-resize}.x{cursor:ew-resize}" +
1257
+ "canvas{position:absolute;left:0;top:0;pointer-events:auto}" +
1258
+ ".corner{position:absolute;left:0;top:0;width:" + RS + "px;height:" + RS + "px;background:#fff;pointer-events:auto;cursor:default;" +
1259
+ "box-shadow:inset -1px -1px 0 rgba(16,16,16,.14)}" +
1260
+ ".guide{position:absolute;left:0;top:0;pointer-events:auto}" +
1261
+ ".guide i{position:absolute;background:" + ACCENT + "}" +
1262
+ ".guide.v{width:7px;margin-left:-3px;height:100%;cursor:col-resize}.guide.v i{left:3px;top:0;bottom:0;width:1px}" +
1263
+ ".guide.h{height:7px;margin-top:-3px;width:100%;cursor:row-resize}.guide.h i{top:3px;left:0;right:0;height:1px}" +
1264
+ ".sel.text{outline-width:1px;box-shadow:none}" +
1265
+ ".handle{position:absolute;left:0;top:0;width:8px;height:8px;margin:-4px 0 0 -4px;box-sizing:border-box;background:#fff;border:1.5px solid " + ACCENT + ";border-radius:2px;pointer-events:auto}" +
1266
+ ".drop{position:absolute;left:0;top:0;background:" + ACCENT + ";border-radius:1px;box-shadow:0 0 0 1px #fff}" +
1267
+ ".ml{position:absolute;left:0;top:0;background:" + MEASURE + "}" +
1268
+ ".mbox{position:absolute;left:0;top:0;box-sizing:border-box;outline:1px dashed " + MEASURE + ";outline-offset:-1px}" +
1269
+ ".mtag{position:absolute;left:0;top:0;padding:1px 5px;border-radius:4px;background:" + MEASURE + ";color:#fff;white-space:nowrap;" +
1270
+ "font:600 11px/16px ui-sans-serif,system-ui,sans-serif;font-variant-numeric:tabular-nums}";
1271
+ shadow.appendChild(css);
1272
+ var layer = document.createElement("div");
1273
+ shadow.appendChild(layer);
1274
+ function div(cls) {
1275
+ var d = document.createElement("div");
1276
+ d.className = cls;
1277
+ return d;
1278
+ }
1279
+ var hoverBox = div("box hover");
1280
+ var hoverTag = div("tag");
1281
+ var selBox = div("box sel");
1282
+ var selTag = div("tag accent");
1283
+ var bandLayer = div("box");
1284
+ var tip = div("tag");
1285
+ var guideLayer = div("box");
1286
+ var topRuler = document.createElement("canvas");
1287
+ var leftRuler = document.createElement("canvas");
1288
+ var corner = div("corner");
1289
+ var dropLine = div("drop");
1290
+ var othersLayer = div("box");
1291
+ var snapLayer = div("box");
1292
+ var intoBox = div("box sel");
1293
+ var bandTag = div("tag accent");
1294
+ var measureLayer = div("box");
1295
+ var HANDLES = ["nw", "n", "ne", "e", "se", "s", "sw", "w"];
1296
+ var handles = HANDLES.map(function (d) {
1297
+ var h = div("handle");
1298
+ h.style.cursor = d + "-resize";
1299
+ h.__dir = d;
1300
+ h.addEventListener("pointerdown", startResize);
1301
+ return h;
1302
+ });
1303
+ [bandLayer, hoverBox, hoverTag, selBox, selTag, othersLayer, intoBox, measureLayer, snapLayer, dropLine, bandTag].concat(handles, [guideLayer, topRuler, leftRuler, corner, tip]).forEach(function (n) {
1304
+ layer.appendChild(n);
1305
+ });
1306
+ function place(n, x, y, w, h) {
1307
+ n.style.transform = "translate(" + x + "px," + y + "px)";
1308
+ if (w !== undefined) {
1309
+ n.style.width = Math.max(0, w) + "px";
1310
+ n.style.height = Math.max(0, h) + "px";
1311
+ }
1312
+ }
1313
+ function show(n, on) {
1314
+ n.style.display = on ? "" : "none";
1315
+ }
1316
+ function mount() {
1317
+ if (!host.isConnected) document.documentElement.appendChild(host);
1318
+ }
1319
+ function ours(e) {
1320
+ var path = e.composedPath ? e.composedPath() : [];
1321
+ for (var i = 0; i < path.length; i++) {
1322
+ var n = path[i];
1323
+ if (n === host || (n && (n.localName === "blockout-pins" || (n.hasAttribute && n.hasAttribute("data-blockout-editor"))))) return true;
1324
+ }
1325
+ return false;
1326
+ }
1327
+
1328
+ // The margin, padding and gap bands of what is picked, each a handle to drag.
1329
+ var bands = [];
1330
+ function bandsFor(el) {
1331
+ var cs = getComputedStyle(el);
1332
+ var r = el.getBoundingClientRect();
1333
+ var n = function (p) {
1334
+ return parseFloat(cs.getPropertyValue(p)) || 0;
1335
+ };
1336
+ var mt = n("margin-top"), mr = n("margin-right"), mb = n("margin-bottom"), ml = n("margin-left");
1337
+ var pt = n("padding-top"), pr = n("padding-right"), pb = n("padding-bottom"), pl = n("padding-left");
1338
+ var bt = n("border-top-width"), br = n("border-right-width"), bb = n("border-bottom-width"), bl = n("border-left-width");
1339
+ var out = [
1340
+ { prop: "margin-top", kind: "m", axis: "y", sign: -1, v: mt, x: r.left - ml, y: r.top - mt, w: r.width + ml + mr, h: mt },
1341
+ { prop: "margin-bottom", kind: "m", axis: "y", sign: 1, v: mb, x: r.left - ml, y: r.bottom, w: r.width + ml + mr, h: mb },
1342
+ { prop: "margin-left", kind: "m", axis: "x", sign: -1, v: ml, x: r.left - ml, y: r.top, w: ml, h: r.height },
1343
+ { prop: "margin-right", kind: "m", axis: "x", sign: 1, v: mr, x: r.right, y: r.top, w: mr, h: r.height },
1344
+ { prop: "padding-top", kind: "p", axis: "y", sign: 1, v: pt, x: r.left + bl, y: r.top + bt, w: r.width - bl - br, h: pt },
1345
+ { prop: "padding-bottom", kind: "p", axis: "y", sign: -1, v: pb, x: r.left + bl, y: r.bottom - bb - pb, w: r.width - bl - br, h: pb },
1346
+ { prop: "padding-left", kind: "p", axis: "x", sign: 1, v: pl, x: r.left + bl, y: r.top + bt + pt, w: pl, h: r.height - bt - bb - pt - pb },
1347
+ { prop: "padding-right", kind: "p", axis: "x", sign: -1, v: pr, x: r.right - br - pr, y: r.top + bt + pt, w: pr, h: r.height - bt - bb - pt - pb },
1348
+ ];
1349
+ // A side with nothing gets a thin edge to drag one out of.
1350
+ out.forEach(function (b) {
1351
+ if (b.v > 0) return;
1352
+ b.zero = true;
1353
+ if (b.axis === "y") {
1354
+ b.h = 6;
1355
+ b.y -= 3;
1356
+ } else {
1357
+ b.w = 6;
1358
+ b.x -= 3;
1359
+ }
1360
+ });
1361
+ // Gaps between the children of a flex or grid box, where they sit side by side or one under the other.
1362
+ if (/flex|grid/.test(cs.display)) {
1363
+ var kids = [].slice.call(el.children).filter(function (c) {
1364
+ var s = getComputedStyle(c);
1365
+ return s.display !== "none" && s.position !== "absolute" && s.position !== "fixed";
1366
+ });
1367
+ var cg = n("column-gap"), rg = n("row-gap");
1368
+ for (var i = 0; i + 1 < kids.length; i++) {
1369
+ var a = kids[i].getBoundingClientRect();
1370
+ var b = kids[i + 1].getBoundingClientRect();
1371
+ if (cg > 0 && b.left - a.right > cg - 1 && b.left - a.right < cg + 1)
1372
+ out.push({ prop: "column-gap", kind: "g", axis: "x", sign: 1, v: cg, x: a.right, y: Math.min(a.top, b.top), w: cg, h: Math.max(a.bottom, b.bottom) - Math.min(a.top, b.top) });
1373
+ else if (rg > 0 && b.top - a.bottom > rg - 1 && b.top - a.bottom < rg + 1)
1374
+ out.push({ prop: "row-gap", kind: "g", axis: "y", sign: 1, v: rg, x: Math.min(a.left, b.left), y: a.bottom, w: Math.max(a.right, b.right) - Math.min(a.left, b.left), h: rg });
1375
+ }
1376
+ }
1377
+ return out;
1378
+ }
1379
+ function drawBands() {
1380
+ var list = S.sel && S.on && S.sel.isConnected ? bandsFor(S.sel) : [];
1381
+ while (bands.length < list.length) {
1382
+ var d = div("band");
1383
+ d.addEventListener("pointerdown", startDrag);
1384
+ // Pointing at a band says its value, as Figma labels a gap or padding.
1385
+ d.addEventListener("pointerenter", function (e) {
1386
+ S.bandHover = e.currentTarget;
1387
+ });
1388
+ d.addEventListener("pointerleave", function () {
1389
+ S.bandHover = null;
1390
+ });
1391
+ bandLayer.appendChild(d);
1392
+ bands.push(d);
1393
+ }
1394
+ bands.forEach(function (d, i) {
1395
+ var b = list[i];
1396
+ show(d, !!b);
1397
+ if (!b) return;
1398
+ d.className = "band " + b.kind + " " + b.axis + (b.zero ? " zero" : "") + (S.drag && S.drag.prop === b.prop ? " live" : "");
1399
+ d.__band = b;
1400
+ place(d, b.x, b.y, b.w, b.h);
1401
+ });
1402
+ }
1403
+
1404
+ // Rulers on the top and left edges, in the page's px, and the guides pulled out of them.
1405
+ function drawRulers() {
1406
+ var on = S.on && S.rulers;
1407
+ show(topRuler, on);
1408
+ show(leftRuler, on);
1409
+ show(corner, on);
1410
+ show(guideLayer, S.on && (S.rulers || S.guides.x.length || S.guides.y.length));
1411
+ if (!S.on) return;
1412
+ var dpr = window.devicePixelRatio || 1;
1413
+ var W = window.innerWidth;
1414
+ var H = window.innerHeight;
1415
+ if (on) {
1416
+ ruler(topRuler, W, RS, dpr, window.scrollX, "x");
1417
+ ruler(leftRuler, RS, H, dpr, window.scrollY, "y");
1418
+ }
1419
+ var nodes = guideLayer.children;
1420
+ var want = S.guides.x.length + S.guides.y.length;
1421
+ while (nodes.length < want) {
1422
+ var g = div("guide");
1423
+ g.appendChild(document.createElement("i"));
1424
+ g.addEventListener("pointerdown", grabGuide);
1425
+ guideLayer.appendChild(g);
1426
+ }
1427
+ while (nodes.length > want) guideLayer.removeChild(guideLayer.lastChild);
1428
+ var i = 0;
1429
+ S.guides.x.forEach(function (x, n) {
1430
+ var g = nodes[i++];
1431
+ g.className = "guide v";
1432
+ g.__guide = { axis: "x", n: n };
1433
+ g.style.height = H + "px";
1434
+ place(g, x - window.scrollX, 0);
1435
+ });
1436
+ S.guides.y.forEach(function (y, n) {
1437
+ var g = nodes[i++];
1438
+ g.className = "guide h";
1439
+ g.__guide = { axis: "y", n: n };
1440
+ g.style.width = W + "px";
1441
+ place(g, 0, y - window.scrollY);
1442
+ });
1443
+ }
1444
+ function ruler(c, w, h, dpr, scroll, axis) {
1445
+ if (c.width !== Math.round(w * dpr) || c.height !== Math.round(h * dpr)) {
1446
+ c.width = Math.round(w * dpr);
1447
+ c.height = Math.round(h * dpr);
1448
+ c.style.width = w + "px";
1449
+ c.style.height = h + "px";
1450
+ }
1451
+ place(c, 0, 0);
1452
+ var g = c.getContext("2d");
1453
+ g.setTransform(dpr, 0, 0, dpr, 0, 0);
1454
+ g.clearRect(0, 0, w, h);
1455
+ g.fillStyle = "rgba(255,255,255,.96)";
1456
+ g.fillRect(0, 0, w, h);
1457
+ var len = axis === "x" ? w : h;
1458
+ // What is picked, marked along the ruler.
1459
+ if (S.sel && S.sel.isConnected) {
1460
+ var r = S.sel.getBoundingClientRect();
1461
+ g.fillStyle = "rgba(255,77,46,.18)";
1462
+ if (axis === "x") g.fillRect(r.left, 0, r.width, h);
1463
+ else g.fillRect(0, r.top, w, r.height);
1464
+ }
1465
+ g.strokeStyle = "rgba(16,16,16,.34)";
1466
+ g.fillStyle = "#6b665f";
1467
+ g.font = "9px ui-sans-serif,system-ui,sans-serif";
1468
+ g.lineWidth = 1;
1469
+ g.beginPath();
1470
+ for (var v = Math.floor(scroll / 10) * 10; v <= scroll + len; v += 10) {
1471
+ var at = Math.round(v - scroll) + 0.5;
1472
+ var t = v % 100 === 0 ? RS * 0.6 : v % 50 === 0 ? RS * 0.38 : RS * 0.22;
1473
+ if (axis === "x") {
1474
+ g.moveTo(at, RS);
1475
+ g.lineTo(at, RS - t);
1476
+ } else {
1477
+ g.moveTo(RS, at);
1478
+ g.lineTo(RS - t, at);
1479
+ }
1480
+ if (v % 100 === 0 && v > 0) {
1481
+ if (axis === "x") g.fillText(String(v), at + 3, 9);
1482
+ else {
1483
+ g.save();
1484
+ g.translate(9, at - 3);
1485
+ g.rotate(-Math.PI / 2);
1486
+ g.fillText(String(v), 0, 0);
1487
+ g.restore();
1488
+ }
1489
+ }
1490
+ }
1491
+ g.stroke();
1492
+ g.fillStyle = "rgba(16,16,16,.14)";
1493
+ if (axis === "x") g.fillRect(0, h - 1, w, 1);
1494
+ else g.fillRect(w - 1, 0, 1, h);
1495
+ }
1496
+
1497
+ function draw() {
1498
+ mount();
1499
+ var on = S.on;
1500
+ var hv = on && S.hover && S.hover !== S.sel && S.hover.isConnected && !S.drag && !S.resize && !S.move && !S.editing && !S.pass ? S.hover : null;
1501
+ show(hoverBox, !!hv);
1502
+ show(hoverTag, !!hv);
1503
+ if (hv) {
1504
+ var r = hv.getBoundingClientRect();
1505
+ place(hoverBox, r.left, r.top, r.width, r.height);
1506
+ hoverTag.textContent = label(hv) + " " + Math.round(r.width) + " × " + Math.round(r.height);
1507
+ place(hoverTag, Math.max(0, r.left), Math.max(0, r.top - 22));
1508
+ }
1509
+ var sl = on && S.sel && S.sel.isConnected ? S.sel : null;
1510
+ show(selBox, !!sl);
1511
+ // Its size shows once: under it, or by the pointer while a handle is dragged.
1512
+ show(selTag, !!sl && !S.resize);
1513
+ if (sl) {
1514
+ var s = sl.getBoundingClientRect();
1515
+ place(selBox, s.left, s.top, s.width, s.height);
1516
+ selBox.className = "box sel" + (S.editing === sl ? " text" : "");
1517
+ selTag.textContent = Math.round(s.width * 10) / 10 + " × " + Math.round(s.height * 10) / 10;
1518
+ var tw = selTag.offsetWidth || 60;
1519
+ place(selTag, s.left + s.width / 2 - tw / 2, Math.min(window.innerHeight - 22, s.bottom + 6));
1520
+ }
1521
+ // Handles to resize what is picked, at its corners and sides (not while its text is edited or it is moved).
1522
+ // The others picked with it, outlined too.
1523
+ var others = on ? picked().slice(1) : [];
1524
+ while (othersLayer.children.length < others.length) othersLayer.appendChild(div("box sel"));
1525
+ [].forEach.call(othersLayer.children, function (n, i) {
1526
+ var x = others[i];
1527
+ show(n, !!x);
1528
+ if (x) {
1529
+ var rx = x.getBoundingClientRect();
1530
+ place(n, rx.left, rx.top, rx.width, rx.height);
1531
+ }
1532
+ });
1533
+ var hs = sl && !others.length && !S.editing && !S.move && !S.drag && !S.pass && !(sl instanceof SVGElement && sl.localName !== "svg");
1534
+ var r0 = hs ? sl.getBoundingClientRect() : null;
1535
+ handles.forEach(function (h) {
1536
+ show(h, !!hs);
1537
+ if (!hs) return;
1538
+ var d = h.__dir;
1539
+ place(h, d.indexOf("w") >= 0 ? r0.left : d.indexOf("e") >= 0 ? r0.right : r0.left + r0.width / 2, d.indexOf("n") >= 0 ? r0.top : d.indexOf("s") >= 0 ? r0.bottom : r0.top + r0.height / 2);
1540
+ });
1541
+ var slot = S.move && S.move.mode === "order" && S.move.slot && !S.move.slot.same ? S.move.slot.line : null;
1542
+ show(dropLine, !!slot);
1543
+ if (slot) place(dropLine, slot.x, slot.y, slot.w, slot.h);
1544
+ // The parent it would go into, when that's another one, outlined as Figma outlines the frame.
1545
+ var into = slot && S.move.slot.box;
1546
+ show(intoBox, !!into);
1547
+ if (into) place(intoBox, into.left, into.top, into.width, into.height);
1548
+ drawMeasure();
1549
+ drawSnaps();
1550
+ var bh = S.bandHover && S.bandHover.isConnected && S.bandHover.style.display !== "none" && !S.drag && !S.move && !S.editing ? S.bandHover.__band : null;
1551
+ show(bandTag, !!bh);
1552
+ if (bh) {
1553
+ bandTag.textContent = String(Math.round(bh.v * 10) / 10);
1554
+ var tw = bandTag.offsetWidth || 24;
1555
+ place(bandTag, bh.x + Math.max(bh.w, 0) / 2 - tw / 2, bh.y + Math.max(bh.h, 0) / 2 - 8);
1556
+ }
1557
+ if (S.editing || S.move || S.pass || S.extra.length) bands.forEach(function (d) {
1558
+ show(d, false);
1559
+ });
1560
+ else drawBands();
1561
+ drawRulers();
1562
+ if (!S.drag && !S.guideDrag && !S.resize && !S.move) show(tip, false);
1563
+ }
1564
+ var frame = 0;
1565
+ function loop() {
1566
+ frame = 0;
1567
+ if (!S.on) return draw();
1568
+ draw();
1569
+ frame = requestAnimationFrame(loop);
1570
+ }
1571
+
1572
+ /* ---------------------------------------------------------------- picking */
1573
+ // What is picked: one layer (S.sel), and the others picked with it (⇧), as Figma's selection.
1574
+ S.extra = [];
1575
+ function picked() {
1576
+ return (S.sel && S.sel.isConnected ? [S.sel] : []).concat(S.extra.filter(function (x) {
1577
+ return x.isConnected && x !== S.sel;
1578
+ }));
1579
+ }
1580
+ // ⇧-click: in or out of the selection.
1581
+ function toggleSel(el) {
1582
+ if (!el) return;
1583
+ if (!S.sel) return select(el, false);
1584
+ if (el === S.sel) {
1585
+ var next = S.extra.shift() || null;
1586
+ S.sel = next;
1587
+ } else if (S.extra.indexOf(el) >= 0) S.extra.splice(S.extra.indexOf(el), 1);
1588
+ else S.extra.push(el);
1589
+ if (S.editing) stopText();
1590
+ report();
1591
+ }
1592
+ function select(el, scroll) {
1593
+ if (S.editing && el !== S.editing) stopText();
1594
+ S.sel = el;
1595
+ S.extra = [];
1596
+ if (el && scroll) el.scrollIntoView({ block: "center", inline: "nearest", behavior: "smooth" });
1597
+ report();
1598
+ }
1599
+ // Picked with others: how many, which, and the values they don't share (shown as Mixed).
1600
+ function withOthers(i) {
1601
+ var all = picked();
1602
+ if (all.length < 2) return i;
1603
+ i.count = all.length;
1604
+ i.keys = all.map(keyOf);
1605
+ var styles = all.slice(1).map(function (x) {
1606
+ return getComputedStyle(x);
1607
+ });
1608
+ for (var p in i.props) {
1609
+ var v = i.props[p].value;
1610
+ if (styles.some(function (cs) {
1611
+ return cs.getPropertyValue(p).trim() !== v;
1612
+ })) i.props[p].mixed = true;
1613
+ }
1614
+ return i;
1615
+ }
1616
+ var reportQueued = false;
1617
+ function report() {
1618
+ if (reportQueued) return;
1619
+ reportQueued = true;
1620
+ requestAnimationFrame(function () {
1621
+ reportQueued = false;
1622
+ var on = S.sel && S.sel.isConnected;
1623
+ // Nothing picked: the page itself, as Figma's panel shows the page's background.
1624
+ var body = document.body;
1625
+ send({
1626
+ type: "selected",
1627
+ el: on ? withOthers(info(S.sel)) : null,
1628
+ page: on || !body ? null : { key: keyOf(body), background: propInfo(body, getComputedStyle(body), "background-color") },
1629
+ });
1630
+ });
1631
+ }
1632
+ function reportChanges() {
1633
+ send({ type: "changes", changes: changes() });
1634
+ }
1635
+ function target(e) {
1636
+ var t = e.target;
1637
+ if (!t || t.nodeType !== 1 || t === document.documentElement) return null;
1638
+ return t;
1639
+ }
1640
+ function isLink(el) {
1641
+ return !!el.closest("a[href],area[href]");
1642
+ }
1643
+ function isButton(el) {
1644
+ return !!el.closest("button,input,select,textarea,label,summary,[role=button],[onclick]");
1645
+ }
1646
+ // While editing, a press only picks: the page's own handlers don't hear it, unless Space is held (the page as usual)
1647
+ // or it is in the text being edited.
1648
+ function swallow(e) {
1649
+ if (!S.on || S.pass || ours(e)) return false;
1650
+ var t = target(e);
1651
+ if (S.editing && t && S.editing.contains(t)) return false;
1652
+ if (t && ((!S.block.links && isLink(t)) || (!S.block.buttons && isButton(t) && !isLink(t)))) return false;
1653
+ e.preventDefault();
1654
+ e.stopPropagation();
1655
+ e.stopImmediatePropagation();
1656
+ return true;
1657
+ }
1658
+
1659
+ /* ---------------------------------------------------------------- picking, as Figma picks */
1660
+ // A box that only wraps one other box the same size, with nothing of its own to see, is passed straight through, as
1661
+ // if the two were one layer.
1662
+ function paints(n) {
1663
+ var cs = getComputedStyle(n);
1664
+ return !/^(rgba\(0, 0, 0, 0\)|transparent)$/.test(cs.backgroundColor) || cs.backgroundImage !== "none" || cs.boxShadow !== "none" ||
1665
+ ["Top", "Right", "Bottom", "Left"].some(function (s) {
1666
+ return parseFloat(cs["border" + s + "Width"]) > 0 && cs["border" + s + "Style"] !== "none";
1667
+ });
1668
+ }
1669
+ function through(n, t) {
1670
+ while (n !== t) {
1671
+ var kids = layerKids(n);
1672
+ if (kids.length !== 1 || ownText(n) || paints(n)) break;
1673
+ var a = n.getBoundingClientRect();
1674
+ var b = kids[0].getBoundingClientRect();
1675
+ if (Math.abs(a.width - b.width) > 1 || Math.abs(a.height - b.height) > 1) break;
1676
+ n = kids[0];
1677
+ }
1678
+ return n;
1679
+ }
1680
+ // The child of scope that holds t: one level in.
1681
+ function childLayer(scope, t) {
1682
+ if (!t || t === scope || !scope.contains(t)) return null;
1683
+ var n = t;
1684
+ while (n.parentElement && n.parentElement !== scope) n = n.parentElement;
1685
+ return through(n, t);
1686
+ }
1687
+ // What a click on t picks: as in Figma, a layer at the level of what is picked (its siblings), or higher up when the
1688
+ // click is outside its parent; within what is picked, it stays picked; ⌘ picks the deepest.
1689
+ function pickAt(t, deep) {
1690
+ // Words styled in a text are part of it, not layers.
1691
+ while (t && t.hasAttribute && t.hasAttribute("data-bo-mark")) t = t.parentElement;
1692
+ if (!t || t === document.documentElement || t === document.body) return null;
1693
+ // The kit's comment mode: a click is on what is under the pointer, as a whole: a button or link rather than its
1694
+ // label, an icon rather than its paths.
1695
+ if (window.__blockoutEditorDeep) return (t.closest && t.closest("button,a,input,select,textarea,label,img,svg,[role=button]")) || t;
1696
+ if (deep) return t;
1697
+ if (S.sel && S.sel.isConnected && (S.sel === t || S.sel.contains(t))) return S.sel;
1698
+ var scope = S.sel && S.sel.isConnected ? S.sel.parentElement : null;
1699
+ while (scope && !scope.contains(t)) scope = scope.parentElement;
1700
+ if (!scope || scope === document.documentElement) scope = document.body;
1701
+ return childLayer(scope, t) || t;
1702
+ }
1703
+
1704
+ /* ---------------------------------------------------------------- editing text */
1705
+ var PLAIN = (function () {
1706
+ try {
1707
+ var d = document.createElement("div");
1708
+ d.contentEditable = "plaintext-only";
1709
+ return d.contentEditable === "plaintext-only";
1710
+ } catch (e) {
1711
+ return false;
1712
+ }
1713
+ })();
1714
+ var TEXTY = /^(h[1-6]|p|span|a|button|label|li|td|th|dt|dd|figcaption|blockquote|small|strong|em|b|i|u|s|code|q|cite|caption|legend|summary|time|mark|sub|sup)$/;
1715
+ // A text layer, as Figma has them: it holds text of its own, or it is an empty text element.
1716
+ function isTextLayer(el) {
1717
+ return !!el && !(el instanceof SVGElement) && (ownText(el) || (TEXTY.test(el.localName) && !el.children.length));
1718
+ }
1719
+ function startText(el, all, x, y) {
1720
+ stopText();
1721
+ if (!isTextLayer(el)) return;
1722
+ record([el], "text:" + keyOf(el) + ":" + Date.now(), "text");
1723
+ rememberContent(el, "text");
1724
+ S.editing = el;
1725
+ S.editingWas = el.getAttribute("contenteditable");
1726
+ el.setAttribute("contenteditable", PLAIN ? "plaintext-only" : "true");
1727
+ el.focus({ preventScroll: true });
1728
+ var range = null;
1729
+ if (!all && x !== undefined) {
1730
+ if (document.caretRangeFromPoint) range = document.caretRangeFromPoint(x, y);
1731
+ else if (document.caretPositionFromPoint) {
1732
+ var at = document.caretPositionFromPoint(x, y);
1733
+ if (at) {
1734
+ range = document.createRange();
1735
+ range.setStart(at.offsetNode, at.offset);
1736
+ }
1737
+ }
1738
+ if (range && !el.contains(range.startContainer)) range = null;
1739
+ }
1740
+ if (!range) {
1741
+ range = document.createRange();
1742
+ range.selectNodeContents(el);
1743
+ }
1744
+ var sel = window.getSelection();
1745
+ sel.removeAllRanges();
1746
+ sel.addRange(range);
1747
+ S.sel = el;
1748
+ report();
1749
+ }
1750
+ function stopText() {
1751
+ var el = S.editing;
1752
+ if (!el) return;
1753
+ S.editing = null;
1754
+ if (S.editingWas === null) el.removeAttribute("contenteditable");
1755
+ else el.setAttribute("contenteditable", S.editingWas);
1756
+ var s = window.getSelection();
1757
+ if (s) s.removeAllRanges();
1758
+ if (document.activeElement === el) el.blur();
1759
+ // Nothing typed: no step to undo.
1760
+ var last = past[past.length - 1];
1761
+ if (last && last.mode === "text" && last.items[0].el === el && JSON.stringify(runsOf(el, true)) === last.runs) past.pop();
1762
+ var o = originals.get(el);
1763
+ if (o && !isChanged(el)) originals.delete(el);
1764
+ reportChanges();
1765
+ report();
1766
+ if (el.parentElement) sendChildren(el.parentElement);
1767
+ }
1768
+ // Typing shows in the panel as it goes; a paste comes in as plain text.
1769
+ var typingQueued = false;
1770
+ document.addEventListener("input", function (e) {
1771
+ if (!S.editing || !S.editing.contains(e.target) || typingQueued) return;
1772
+ typingQueued = true;
1773
+ requestAnimationFrame(function () {
1774
+ typingQueued = false;
1775
+ reportChanges();
1776
+ report();
1777
+ });
1778
+ }, true);
1779
+ document.addEventListener("paste", function (e) {
1780
+ if (!S.editing || !S.editing.contains(e.target)) return;
1781
+ e.preventDefault();
1782
+ var text = (e.clipboardData && e.clipboardData.getData("text/plain")) || "";
1783
+ document.execCommand("insertText", false, text);
1784
+ }, true);
1785
+
1786
+ /* ---------------------------------------------------------------- pressing, dragging, clicking */
1787
+ // A press that moves drags what it would pick: an absolute box moves; one in a layout moves among its siblings.
1788
+ window.addEventListener("pointerdown", function (e) {
1789
+ if (!S.on || S.pass || e.button !== 0 || ours(e)) return;
1790
+ var t = target(e);
1791
+ if (!t || (S.editing && S.editing.contains(t))) return;
1792
+ // The press is held from the page, so the page doesn't take the keyboard by itself: it is given it, for Enter,
1793
+ // Delete, the arrows and Tab to reach what is picked.
1794
+ if (!document.hasFocus()) window.focus();
1795
+ // Which of the canvas's frames is being worked in: the panel follows it.
1796
+ send({ type: "focus" });
1797
+ if (document.activeElement && document.activeElement !== document.body && !ours(e)) document.activeElement.blur();
1798
+ S.press = { x: e.clientX, y: e.clientY, t: t, deep: e.metaKey || e.ctrlKey };
1799
+ }, true);
1800
+ // Before the page's presses are held still below, so a press always ends here.
1801
+ window.addEventListener("pointerup", function (e) {
1802
+ if (S.move) endMove(e);
1803
+ S.press = null;
1804
+ }, true);
1805
+ ["pointerdown", "mousedown", "pointerup", "mouseup", "dblclick", "auxclick", "touchstart", "submit"].forEach(function (type) {
1806
+ window.addEventListener(type, swallow, { capture: true, passive: false });
1807
+ });
1808
+ window.addEventListener(
1809
+ "click",
1810
+ function (e) {
1811
+ if (!S.on || S.pass || ours(e)) return;
1812
+ var t = target(e);
1813
+ if (S.editing && t && S.editing.contains(t)) return;
1814
+ swallow(e);
1815
+ if (S.moved) {
1816
+ S.moved = false;
1817
+ return;
1818
+ }
1819
+ if (S.editing) stopText();
1820
+ // A double-click goes in: into the text of a text layer, or a level down to what is under the pointer.
1821
+ if (e.detail >= 2 && S.sel && t && (S.sel === t || S.sel.contains(t))) {
1822
+ var inner = childLayer(S.sel, t);
1823
+ if (isTextLayer(S.sel) && (!inner || /^inline/.test(getComputedStyle(inner).display))) return startText(S.sel, false, e.clientX, e.clientY);
1824
+ if (inner) select(inner, false);
1825
+ return;
1826
+ }
1827
+ if (e.shiftKey) return toggleSel(pickAt(t, e.metaKey || e.ctrlKey));
1828
+ select(pickAt(t, e.metaKey || e.ctrlKey), false);
1829
+ },
1830
+ true,
1831
+ );
1832
+ window.addEventListener(
1833
+ "pointermove",
1834
+ function (e) {
1835
+ if (!S.on) return;
1836
+ S.alt = e.altKey;
1837
+ if (S.press && !S.move && !S.drag && !S.resize && Math.hypot(e.clientX - S.press.x, e.clientY - S.press.y) > 4) startMove(e);
1838
+ if (S.move) return moveTo(e);
1839
+ if (S.drag || S.resize) return;
1840
+ S.hover = ours(e) || S.editing ? null : pickAt(target(e), e.metaKey || e.ctrlKey);
1841
+ if (S.hover !== lastHover) {
1842
+ lastHover = S.hover;
1843
+ send({ type: "hovered", key: S.hover ? keyOf(S.hover) : null });
1844
+ }
1845
+ },
1846
+ true,
1847
+ );
1848
+ document.documentElement.addEventListener("mouseleave", function () {
1849
+ S.hover = null;
1850
+ });
1851
+
1852
+ // The siblings it moves among, in a layout: what is laid out with it (not absolute, not deleted).
1853
+ function flowKids(parent) {
1854
+ return layerKids(parent).filter(function (k) {
1855
+ return !isRemoved(k) && !/^(absolute|fixed)$/.test(getComputedStyle(k).position);
1856
+ });
1857
+ }
1858
+ function axisOf(parent) {
1859
+ var cs = getComputedStyle(parent);
1860
+ if (/grid/.test(cs.display)) return "grid";
1861
+ if (/flex/.test(cs.display)) return cs.flexWrap === "wrap" && !/column/.test(cs.flexDirection) ? "grid" : /column/.test(cs.flexDirection) ? "y" : "x";
1862
+ return /^inline/.test(getComputedStyle(parent.firstElementChild || parent).display) ? "x" : "y";
1863
+ }
1864
+ // Where a dragged element would go among its siblings: before which one, and the line that shows it.
1865
+ // Where a dragged element would go: into which parent (the auto layout under the pointer, as Figma drops into a
1866
+ // frame; a sibling only from its middle, so its edges still reorder), before which child, and the line that shows it.
1867
+ function intoAt(el, x, y) {
1868
+ var home = el.parentElement;
1869
+ var hits = document.elementsFromPoint(x, y);
1870
+ for (var i = 0; i < hits.length; i++) {
1871
+ var c = hits[i];
1872
+ if (c === host || host.contains(c) || c === el || el.contains(c)) continue;
1873
+ for (; c && c !== document.documentElement; c = c.parentElement) {
1874
+ if (c === el || el.contains(c)) break;
1875
+ if (c === home || c === document.body) return home;
1876
+ if (c instanceof SVGElement || isTextLayer(c) || /^(img|picture|video|canvas|iframe|input|textarea|select|button|a)$/.test(c.localName)) continue;
1877
+ if (!/(flex|grid)/.test(getComputedStyle(c).display)) continue;
1878
+ if (c.parentElement === home) {
1879
+ var r = c.getBoundingClientRect();
1880
+ var ax = axisOf(home);
1881
+ var inner = ax === "y" ? y > r.top + r.height / 4 && y < r.bottom - r.height / 4 : x > r.left + r.width / 4 && x < r.right - r.width / 4;
1882
+ if (!inner) continue;
1883
+ }
1884
+ return c;
1885
+ }
1886
+ }
1887
+ return home;
1888
+ }
1889
+ function slotFor(el, x, y) {
1890
+ var parent = intoAt(el, x, y) || el.parentElement;
1891
+ var all = flowKids(parent);
1892
+ var cur = all.indexOf(el);
1893
+ var kids = all.filter(function (k) {
1894
+ return k !== el;
1895
+ });
1896
+ var box = parent.getBoundingClientRect();
1897
+ if (!kids.length) {
1898
+ if (parent === el.parentElement) return null;
1899
+ var pcs = getComputedStyle(parent);
1900
+ var px = box.left + (parseFloat(pcs.paddingLeft) || 0);
1901
+ var py = box.top + (parseFloat(pcs.paddingTop) || 0);
1902
+ return { parent: parent, ref: null, line: { x: px, y: py, w: Math.max(2, box.width - (parseFloat(pcs.paddingLeft) || 0) - (parseFloat(pcs.paddingRight) || 0)), h: 2 }, same: false, box: box };
1903
+ }
1904
+ var axis = axisOf(parent);
1905
+ var at = kids.length;
1906
+ for (var i = 0; i < kids.length; i++) {
1907
+ var r = kids[i].getBoundingClientRect();
1908
+ var before = axis === "x" ? x < r.left + r.width / 2 : axis === "y" ? y < r.top + r.height / 2 : y < r.top || (y <= r.bottom && x < r.left + r.width / 2);
1909
+ if (before) {
1910
+ at = i;
1911
+ break;
1912
+ }
1913
+ }
1914
+ var ref = at < kids.length ? kids[at] : null;
1915
+ var near = (ref || kids[kids.length - 1]).getBoundingClientRect();
1916
+ var line = axis === "y"
1917
+ ? { x: near.left, y: ref ? near.top - 2 : near.bottom + 1, w: near.width, h: 2 }
1918
+ : { x: ref ? near.left - 2 : near.right + 1, y: near.top, w: 2, h: near.height };
1919
+ var other = parent !== el.parentElement;
1920
+ return { parent: parent, ref: ref ? ref : kids[kids.length - 1].nextSibling, line: line, same: !other && at === cur, box: other ? box : null };
1921
+ }
1922
+ function startMove(e) {
1923
+ var press = S.press;
1924
+ var el = pickAt(press.t, press.deep);
1925
+ S.press = null;
1926
+ if (!el || !el.parentElement || el === document.body || S.editing) return;
1927
+ if (S.sel !== el) select(el, false);
1928
+ var abs = /^(absolute|fixed)$/.test(getComputedStyle(el).position);
1929
+ var cs = getComputedStyle(el);
1930
+ S.move = abs
1931
+ ? // From where the press began, not where the drag threshold was passed, so the layer stays under the pointer.
1932
+ { el: el, mode: "free", x0: press.x, y0: press.y, l0: parseFloat(cs.left) || 0, t0: parseFloat(cs.top) || 0, r0: el.getBoundingClientRect(), recorded: false }
1933
+ : { el: el, mode: "order", slot: null };
1934
+ S.hover = null;
1935
+ }
1936
+ function moveTo(e) {
1937
+ var m = S.move;
1938
+ if (m.mode === "free") {
1939
+ if (!m.recorded) {
1940
+ record([m.el], null);
1941
+ m.recorded = true;
1942
+ }
1943
+ var dx = e.clientX - m.x0;
1944
+ var dy = e.clientY - m.y0;
1945
+ // Its edges and centre catch on what is around it, as Figma's snapping; ⌘ moves freely.
1946
+ S.snaps = [];
1947
+ if (!(e.metaKey || e.ctrlKey)) {
1948
+ var tg = snapTargets(m.el);
1949
+ var sx = snapAxis([m.r0.left + dx, m.r0.left + dx + m.r0.width / 2, m.r0.right + dx], tg.x);
1950
+ var sy = snapAxis([m.r0.top + dy, m.r0.top + dy + m.r0.height / 2, m.r0.bottom + dy], tg.y);
1951
+ if (sx) dx += sx.d;
1952
+ if (sy) dy += sy.d;
1953
+ var moved = { left: m.r0.left + dx, top: m.r0.top + dy, right: m.r0.right + dx, bottom: m.r0.bottom + dy };
1954
+ if (sx) S.snaps.push(snapLine("x", sx, moved));
1955
+ if (sy) S.snaps.push(snapLine("y", sy, moved));
1956
+ }
1957
+ var l = Math.round(m.l0 + dx);
1958
+ var t = Math.round(m.t0 + dy);
1959
+ setProp(m.el, "left", l + "px");
1960
+ setProp(m.el, "right", "auto");
1961
+ setProp(m.el, "top", t + "px");
1962
+ setProp(m.el, "bottom", "auto");
1963
+ tip.textContent = "X " + l + " Y " + t;
1964
+ } else {
1965
+ m.slot = slotFor(m.el, e.clientX, e.clientY);
1966
+ tip.textContent = m.slot && !m.slot.same ? (m.slot.box ? "Move into " + layerName(m.slot.parent) : "Move here") : "";
1967
+ }
1968
+ show(tip, !!tip.textContent);
1969
+ place(tip, e.clientX + 14, e.clientY + 14);
1970
+ report();
1971
+ }
1972
+ function endMove() {
1973
+ var m = S.move;
1974
+ S.move = null;
1975
+ S.moved = true;
1976
+ show(tip, false);
1977
+ if (m.mode === "order" && m.slot && !m.slot.same) moveEl(m.el, m.slot.parent || m.el.parentElement, m.slot.ref);
1978
+ reportChanges();
1979
+ report();
1980
+ }
1981
+ // Into a parent before a child (last when null), one step to undo; into another parent, it remembers where it was,
1982
+ // to say it moved (and from where).
1983
+ function moveEl(el, to, ref) {
1984
+ var parent = el.parentElement;
1985
+ if (!parent || !to || to === el || el.contains(to)) return;
1986
+ var both = to === parent ? [parent] : [parent, to];
1987
+ record(both, null, "order");
1988
+ both.forEach(function (p) {
1989
+ rememberContent(p, "order");
1990
+ });
1991
+ if (to !== parent) {
1992
+ var o = remember(el);
1993
+ if (!o.home) o.home = parent;
1994
+ }
1995
+ to.insertBefore(el, ref);
1996
+ both.forEach(sendChildren);
1997
+ if (to !== parent) send({ type: "dom" });
1998
+ }
1999
+ // In a layout, the arrows along it move it among its siblings, as Figma's auto layout; an absolute box nudges.
2000
+ function arrow(el, key, big) {
2001
+ var cs = getComputedStyle(el);
2002
+ if (/^(absolute|fixed)$/.test(cs.position)) {
2003
+ var d = big ? 10 : 1;
2004
+ var prop = key === "ArrowLeft" || key === "ArrowRight" ? "left" : "top";
2005
+ var sign = key === "ArrowLeft" || key === "ArrowUp" ? -1 : 1;
2006
+ record([el], "nudge:" + keyOf(el));
2007
+ setProp(el, prop, (parseFloat(cs[prop]) || 0) + sign * d + "px");
2008
+ setProp(el, prop === "left" ? "right" : "bottom", "auto");
2009
+ reportChanges();
2010
+ report();
2011
+ return true;
2012
+ }
2013
+ var parent = el.parentElement;
2014
+ if (!parent || parent === document.documentElement) return false;
2015
+ var axis = axisOf(parent);
2016
+ var back = key === "ArrowLeft" || key === "ArrowUp";
2017
+ if ((axis === "x" && /Up|Down/.test(key)) || (axis === "y" && /Left|Right/.test(key))) return false;
2018
+ var kids = flowKids(parent);
2019
+ var i = kids.indexOf(el);
2020
+ var j = back ? i - 1 : i + 1;
2021
+ if (i < 0 || j < 0 || j >= kids.length) return true;
2022
+ record([parent], "order:" + keyOf(parent), "order");
2023
+ rememberContent(parent, "order");
2024
+ parent.insertBefore(el, back ? kids[j] : kids[j].nextSibling);
2025
+ sendChildren(parent);
2026
+ reportChanges();
2027
+ report();
2028
+ return true;
2029
+ }
2030
+
2031
+ window.addEventListener(
2032
+ "keydown",
2033
+ function (e) {
2034
+ if (!S.on) return;
2035
+ var t = e.target;
2036
+ var typing = t && t.closest && t.closest("input,textarea,select,[contenteditable]");
2037
+ if (e.key === "Alt") S.alt = true;
2038
+ if (S.editing) {
2039
+ // In the text: Esc, or ⌘Enter, is done; ⌘B, ⌘I and ⌘U style the words picked; everything else types.
2040
+ if (e.key === "Escape" || (e.key === "Enter" && (e.metaKey || e.ctrlKey))) {
2041
+ e.preventDefault();
2042
+ e.stopPropagation();
2043
+ stopText();
2044
+ }
2045
+ if ((e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey && /^[biu]$/i.test(e.key)) {
2046
+ e.preventDefault();
2047
+ e.stopPropagation();
2048
+ markText(e.key.toLowerCase());
2049
+ }
2050
+ return;
2051
+ }
2052
+ if ((e.metaKey || e.ctrlKey) && !e.altKey && !typing && /^[zy]$/i.test(e.key)) {
2053
+ e.preventDefault();
2054
+ e.stopPropagation();
2055
+ var redo = e.key.toLowerCase() === "y" || e.shiftKey;
2056
+ return redo ? step(future, past) : step(past, future);
2057
+ }
2058
+ // ⌘D duplicates, ⌘C and ⌘V copy and paste the picked layers (unless text is selected on the page to copy).
2059
+ if ((e.metaKey || e.ctrlKey) && !e.altKey && !typing && /^[dcv]$/i.test(e.key)) {
2060
+ var k = e.key.toLowerCase();
2061
+ var textSel = String(window.getSelection && window.getSelection()).length > 0;
2062
+ if (k === "c" && (textSel || !S.sel)) return;
2063
+ if (k === "v" && !clip.length) return;
2064
+ if (k === "d" && !S.sel) return;
2065
+ e.preventDefault();
2066
+ e.stopPropagation();
2067
+ return k === "d" ? duplicate() : k === "c" ? copySel() : paste();
2068
+ }
2069
+ if (e.metaKey || e.ctrlKey) return;
2070
+ if (e.key === "Escape") {
2071
+ e.preventDefault();
2072
+ e.stopPropagation();
2073
+ if (S.sel) select(null);
2074
+ else send({ type: "escape" });
2075
+ return;
2076
+ }
2077
+ if (typing) return;
2078
+ // Space held: the page as usual, for a moment.
2079
+ if (e.key === " ") {
2080
+ e.preventDefault();
2081
+ S.pass = true;
2082
+ S.hover = null;
2083
+ return;
2084
+ }
2085
+ if (e.altKey) return;
2086
+ if ((e.key === "v" || e.key === "V") && !e.shiftKey) return send({ type: "mode" });
2087
+ if (e.key === "R" && e.shiftKey) return send({ type: "rulers" });
2088
+ if (!S.sel) return;
2089
+ if (e.key === "Enter") {
2090
+ e.preventDefault();
2091
+ if (e.shiftKey) return nav("parent");
2092
+ if (isTextLayer(S.sel)) return startText(S.sel, true);
2093
+ return nav("child");
2094
+ }
2095
+ if (e.key === "Tab") {
2096
+ e.preventDefault();
2097
+ return nav(e.shiftKey ? "prev" : "next");
2098
+ }
2099
+ if (e.key === "Backspace" || e.key === "Delete") {
2100
+ e.preventDefault();
2101
+ return removeEls(picked());
2102
+ }
2103
+ if (/^Arrow/.test(e.key)) {
2104
+ var handled = false;
2105
+ picked().forEach(function (x) {
2106
+ if (arrow(x, e.key, e.shiftKey)) handled = true;
2107
+ });
2108
+ if (handled) e.preventDefault();
2109
+ }
2110
+ },
2111
+ true,
2112
+ );
2113
+ // Zooming is the canvas's, around the page: ⌘-scroll and pinches (a wheel with ctrl) and ⌘+ ⌘− ⌘0 ⇧1 go out to it.
2114
+ window.addEventListener("wheel", function (e) {
2115
+ if (!S.on || !(e.ctrlKey || e.metaKey)) return;
2116
+ e.preventDefault();
2117
+ send({ type: "zoom", dy: e.deltaY, x: e.clientX, y: e.clientY });
2118
+ }, { capture: true, passive: false });
2119
+ window.addEventListener("keydown", function (e) {
2120
+ if (!S.on) return;
2121
+ var t = e.target;
2122
+ if (t && t.closest && t.closest("input,textarea,select,[contenteditable]")) return;
2123
+ var k = (e.metaKey || e.ctrlKey) && /^(=|\+|-|0)$/.test(e.key) ? e.key : e.shiftKey && (e.key === "!" || e.code === "Digit1") ? "fit" : null;
2124
+ if (!k) return;
2125
+ e.preventDefault();
2126
+ send({ type: "zoomKey", key: k === "+" ? "=" : k });
2127
+ }, true);
2128
+ window.addEventListener(
2129
+ "keyup",
2130
+ function (e) {
2131
+ if (e.key === " ") S.pass = false;
2132
+ if (e.key === "Alt") S.alt = false;
2133
+ },
2134
+ true,
2135
+ );
2136
+ window.addEventListener("blur", function () {
2137
+ S.pass = false;
2138
+ S.alt = false;
2139
+ });
2140
+ function nav(to) {
2141
+ var el = S.sel;
2142
+ if (!el) return;
2143
+ var next = null;
2144
+ if (to === "parent") next = el.parentElement !== document.documentElement && el.parentElement !== document.body && el.parentElement;
2145
+ else if (to === "child") next = layerKids(el)[0] ? through(layerKids(el)[0], layerKids(el)[0]) : null;
2146
+ else {
2147
+ var kids = layerKids(el.parentElement || document.body).filter(function (k) {
2148
+ return !isRemoved(k);
2149
+ });
2150
+ var i = kids.indexOf(el);
2151
+ if (kids.length > 1 && i >= 0) next = kids[(i + (to === "next" ? 1 : kids.length - 1)) % kids.length];
2152
+ }
2153
+ if (next && next !== host) select(next, true);
2154
+ }
2155
+
2156
+ /* ---------------------------------------------------------------- layers */
2157
+ // The page as Figma's layers panel shows it: each element's children, named and kinded, asked for as rows open.
2158
+ var lastHover = null;
2159
+ var SKIP = /^(script|style|link|meta|noscript|template|title|head|base)$/;
2160
+ function layerKids(el) {
2161
+ if (el instanceof SVGElement) return [];
2162
+ return [].filter.call(el.children, function (c) {
2163
+ return c !== host && !SKIP.test(c.localName) && c.localName !== "blockout-pins" && !c.hasAttribute("data-blockout-editor") && !c.hasAttribute("data-bo-mark") && !isRemoved(c);
2164
+ });
2165
+ }
2166
+ function ownText(el) {
2167
+ return [].some.call(el.childNodes, function (n) {
2168
+ return (n.nodeType === 3 || (n.nodeType === 1 && n.hasAttribute("data-bo-mark"))) && n.textContent.trim();
2169
+ });
2170
+ }
2171
+ function layerName(el) {
2172
+ if (ownText(el)) return (el.innerText || el.textContent || "").trim().replace(/\s+/g, " ").slice(0, 60);
2173
+ var a = el.getAttribute("aria-label") || el.getAttribute("alt") || el.getAttribute("title");
2174
+ if (a) return a.slice(0, 60);
2175
+ if (stableId(el)) return "#" + el.id;
2176
+ var cls = [].slice.call(el.classList).find(function (c) {
2177
+ return /^[a-z][\w-]*$/i.test(c);
2178
+ });
2179
+ return el.localName + (cls ? "." + cls : "");
2180
+ }
2181
+ function layerOf(el) {
2182
+ var cs = getComputedStyle(el);
2183
+ var kids = layerKids(el);
2184
+ var tag = el.localName;
2185
+ var kind = el instanceof SVGElement ? "vector"
2186
+ : /^(img|picture|video|canvas|iframe)$/.test(tag) ? "image"
2187
+ : /^(input|textarea|select)$/.test(tag) ? "input"
2188
+ : /grid/.test(cs.display) ? "grid"
2189
+ : /flex/.test(cs.display) ? (/column/.test(cs.flexDirection) ? "column" : "row")
2190
+ : ownText(el) && !kids.length ? "text"
2191
+ : "frame";
2192
+ return { key: keyOf(el), name: layerName(el), kind: kind, children: kids.length, hidden: cs.display === "none" || cs.visibility === "hidden" };
2193
+ }
2194
+ // The page changing its elements (not its text): open layers are asked for again.
2195
+ var domQueued = 0;
2196
+ new MutationObserver(function (list) {
2197
+ if (!S.on || domQueued) return;
2198
+ var real = list.some(function (m) {
2199
+ return [].some.call(m.addedNodes, function (n) {
2200
+ return n.nodeType === 1 && n !== host;
2201
+ }) || [].some.call(m.removedNodes, function (n) {
2202
+ return n.nodeType === 1 && n !== host;
2203
+ });
2204
+ });
2205
+ if (!real) return;
2206
+ domQueued = setTimeout(function () {
2207
+ domQueued = 0;
2208
+ send({ type: "dom" });
2209
+ }, 400);
2210
+ }).observe(document.documentElement, { childList: true, subtree: true });
2211
+
2212
+ /* ---------------------------------------------------------------- the same edits in another frame */
2213
+ // The canvas shows the page at more than one width; what is changed in one frame is made the same here, by each
2214
+ // element's number in the file, and kept as this frame's own changes, so picking up the work here carries them on.
2215
+ var mirrored = {};
2216
+ function byId(id) {
2217
+ return document.querySelector('[data-bo-e="' + id + '"]');
2218
+ }
2219
+ function buildRuns(runs, used) {
2220
+ var out = [];
2221
+ runs.forEach(function (r) {
2222
+ if (typeof r === "string") out.push(document.createTextNode(r));
2223
+ else if (r && r.br) out.push(document.createElement("br"));
2224
+ else if (r && r.mark && MARK_TAG[r.mark]) {
2225
+ var m = document.createElement(MARK_TAG[r.mark]);
2226
+ m.setAttribute("data-bo-mark", r.mark);
2227
+ m.replaceChildren.apply(m, buildRuns(r.runs || [], used));
2228
+ out.push(m);
2229
+ }
2230
+ else if (r && r.el) {
2231
+ var el = byId(r.el);
2232
+ if (!el || used.has(el)) return;
2233
+ used.add(el);
2234
+ if (r.runs) el.replaceChildren.apply(el, buildRuns(r.runs, used));
2235
+ out.push(el);
2236
+ }
2237
+ });
2238
+ return out;
2239
+ }
2240
+ var mirroredCopies = {};
2241
+ function findRef(r) {
2242
+ if (!r) return null;
2243
+ try {
2244
+ return typeof r.id === "string" ? byId(r.id) : r.path ? document.querySelector(r.path) : null;
2245
+ } catch (x) {
2246
+ return null;
2247
+ }
2248
+ }
2249
+ function mirror(list) {
2250
+ var now = {};
2251
+ var copies = {};
2252
+ list.forEach(function (c) {
2253
+ if (!c) return;
2254
+ if (c.copyOf) {
2255
+ // A copy made in another frame: made here too, once, after the same element.
2256
+ var key = "c:" + c.key;
2257
+ var made = mirroredCopies[key];
2258
+ if (!made || !made.isConnected) {
2259
+ var src = findRef(c.copyOf);
2260
+ var at = c.after ? findRef(c.after) : null;
2261
+ var parent = at ? at.parentElement : findRef(c.parent);
2262
+ if (!src || !parent) return;
2263
+ made = cloneOf(src);
2264
+ parent.insertBefore(made, at ? at.nextSibling : parent.firstChild);
2265
+ }
2266
+ if (c.style) made.setAttribute("style", c.style);
2267
+ else made.removeAttribute("style");
2268
+ copies[key] = made;
2269
+ return;
2270
+ }
2271
+ // By its number in the file, or in a project's page (no numbers) by its CSS path.
2272
+ var key = typeof c.id === "string" ? c.id : typeof c.path === "string" ? "p:" + c.path : null;
2273
+ var el = null;
2274
+ try {
2275
+ el = typeof c.id === "string" ? byId(c.id) : c.path ? document.querySelector(c.path) : null;
2276
+ } catch (x) {}
2277
+ if (!key || !el) return;
2278
+ now[key] = 1;
2279
+ if (c.content) rememberContent(el, "text");
2280
+ else remember(el);
2281
+ if (c.style) el.setAttribute("style", c.style);
2282
+ else el.removeAttribute("style");
2283
+ if (c.cls !== undefined) {
2284
+ if (c.cls) el.setAttribute("class", c.cls);
2285
+ else el.removeAttribute("class");
2286
+ }
2287
+ if (c.removed) originals.get(el).removed = true;
2288
+ // Children by their file numbers; a project's page has none, so its frames keep their own children.
2289
+ if (c.content && typeof c.id === "string") el.replaceChildren.apply(el, buildRuns(c.content, new Set()));
2290
+ });
2291
+ // What was changed here before and isn't any more (undone there): back as it was.
2292
+ Object.keys(mirrored).forEach(function (id) {
2293
+ if (now[id]) return;
2294
+ var el = null;
2295
+ try {
2296
+ el = id.indexOf("p:") === 0 ? document.querySelector(id.slice(2)) : byId(id);
2297
+ } catch (x) {}
2298
+ if (el) resetEl(el);
2299
+ });
2300
+ mirrored = now;
2301
+ Object.keys(mirroredCopies).forEach(function (k) {
2302
+ if (!copies[k]) mirroredCopies[k].remove();
2303
+ });
2304
+ mirroredCopies = copies;
2305
+ }
2306
+
2307
+ /* ---------------------------------------------------------------- snapping */
2308
+ var SNAP = 5;
2309
+ // What an element catches on: its siblings' and its parent's edges and centres, on each axis, each with its box.
2310
+ function snapTargets(el) {
2311
+ var p = el.parentElement || document.body;
2312
+ var boxes = layerKids(p).filter(function (k) {
2313
+ return k !== el && !k.contains(el) && !el.contains(k);
2314
+ }).map(function (k) {
2315
+ return k.getBoundingClientRect();
2316
+ });
2317
+ boxes.push(p.getBoundingClientRect());
2318
+ var x = [];
2319
+ var y = [];
2320
+ boxes.forEach(function (r) {
2321
+ [r.left, r.left + r.width / 2, r.right].forEach(function (v) {
2322
+ x.push({ at: v, r: r });
2323
+ });
2324
+ [r.top, r.top + r.height / 2, r.bottom].forEach(function (v) {
2325
+ y.push({ at: v, r: r });
2326
+ });
2327
+ });
2328
+ return { x: x, y: y };
2329
+ }
2330
+ // The nearest catch for any of these edges: how far to shift, where, and against which box.
2331
+ function snapAxis(edges, targets) {
2332
+ var best = null;
2333
+ edges.forEach(function (e) {
2334
+ targets.forEach(function (t) {
2335
+ var d = t.at - e;
2336
+ if (Math.abs(d) <= SNAP && (!best || Math.abs(d) < Math.abs(best.d))) best = { d: d, at: t.at, r: t.r };
2337
+ });
2338
+ });
2339
+ return best;
2340
+ }
2341
+ // A guide from the element to what it caught on, along the line they share.
2342
+ function snapLine(axis, s, box) {
2343
+ return axis === "x"
2344
+ ? { axis: "x", at: s.at, from: Math.min(box.top, s.r.top), to: Math.max(box.bottom, s.r.bottom) }
2345
+ : { axis: "y", at: s.at, from: Math.min(box.left, s.r.left), to: Math.max(box.right, s.r.right) };
2346
+ }
2347
+ function drawSnaps() {
2348
+ snapLayer.textContent = "";
2349
+ if (!(S.move || S.resize) || !S.snaps) return;
2350
+ S.snaps.forEach(function (g) {
2351
+ var l = div("ml");
2352
+ if (g.axis === "x") place(l, g.at - 0.5, g.from, 1, g.to - g.from);
2353
+ else place(l, g.from, g.at - 0.5, g.to - g.from, 1);
2354
+ snapLayer.appendChild(l);
2355
+ });
2356
+ }
2357
+
2358
+ /* ---------------------------------------------------------------- resizing */
2359
+ // A handle's drag sets a fixed width and height, as Figma's: ⇧ on a corner keeps the proportions. Pulling a left or
2360
+ // top edge of an absolute box moves it too, so the other edge stays where it is.
2361
+ function startResize(e) {
2362
+ if (e.button !== 0 || !S.sel) return;
2363
+ e.preventDefault();
2364
+ e.stopPropagation();
2365
+ e.currentTarget.setPointerCapture(e.pointerId);
2366
+ var el = S.sel;
2367
+ var r = el.getBoundingClientRect();
2368
+ var cs = getComputedStyle(el);
2369
+ var p = el.parentElement ? getComputedStyle(el.parentElement) : null;
2370
+ S.resize = {
2371
+ el: el,
2372
+ dir: e.currentTarget.__dir,
2373
+ x0: e.clientX,
2374
+ y0: e.clientY,
2375
+ w0: r.width,
2376
+ h0: r.height,
2377
+ r0: r,
2378
+ abs: /^(absolute|fixed)$/.test(cs.position),
2379
+ l0: parseFloat(cs.left) || 0,
2380
+ t0: parseFloat(cs.top) || 0,
2381
+ row: p && /flex/.test(p.display) ? !/column/.test(p.flexDirection) : null,
2382
+ node: e.currentTarget,
2383
+ recorded: false,
2384
+ };
2385
+ }
2386
+ function moveResize(e) {
2387
+ var z = S.resize;
2388
+ if (!z) return;
2389
+ if (!z.recorded) {
2390
+ record([z.el], null);
2391
+ z.recorded = true;
2392
+ }
2393
+ var dx = e.clientX - z.x0;
2394
+ var dy = e.clientY - z.y0;
2395
+ var w = z.dir.indexOf("e") >= 0 ? z.w0 + dx : z.dir.indexOf("w") >= 0 ? z.w0 - dx : z.w0;
2396
+ var h = z.dir.indexOf("s") >= 0 ? z.h0 + dy : z.dir.indexOf("n") >= 0 ? z.h0 - dy : z.h0;
2397
+ if (e.shiftKey && z.dir.length === 2) {
2398
+ var k = Math.max(w / z.w0, h / z.h0);
2399
+ w = z.w0 * k;
2400
+ h = z.h0 * k;
2401
+ }
2402
+ // The edge being pulled catches on what is around it (not with ⇧ keeping proportions; ⌘ goes freely).
2403
+ S.snaps = [];
2404
+ if (!e.shiftKey && !(e.metaKey || e.ctrlKey)) {
2405
+ var tg = snapTargets(z.el);
2406
+ var box = { left: z.r0.left, top: z.r0.top, right: z.r0.left + w, bottom: z.r0.top + h };
2407
+ if (z.dir.indexOf("e") >= 0) {
2408
+ var se = snapAxis([z.r0.left + w], tg.x);
2409
+ if (se) {
2410
+ w += se.d;
2411
+ box.right = z.r0.left + w;
2412
+ S.snaps.push(snapLine("x", se, box));
2413
+ }
2414
+ } else if (z.dir.indexOf("w") >= 0) {
2415
+ var sw = snapAxis([z.r0.right - w], tg.x);
2416
+ if (sw) {
2417
+ w -= sw.d;
2418
+ box.left = z.r0.right - w;
2419
+ S.snaps.push(snapLine("x", sw, box));
2420
+ }
2421
+ }
2422
+ if (z.dir.indexOf("s") >= 0) {
2423
+ var ss = snapAxis([z.r0.top + h], tg.y);
2424
+ if (ss) {
2425
+ h += ss.d;
2426
+ box.bottom = z.r0.top + h;
2427
+ S.snaps.push(snapLine("y", ss, box));
2428
+ }
2429
+ } else if (z.dir.indexOf("n") >= 0) {
2430
+ var sn = snapAxis([z.r0.bottom - h], tg.y);
2431
+ if (sn) {
2432
+ h -= sn.d;
2433
+ box.top = z.r0.bottom - h;
2434
+ S.snaps.push(snapLine("y", sn, box));
2435
+ }
2436
+ }
2437
+ }
2438
+ w = Math.max(1, Math.round(w));
2439
+ h = Math.max(1, Math.round(h));
2440
+ if (z.dir !== "n" && z.dir !== "s") {
2441
+ setProp(z.el, "width", w + "px");
2442
+ if (z.row === true) fixFlex(z.el);
2443
+ if (z.abs && z.dir.indexOf("w") >= 0) setProp(z.el, "left", Math.round(z.l0 + z.w0 - w) + "px");
2444
+ }
2445
+ if (z.dir !== "e" && z.dir !== "w") {
2446
+ setProp(z.el, "height", h + "px");
2447
+ if (z.row === false) fixFlex(z.el);
2448
+ if (z.abs && z.dir.indexOf("n") >= 0) setProp(z.el, "top", Math.round(z.t0 + z.h0 - h) + "px");
2449
+ }
2450
+ tip.textContent = w + " × " + h;
2451
+ show(tip, true);
2452
+ place(tip, e.clientX + 14, e.clientY + 14);
2453
+ report();
2454
+ }
2455
+ // A fixed size along a flex row or column only holds when the item neither grows nor starts from a basis.
2456
+ function fixFlex(el) {
2457
+ var cs = getComputedStyle(el);
2458
+ if (cs.flexGrow !== "0") setProp(el, "flex-grow", "0");
2459
+ if (cs.flexBasis !== "auto") setProp(el, "flex-basis", "auto");
2460
+ }
2461
+ function endResize(e) {
2462
+ var z = S.resize;
2463
+ if (!z) return;
2464
+ S.resize = null;
2465
+ try {
2466
+ z.node.releasePointerCapture(e.pointerId);
2467
+ } catch (x) {}
2468
+ show(tip, false);
2469
+ reportChanges();
2470
+ report();
2471
+ }
2472
+ shadow.addEventListener("pointermove", moveResize);
2473
+ shadow.addEventListener("pointerup", endResize);
2474
+ shadow.addEventListener("pointercancel", endResize);
2475
+
2476
+ /* ---------------------------------------------------------------- distances, held on ⌥ */
2477
+ // As Figma's: from what is picked to what the pointer is over, or to its parent's edges, in red with the px.
2478
+ function mline(x, y, w, h, n, tx, ty) {
2479
+ var l = div("ml");
2480
+ place(l, x, y, Math.max(1, w), Math.max(1, h));
2481
+ measureLayer.appendChild(l);
2482
+ var t = div("mtag");
2483
+ t.textContent = String(Math.round(n * 10) / 10);
2484
+ measureLayer.appendChild(t);
2485
+ place(t, tx, ty);
2486
+ }
2487
+ function drawMeasure() {
2488
+ measureLayer.textContent = "";
2489
+ var a0 = S.sel;
2490
+ if (!S.on || !S.alt || !a0 || !a0.isConnected || S.move || S.resize || S.editing) return;
2491
+ var other = S.hover && S.hover !== a0 && S.hover.isConnected ? S.hover : a0.parentElement;
2492
+ if (!other || other === document.documentElement) return;
2493
+ var a = a0.getBoundingClientRect();
2494
+ var b = other.getBoundingClientRect();
2495
+ var box = div("mbox");
2496
+ place(box, b.left, b.top, b.width, b.height);
2497
+ measureLayer.appendChild(box);
2498
+ var inside = function (p, q) {
2499
+ return q.left <= p.left && q.right >= p.right && q.top <= p.top && q.bottom >= p.bottom;
2500
+ };
2501
+ var inner = inside(a, b) ? a : inside(b, a) ? b : null;
2502
+ if (inner) {
2503
+ var outer = inner === a ? b : a;
2504
+ var cx = inner.left + inner.width / 2;
2505
+ var cy = inner.top + inner.height / 2;
2506
+ if (inner.left - outer.left > 0.5) mline(outer.left, cy, inner.left - outer.left, 1, inner.left - outer.left, outer.left + (inner.left - outer.left) / 2 - 10, cy + 4);
2507
+ if (outer.right - inner.right > 0.5) mline(inner.right, cy, outer.right - inner.right, 1, outer.right - inner.right, inner.right + (outer.right - inner.right) / 2 - 10, cy + 4);
2508
+ if (inner.top - outer.top > 0.5) mline(cx, outer.top, 1, inner.top - outer.top, inner.top - outer.top, cx + 4, outer.top + (inner.top - outer.top) / 2 - 8);
2509
+ if (outer.bottom - inner.bottom > 0.5) mline(cx, inner.bottom, 1, outer.bottom - inner.bottom, outer.bottom - inner.bottom, cx + 4, inner.bottom + (outer.bottom - inner.bottom) / 2 - 8);
2510
+ return;
2511
+ }
2512
+ var top = Math.max(a.top, b.top);
2513
+ var bottom = Math.min(a.bottom, b.bottom);
2514
+ var y = top < bottom ? (top + bottom) / 2 : a.top + a.height / 2;
2515
+ var left = Math.max(a.left, b.left);
2516
+ var right = Math.min(a.right, b.right);
2517
+ var x = left < right ? (left + right) / 2 : a.left + a.width / 2;
2518
+ if (b.left >= a.right) mline(a.right, y, b.left - a.right, 1, b.left - a.right, a.right + (b.left - a.right) / 2 - 10, y + 4);
2519
+ else if (b.right <= a.left) mline(b.right, y, a.left - b.right, 1, a.left - b.right, b.right + (a.left - b.right) / 2 - 10, y + 4);
2520
+ if (b.top >= a.bottom) mline(x, a.bottom, 1, b.top - a.bottom, b.top - a.bottom, x + 4, a.bottom + (b.top - a.bottom) / 2 - 8);
2521
+ else if (b.bottom <= a.top) mline(x, b.bottom, 1, a.top - b.bottom, a.top - b.bottom, x + 4, b.bottom + (a.top - b.bottom) / 2 - 8);
2522
+ }
2523
+
2524
+ /* ---------------------------------------------------------------- dragging a band */
2525
+ var spaceList = function () {
2526
+ return tokens().space;
2527
+ };
2528
+ function snap(px, free) {
2529
+ var v = Math.max(0, Math.round(px));
2530
+ if (free) return { value: v + "px", px: v, token: null };
2531
+ var best = null;
2532
+ var b = baseStep(spaceList());
2533
+ var candidates = spaceList().map(function (t) {
2534
+ return { value: "var(" + t.name + ")", px: t.px, token: t.name };
2535
+ }).concat(b ? STEPS.map(function (k) {
2536
+ return { value: "calc(var(" + b.name + ") * " + k + ")", px: b.px * k, token: b.name + " × " + k };
2537
+ }) : []);
2538
+ // Steps are closer together than tokens usually are: they catch within a quarter of a step, tokens within 6px.
2539
+ candidates.forEach(function (c) {
2540
+ var reach = b && c.token.indexOf("×") > 0 ? Math.min(6, b.px) : 6;
2541
+ if (Math.abs(c.px - px) <= reach && (!best || Math.abs(c.px - px) < Math.abs(best.px - px))) best = c;
2542
+ });
2543
+ return best || { value: v + "px", px: v, token: null };
2544
+ }
2545
+ function startDrag(e) {
2546
+ if (e.button !== 0) return;
2547
+ var b = e.currentTarget.__band;
2548
+ if (!b || !S.sel) return;
2549
+ e.preventDefault();
2550
+ e.stopPropagation();
2551
+ e.currentTarget.setPointerCapture(e.pointerId);
2552
+ S.drag = { b: b, prop: b.prop, el: S.sel, x0: e.clientX, y0: e.clientY, start: b.v, moved: false, node: e.currentTarget };
2553
+ }
2554
+ function moveDrag(e) {
2555
+ var d = S.drag;
2556
+ if (!d) return;
2557
+ var delta = d.b.axis === "y" ? e.clientY - d.y0 : e.clientX - d.x0;
2558
+ if (!d.moved && Math.abs(delta) < 3) return;
2559
+ if (!d.moved) record([d.el], null);
2560
+ d.moved = true;
2561
+ var s = snap(d.start + d.b.sign * delta, e.metaKey || e.ctrlKey);
2562
+ setProp(d.el, d.prop, s.value);
2563
+ tip.textContent = d.prop + " " + s.px + (s.token ? " " + s.token : "");
2564
+ show(tip, true);
2565
+ place(tip, e.clientX + 14, e.clientY + 14);
2566
+ report();
2567
+ }
2568
+ function endDrag(e) {
2569
+ var d = S.drag;
2570
+ if (!d) return;
2571
+ S.drag = null;
2572
+ try {
2573
+ d.node.releasePointerCapture(e.pointerId);
2574
+ } catch (x) {}
2575
+ if (d.moved) {
2576
+ reportChanges();
2577
+ report();
2578
+ return;
2579
+ }
2580
+ // A press that didn't move picks what is under it, as a click on the page would.
2581
+ host.style.display = "none";
2582
+ var under = document.elementFromPoint(e.clientX, e.clientY);
2583
+ host.style.display = "block";
2584
+ if (under && under !== document.documentElement) select(under, false);
2585
+ }
2586
+ shadow.addEventListener("pointermove", moveDrag);
2587
+ shadow.addEventListener("pointerup", endDrag);
2588
+ shadow.addEventListener("pointercancel", endDrag);
2589
+
2590
+ /* ---------------------------------------------------------------- guides */
2591
+ // A guide is pulled out of a ruler, moved, and put back on its ruler to go. It snaps to what is picked.
2592
+ function snapGuide(axis, v) {
2593
+ if (!S.sel || !S.sel.isConnected) return v;
2594
+ var r = S.sel.getBoundingClientRect();
2595
+ var sx = window.scrollX, sy = window.scrollY;
2596
+ var stops = axis === "x" ? [r.left + sx, r.left + r.width / 2 + sx, r.right + sx] : [r.top + sy, r.top + r.height / 2 + sy, r.bottom + sy];
2597
+ for (var i = 0; i < stops.length; i++) if (Math.abs(stops[i] - v) <= 5) return Math.round(stops[i] * 10) / 10;
2598
+ return Math.round(v);
2599
+ }
2600
+ function guideFrom(axis, n, e, node) {
2601
+ e.preventDefault();
2602
+ e.stopPropagation();
2603
+ node.setPointerCapture(e.pointerId);
2604
+ S.guideDrag = { axis: axis, n: n, node: node };
2605
+ }
2606
+ function grabGuide(e) {
2607
+ var g = e.currentTarget.__guide;
2608
+ if (g) guideFrom(g.axis, g.n, e, e.currentTarget);
2609
+ }
2610
+ topRuler.addEventListener("pointerdown", function (e) {
2611
+ S.guides.y.push(e.clientY + window.scrollY);
2612
+ guideFrom("y", S.guides.y.length - 1, e, topRuler);
2613
+ });
2614
+ leftRuler.addEventListener("pointerdown", function (e) {
2615
+ S.guides.x.push(e.clientX + window.scrollX);
2616
+ guideFrom("x", S.guides.x.length - 1, e, leftRuler);
2617
+ });
2618
+ corner.addEventListener("dblclick", function () {
2619
+ S.guides = { x: [], y: [] };
2620
+ });
2621
+ shadow.addEventListener("pointermove", function (e) {
2622
+ var g = S.guideDrag;
2623
+ if (!g) return;
2624
+ var v = g.axis === "x" ? snapGuide("x", e.clientX + window.scrollX) : snapGuide("y", e.clientY + window.scrollY);
2625
+ S.guides[g.axis][g.n] = v;
2626
+ tip.textContent = String(v);
2627
+ show(tip, true);
2628
+ place(tip, e.clientX + 14, e.clientY + 14);
2629
+ });
2630
+ function dropGuide(e) {
2631
+ var g = S.guideDrag;
2632
+ if (!g) return;
2633
+ S.guideDrag = null;
2634
+ try {
2635
+ g.node.releasePointerCapture(e.pointerId);
2636
+ } catch (x) {}
2637
+ // Back on its ruler (or off the window): it goes.
2638
+ var at = g.axis === "x" ? e.clientX : e.clientY;
2639
+ if (at < RS || at > (g.axis === "x" ? window.innerWidth : window.innerHeight)) S.guides[g.axis].splice(g.n, 1);
2640
+ }
2641
+ shadow.addEventListener("pointerup", dropGuide);
2642
+ shadow.addEventListener("pointercancel", dropGuide);
2643
+
2644
+ /* ---------------------------------------------------------------- hovers held still */
2645
+ // While editing, the page's :hover rules match nothing, so what is under the pointer looks as it does at rest.
2646
+ var held = [];
2647
+ function holdHovers(on) {
2648
+ if (on && !held.length) {
2649
+ eachRule(function (r) {
2650
+ if (r.selectorText && r.selectorText.indexOf(":hover") >= 0) {
2651
+ held.push([r, r.selectorText]);
2652
+ r.selectorText = r.selectorText.replace(/:hover/g, ":is(.__blockout-never)");
2653
+ }
2654
+ });
2655
+ } else if (!on && held.length) {
2656
+ held.forEach(function (h) {
2657
+ h[0].selectorText = h[1];
2658
+ });
2659
+ held = [];
2660
+ }
2661
+ }
2662
+
2663
+ /* ---------------------------------------------------------------- turning on and off */
2664
+ function setOn(on) {
2665
+ if (!on) stopText();
2666
+ S.on = on;
2667
+ holdHovers(on && S.block.hovers);
2668
+ if (!on) {
2669
+ S.hover = null;
2670
+ S.drag = null;
2671
+ }
2672
+ if (!frame) loop();
2673
+ report();
2674
+ }
2675
+
2676
+ /* ---------------------------------------------------------------- the panel's requests */
2677
+ function find(key) {
2678
+ var el = byKey.get(key);
2679
+ return el && el.isConnected ? el : null;
2680
+ }
2681
+ window.addEventListener("message", function (e) {
2682
+ var m = e.data;
2683
+ if (!m || m.blockoutEditor !== 1) return;
2684
+ // The canvas's frames speak from this page's own origin: what they say goes on to the panels (zooms and which frame
2685
+ // is being worked in, to the kit's canvas too).
2686
+ if (cfg.origin && !cfg.frame && (window.__blockoutEditorFrames || []).indexOf(e.source) >= 0) {
2687
+ if (m.type === "zoom" || m.type === "zoomKey" || m.type === "focus" || m.type === "changes" || m.type === "boot")
2688
+ window.dispatchEvent(new CustomEvent("blockout-editor:frame", { detail: { msg: m, from: e.source } }));
2689
+ if (relay && e.source === relay) send(m);
2690
+ return;
2691
+ }
2692
+ if (cfg.frame ? e.source !== window.parent || e.origin !== location.origin : cfg.origin ? e.origin !== cfg.origin : e.source !== window.parent) return;
2693
+ if (cfg.origin && !cfg.frame && peers.indexOf(e.source) < 0) peers.push(e.source);
2694
+ if (m.type === "on") panelOn = !!m.on;
2695
+ // The canvas is open: what the panels say is for the frame being worked in.
2696
+ if (relay) {
2697
+ relay.postMessage(m, location.origin);
2698
+ return;
2699
+ }
2700
+ var el;
2701
+ switch (m.type) {
2702
+ case "hello":
2703
+ tokenCache = null;
2704
+ send({ type: "ready", tokens: tokens() });
2705
+ reportChanges();
2706
+ report();
2707
+ break;
2708
+ case "on":
2709
+ setOn(!!m.on);
2710
+ break;
2711
+ case "rulers":
2712
+ S.rulers = !!m.on;
2713
+ break;
2714
+ case "block":
2715
+ S.block = { links: !!m.links, buttons: !!m.buttons, hovers: !!m.hovers };
2716
+ holdHovers(S.on && S.block.hovers);
2717
+ break;
2718
+ case "set":
2719
+ el = m.key ? find(m.key) : S.sel;
2720
+ if (!el) break;
2721
+ var targets = m.key ? [el] : picked();
2722
+ record(targets, "set:" + targets.map(keyOf).join("+") + ":" + Object.keys(m.values).sort().join(","));
2723
+ targets.forEach(function (x) {
2724
+ for (var p in m.values) setProp(x, p, m.values[p]);
2725
+ });
2726
+ // Hidden or shown from its layer: its row says so again.
2727
+ if (m.key && el.parentElement) send({ type: "children", key: el.parentElement === document.body ? null : keyOf(el.parentElement), nodes: layerKids(el.parentElement).slice(0, 400).map(layerOf) });
2728
+ reportChanges();
2729
+ report();
2730
+ break;
2731
+ case "reset":
2732
+ el = m.key ? find(m.key) : S.sel;
2733
+ var resetting = m.key ? (el ? [el] : []) : picked();
2734
+ if (m.all) record(Array.from(originals.keys()), null);
2735
+ else if (resetting.length) record(resetting, null);
2736
+ if (m.all) originals.forEach(function (o, x) {
2737
+ resetEl(x);
2738
+ });
2739
+ else resetting.forEach(function (x) {
2740
+ if (m.props) resetProps(x, m.props);
2741
+ else resetEl(x);
2742
+ });
2743
+ reportChanges();
2744
+ report();
2745
+ break;
2746
+ case "select":
2747
+ if (Array.isArray(m.keys) && m.keys.length) {
2748
+ var many = m.keys.map(find).filter(Boolean);
2749
+ select(many[0] || null, true);
2750
+ S.extra = many.slice(1);
2751
+ report();
2752
+ break;
2753
+ }
2754
+ el = find(m.key);
2755
+ if (el) select(el, true);
2756
+ else if (m.key === null) select(null);
2757
+ break;
2758
+ case "nav":
2759
+ nav(m.to);
2760
+ break;
2761
+ case "detach":
2762
+ if (S.sel) record([S.sel], null);
2763
+ if (S.sel) detach(S.sel);
2764
+ reportChanges();
2765
+ report();
2766
+ break;
2767
+ case "type":
2768
+ if (S.sel) record([S.sel], null);
2769
+ if (S.sel) applyType(S.sel, m.name || null);
2770
+ reportChanges();
2771
+ report();
2772
+ break;
2773
+ case "clearGuides":
2774
+ S.guides = { x: [], y: [] };
2775
+ break;
2776
+ case "absolute":
2777
+ if (!S.sel) break;
2778
+ record(picked(), null);
2779
+ picked().forEach(function (x) {
2780
+ setAbsolute(x, !!m.on);
2781
+ });
2782
+ reportChanges();
2783
+ report();
2784
+ break;
2785
+ case "mirror":
2786
+ mirror(m.changes || []);
2787
+ break;
2788
+ case "editText":
2789
+ if (S.sel) startText(S.sel, true);
2790
+ break;
2791
+ case "children":
2792
+ el = m.key ? find(m.key) : document.body;
2793
+ send({ type: "children", key: m.key || null, nodes: el ? layerKids(el).slice(0, 400).map(layerOf) : [] });
2794
+ break;
2795
+ case "hover":
2796
+ S.hover = m.key ? find(m.key) : null;
2797
+ break;
2798
+ case "undo":
2799
+ step(past, future);
2800
+ break;
2801
+ case "duplicate":
2802
+ duplicate();
2803
+ break;
2804
+ case "move":
2805
+ // From the layers: before or after a row, or into it.
2806
+ el = find(m.key);
2807
+ var target = find(m.target);
2808
+ if (!el || !target || target === el || el.contains(target)) break;
2809
+ if (m.position === "on") moveEl(el, target, null);
2810
+ else moveEl(el, target.parentElement, m.position === "before" ? target : target.nextSibling);
2811
+ select(el, false);
2812
+ reportChanges();
2813
+ break;
2814
+ case "copy":
2815
+ copySel();
2816
+ break;
2817
+ case "paste":
2818
+ paste();
2819
+ break;
2820
+ case "redo":
2821
+ step(future, past);
2822
+ break;
2823
+ case "saved":
2824
+ // What was changed is now the page's own: nothing to undo or save.
2825
+ originals.clear();
2826
+ past = [];
2827
+ future = [];
2828
+ reportChanges();
2829
+ report();
2830
+ break;
2831
+ }
2832
+ });
2833
+ window.addEventListener("load", function () {
2834
+ tokenCache = null;
2835
+ send({ type: "tokens", tokens: tokens() });
2836
+ });
2837
+ // Here: the panel answers with hello, and the page's tokens go back once its stylesheets are in.
2838
+ send({ type: "boot" });
2839
+ })();