shatter-morph 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1217 @@
1
+ // src/core/settings.ts
2
+ var enabled = true;
3
+ function setShatterEnabled(value) {
4
+ enabled = value;
5
+ }
6
+ function isShatterEnabled() {
7
+ return enabled;
8
+ }
9
+ function prefersReducedMotion() {
10
+ return typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
11
+ }
12
+
13
+ // src/core/motion.ts
14
+ var TAU = Math.PI * 2;
15
+ var SWEEP_SHARE = 0.42;
16
+ var JITTER_SHARE = 0.12;
17
+ var FLIGHT_SHARE = 1 - SWEEP_SHARE - JITTER_SHARE;
18
+ var clamp01 = (value) => Math.min(Math.max(value, 0), 1);
19
+ var mix = (from, to, amount) => from + (to - from) * amount;
20
+ function smoothstep(start, end, value) {
21
+ const x = clamp01((value - start) / (end - start));
22
+ return x * x * (3 - 2 * x);
23
+ }
24
+ function launchDelay(center, origin, jitter) {
25
+ let distance;
26
+ if (origin === "left") distance = center.x;
27
+ else if (origin === "right") distance = 1 - center.x;
28
+ else if (origin === "top") distance = center.y;
29
+ else if (origin === "bottom") distance = 1 - center.y;
30
+ else distance = clamp01(Math.hypot(center.x - 0.5, center.y - 0.5) / Math.SQRT1_2);
31
+ return clamp01(distance) * SWEEP_SHARE + clamp01(jitter) * JITTER_SHARE;
32
+ }
33
+ function flightProgress(time, delay) {
34
+ return smoothstep(0, FLIGHT_SHARE, time - delay);
35
+ }
36
+ function flightWeight(progress) {
37
+ return smoothstep(0, 0.2, progress) * (1 - smoothstep(0.8, 1, progress));
38
+ }
39
+ function flightPoint(motion, progress, seed, radius) {
40
+ const arc = Math.sin(Math.PI * progress);
41
+ if (motion === "burst") {
42
+ const angle2 = seed.a * TAU;
43
+ const tilt = (seed.b - 0.5) * Math.PI;
44
+ const reach2 = radius * (0.55 + seed.c * 0.75) * arc;
45
+ return {
46
+ x: Math.cos(angle2) * Math.cos(tilt) * reach2,
47
+ y: Math.sin(tilt) * reach2 * 0.8,
48
+ z: Math.sin(angle2) * Math.cos(tilt) * reach2 * 0.7
49
+ };
50
+ }
51
+ if (motion === "fall") {
52
+ const drop = progress < 0.5 ? (progress * 2) ** 2 : -(((1 - progress) * 2) ** 2);
53
+ return {
54
+ x: (seed.a - 0.5) * radius * 1.1 * arc,
55
+ y: drop * radius * 1.35 + (seed.b - 0.5) * radius * 0.25 * arc,
56
+ z: (seed.c - 0.5) * radius * 0.6 * arc
57
+ };
58
+ }
59
+ const angle = progress * TAU * 1.08 - 0.62;
60
+ const reach = radius * (0.82 + 0.18 * arc);
61
+ const tube = radius * 0.2 * (0.35 + arc);
62
+ return {
63
+ x: Math.cos(angle) * reach * 1.04 + (seed.b - 0.5) * tube,
64
+ y: -Math.sin(angle) * reach * 0.86 + (seed.c - 0.5) * tube,
65
+ z: Math.sin(angle + 0.9) * reach * 0.6 + (seed.d - 0.5) * tube * 1.4
66
+ };
67
+ }
68
+ function midpointFade(motion, progress) {
69
+ return motion === "fall" ? smoothstep(0, 0.12, Math.abs(progress - 0.5)) : 1;
70
+ }
71
+
72
+ // src/core/debris.ts
73
+ var MAX_PIXEL_RATIO = 1.5;
74
+ function createMotes(count, options, sizeOf) {
75
+ const { frame, origin, random } = options;
76
+ const motes = [];
77
+ for (let index = 0; index < count; index += 1) {
78
+ const seed = { a: random(), b: random(), c: random(), d: random() };
79
+ const unit = { x: random(), y: random() };
80
+ motes.push({
81
+ x: frame.left + unit.x * frame.width,
82
+ y: frame.top + unit.y * frame.height,
83
+ delay: launchDelay(unit, origin, seed.a),
84
+ size: sizeOf(seed),
85
+ seed
86
+ });
87
+ }
88
+ return motes;
89
+ }
90
+ function createMistSprite(color) {
91
+ const sprite = document.createElement("canvas");
92
+ sprite.width = 96;
93
+ sprite.height = 96;
94
+ const context = sprite.getContext("2d");
95
+ if (!context) return null;
96
+ const gradient = context.createRadialGradient(48, 48, 0, 48, 48, 48);
97
+ gradient.addColorStop(0, color);
98
+ gradient.addColorStop(1, "rgba(0, 0, 0, 0)");
99
+ context.fillStyle = gradient;
100
+ context.fillRect(0, 0, 96, 96);
101
+ return sprite;
102
+ }
103
+ function createDebris(options) {
104
+ const { canvas, color, motion, radius, perspective, center, frame } = options;
105
+ const context = canvas.getContext("2d");
106
+ if (!context) return null;
107
+ const pixelRatio = Math.min(window.devicePixelRatio || 1, MAX_PIXEL_RATIO);
108
+ const width = window.innerWidth;
109
+ const height = window.innerHeight;
110
+ canvas.width = Math.round(width * pixelRatio);
111
+ canvas.height = Math.round(height * pixelRatio);
112
+ const scale = Math.max(frame.width, frame.height);
113
+ const dust = createMotes(options.dust, options, (seed) => Math.max(scale * 4e-3, 1.2) * (0.6 + seed.d));
114
+ const mist = createMotes(options.mist, options, (seed) => scale * (0.24 + seed.d * 0.26));
115
+ const sprite = mist.length ? createMistSprite(color) : null;
116
+ const place = (mote, time) => {
117
+ const progress = flightProgress(time, mote.delay);
118
+ const weight = flightWeight(progress);
119
+ if (weight <= 0.01) return null;
120
+ const point = flightPoint(motion, progress, mote.seed, radius);
121
+ const x = mix(mote.x, center.x + point.x, weight);
122
+ const y = mix(mote.y, center.y + point.y, weight);
123
+ const depth = perspective / Math.max(perspective - point.z * weight, 1);
124
+ return {
125
+ x: center.x + (x - center.x) * depth,
126
+ y: center.y + (y - center.y) * depth,
127
+ size: mote.size * depth,
128
+ weight
129
+ };
130
+ };
131
+ return {
132
+ draw(time, offsetX, offsetY) {
133
+ context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
134
+ context.clearRect(0, 0, width, height);
135
+ context.translate(offsetX, offsetY);
136
+ context.globalCompositeOperation = "lighter";
137
+ if (sprite) {
138
+ for (const mote of mist) {
139
+ const placed = place(mote, time);
140
+ if (!placed) continue;
141
+ context.globalAlpha = placed.weight * 0.16;
142
+ context.drawImage(sprite, placed.x - placed.size / 2, placed.y - placed.size / 2, placed.size, placed.size);
143
+ }
144
+ }
145
+ context.fillStyle = color;
146
+ for (const mote of dust) {
147
+ const placed = place(mote, time);
148
+ if (!placed) continue;
149
+ context.globalAlpha = placed.weight * (0.35 + mote.seed.b * 0.65);
150
+ context.fillRect(placed.x, placed.y, placed.size, placed.size);
151
+ }
152
+ context.globalAlpha = 1;
153
+ }
154
+ };
155
+ }
156
+
157
+ // src/core/fracture.ts
158
+ var MIN_AREA = 1e-6;
159
+ function createSites(width, height, count, random) {
160
+ const columns = Math.max(Math.round(Math.sqrt(count * width / height)), 1);
161
+ const rows = Math.max(Math.round(count / columns), 1);
162
+ const cellWidth = width / columns;
163
+ const cellHeight = height / rows;
164
+ const sites = [];
165
+ const addSite = (column, row) => {
166
+ sites.push({
167
+ x: (column + 0.04 + random() * 0.92) * cellWidth,
168
+ y: (row + 0.04 + random() * 0.92) * cellHeight
169
+ });
170
+ };
171
+ for (let row = 0; row < rows; row += 1) {
172
+ for (let column = 0; column < columns; column += 1) {
173
+ if (random() < 0.86) addSite(column, row);
174
+ if (random() < 0.2) addSite(column, row);
175
+ }
176
+ }
177
+ if (sites.length === 0) sites.push({ x: width / 2, y: height / 2 });
178
+ return sites;
179
+ }
180
+ function clip(polygon, mid, normal) {
181
+ const clipped = [];
182
+ polygon.forEach((current, index) => {
183
+ const next = polygon[(index + 1) % polygon.length] ?? current;
184
+ const currentSide = (current.x - mid.x) * normal.x + (current.y - mid.y) * normal.y;
185
+ const nextSide = (next.x - mid.x) * normal.x + (next.y - mid.y) * normal.y;
186
+ if (currentSide <= 0) clipped.push(current);
187
+ if (currentSide < 0 && nextSide > 0 || currentSide > 0 && nextSide < 0) {
188
+ const amount = currentSide / (currentSide - nextSide);
189
+ clipped.push({
190
+ x: current.x + (next.x - current.x) * amount,
191
+ y: current.y + (next.y - current.y) * amount
192
+ });
193
+ }
194
+ });
195
+ return clipped;
196
+ }
197
+ function reachOf(polygon, site) {
198
+ let reach = 0;
199
+ for (const point of polygon) reach = Math.max(reach, Math.hypot(point.x - site.x, point.y - site.y));
200
+ return reach;
201
+ }
202
+ function createCell(outline, site, sites) {
203
+ let polygon = outline;
204
+ let reach = reachOf(polygon, site);
205
+ for (const other of sites) {
206
+ if (other === site) continue;
207
+ const normal = { x: other.x - site.x, y: other.y - site.y };
208
+ if (Math.hypot(normal.x, normal.y) / 2 > reach) continue;
209
+ polygon = clip(polygon, { x: (site.x + other.x) / 2, y: (site.y + other.y) / 2 }, normal);
210
+ if (polygon.length < 3) return [];
211
+ reach = reachOf(polygon, site);
212
+ }
213
+ return polygon;
214
+ }
215
+ function measure(polygon) {
216
+ let doubled = 0;
217
+ let x = 0;
218
+ let y = 0;
219
+ polygon.forEach((current, index) => {
220
+ const next = polygon[(index + 1) % polygon.length] ?? current;
221
+ const cross = current.x * next.y - next.x * current.y;
222
+ doubled += cross;
223
+ x += (current.x + next.x) * cross;
224
+ y += (current.y + next.y) * cross;
225
+ });
226
+ if (doubled === 0) return { center: { x: 0, y: 0 }, area: 0 };
227
+ return {
228
+ center: { x: x / (3 * doubled), y: y / (3 * doubled) },
229
+ area: Math.abs(doubled) / 2
230
+ };
231
+ }
232
+ function fracture(width, height, count, random) {
233
+ const outline = [
234
+ { x: 0, y: 0 },
235
+ { x: width, y: 0 },
236
+ { x: width, y: height },
237
+ { x: 0, y: height }
238
+ ];
239
+ const sites = createSites(width, height, Math.max(count, 1), random);
240
+ const total = width * height;
241
+ const shards = [];
242
+ for (const site of sites) {
243
+ const polygon = createCell(outline, site, sites);
244
+ if (polygon.length < 3) continue;
245
+ const { center, area } = measure(polygon);
246
+ if (area / total < MIN_AREA) continue;
247
+ shards.push({
248
+ points: polygon.map((point) => ({ x: point.x / width, y: point.y / height })),
249
+ center: { x: center.x / width, y: center.y / height },
250
+ area: area / total
251
+ });
252
+ }
253
+ return shards;
254
+ }
255
+
256
+ // src/core/overlay.ts
257
+ var STAGE_RULES = ".stage{position:fixed;inset:0;pointer-events:none;transform-style:preserve-3d;}.piece{position:absolute;transform-style:preserve-3d;will-change:transform,opacity;}.edge,.face{position:absolute;inset:0;}.edge{opacity:0;}.face{overflow:hidden;}.content{position:absolute;}.shade{position:absolute;inset:0;opacity:0;background:linear-gradient(135deg,rgba(255,255,255,.62),rgba(255,255,255,.08));}.line{position:absolute;inset:0;width:100%;height:100%;overflow:visible;opacity:0;}.line path{fill:none;stroke-width:1;vector-effect:non-scaling-stroke;}.debris{position:fixed;inset:0;width:100%;height:100%;}.definitions{position:absolute;width:0;height:0;overflow:hidden;}";
258
+ function applyRules(root, rules) {
259
+ if (typeof CSSStyleSheet !== "undefined" && "adoptedStyleSheets" in root && "replaceSync" in CSSStyleSheet.prototype) {
260
+ const sheet = new CSSStyleSheet();
261
+ sheet.replaceSync(rules);
262
+ root.adoptedStyleSheets = [sheet];
263
+ return;
264
+ }
265
+ const style = document.createElement("style");
266
+ style.textContent = rules;
267
+ root.appendChild(style);
268
+ }
269
+ function createHost(zIndex) {
270
+ const host = document.createElement("div");
271
+ host.setAttribute("data-shatter-morph", "");
272
+ host.setAttribute("aria-hidden", "true");
273
+ host.setAttribute("inert", "");
274
+ host.style.cssText = `position:fixed;inset:0;width:100vw;height:100vh;max-width:none;max-height:none;margin:0;padding:0;border:0;background:transparent;overflow:visible;pointer-events:none;z-index:${zIndex};`;
275
+ if ("popover" in host) host.setAttribute("popover", "manual");
276
+ document.documentElement.appendChild(host);
277
+ try {
278
+ host.showPopover?.();
279
+ } catch {
280
+ host.removeAttribute("popover");
281
+ }
282
+ return host;
283
+ }
284
+ function createOverlay(zIndex, rules) {
285
+ const host = createHost(zIndex);
286
+ const shadow = host.attachShadow({ mode: "open" });
287
+ applyRules(shadow, STAGE_RULES + rules);
288
+ const stage = document.createElement("div");
289
+ stage.className = "stage";
290
+ shadow.appendChild(stage);
291
+ return { host, shadow, stage };
292
+ }
293
+ function resolveColor(host, color, fallback) {
294
+ host.style.color = fallback;
295
+ host.style.color = color;
296
+ return getComputedStyle(host).color || fallback;
297
+ }
298
+
299
+ // src/core/clone.ts
300
+ var SCROLL_ATTRIBUTE = "data-shatter-scroll";
301
+ var HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
302
+ var SVG_NAMESPACE = "http://www.w3.org/2000/svg";
303
+ var DROPPED_TAGS = /* @__PURE__ */ new Set(["script", "style", "link", "meta", "base", "noscript", "template"]);
304
+ var PLACEHOLDER_TAGS = /* @__PURE__ */ new Set(["iframe", "embed", "object", "audio", "frame", "slot"]);
305
+ var FORM_CONTROLS = /* @__PURE__ */ new Set(["button", "input", "meter", "progress", "select", "textarea"]);
306
+ var BLOCKED_ATTRIBUTES = /* @__PURE__ */ new Set([
307
+ "accesskey",
308
+ "action",
309
+ "autofocus",
310
+ "autoplay",
311
+ "class",
312
+ "contenteditable",
313
+ "draggable",
314
+ "form",
315
+ "formaction",
316
+ "id",
317
+ "is",
318
+ "name",
319
+ "nonce",
320
+ "ping",
321
+ "popover",
322
+ "popovertarget",
323
+ "sizes",
324
+ "slot",
325
+ "srcset",
326
+ "style",
327
+ "tabindex",
328
+ "target"
329
+ ]);
330
+ var SKIPPED_PROPERTY = /^(?:animation|transition|will-change|view-transition|view-timeline|scroll-timeline|anchor-name|position-anchor|contain|content-visibility|pointer-events)/;
331
+ var CONTROL_PAINT = /^(?:background|border)/;
332
+ var TEXT_FILL = "-webkit-text-fill-color";
333
+ var URL_REFERENCE = /url\((["']?)#([^"')]+)\1\)/g;
334
+ var LOOK_PROPERTIES = [
335
+ "background-color",
336
+ "background-image",
337
+ "border-top-color",
338
+ "border-top-style",
339
+ "border-top-width",
340
+ "border-top-left-radius"
341
+ ];
342
+ var TEXT_PROPERTIES = [
343
+ "color",
344
+ "content",
345
+ "font-family",
346
+ "font-size",
347
+ "font-style",
348
+ "font-weight",
349
+ "letter-spacing",
350
+ "opacity",
351
+ "text-transform"
352
+ ];
353
+ var PAINT_PROPERTIES = ["fill", "stroke", "stroke-width", "fill-opacity", "stroke-opacity", "opacity"];
354
+ var defaultLooks = /* @__PURE__ */ new Map();
355
+ function createBuild(prefix) {
356
+ return {
357
+ prefix,
358
+ classes: /* @__PURE__ */ new Map(),
359
+ rules: [],
360
+ bitmaps: [],
361
+ references: /* @__PURE__ */ new Map(),
362
+ scopes: /* @__PURE__ */ new Map(),
363
+ nodeCount: 0
364
+ };
365
+ }
366
+ function drawInto(canvas, image) {
367
+ try {
368
+ canvas.getContext("2d")?.drawImage(image, 0, 0, canvas.width, canvas.height);
369
+ } catch {
370
+ return;
371
+ }
372
+ }
373
+ function hasIdLookup(node) {
374
+ return "getElementById" in node;
375
+ }
376
+ function referenceTo(id, source, build, isInstanced) {
377
+ const root = source.getRootNode();
378
+ let scope = build.scopes.get(root);
379
+ if (scope === void 0) {
380
+ scope = build.scopes.size;
381
+ build.scopes.set(root, scope);
382
+ }
383
+ const scopedId = `${build.prefix}${scope}-${id}`;
384
+ if (hasIdLookup(root) && !build.references.has(scopedId)) {
385
+ build.references.set(scopedId, { id, root, isInstanced });
386
+ }
387
+ return scopedId;
388
+ }
389
+ function scopeUrls(text, source, build) {
390
+ return text.replace(
391
+ URL_REFERENCE,
392
+ (_match, _quote, id) => `url("#${referenceTo(id, source, build, false)}")`
393
+ );
394
+ }
395
+ function scopeAttribute(source, name, value, build) {
396
+ if (name !== "href" && name !== "xlink:href") return scopeUrls(value, source, build);
397
+ if (!value.startsWith("#")) return value;
398
+ return `#${referenceTo(value.slice(1), source, build, source.localName === "use")}`;
399
+ }
400
+ function styleText(style, skipped = null) {
401
+ let text = "";
402
+ for (let index = 0; index < style.length; index += 1) {
403
+ const name = style.item(index);
404
+ if (SKIPPED_PROPERTY.test(name) || skipped?.test(name)) continue;
405
+ const value = style.getPropertyValue(name);
406
+ if (!value || name === TEXT_FILL && value === style.getPropertyValue("color")) continue;
407
+ text += `${name}:${value};`;
408
+ }
409
+ return text;
410
+ }
411
+ function textStyle(source, pseudo) {
412
+ const style = getComputedStyle(source, pseudo);
413
+ return TEXT_PROPERTIES.map((name) => {
414
+ const value = style.getPropertyValue(name);
415
+ return value ? `${name}:${value};` : "";
416
+ }).join("");
417
+ }
418
+ function pseudoRules(source, style, build) {
419
+ const rules = [];
420
+ for (const pseudo of ["::before", "::after"]) {
421
+ const computed = getComputedStyle(source, pseudo);
422
+ const content = computed.getPropertyValue("content");
423
+ if (content && content !== "none" && content !== "normal") {
424
+ rules.push([pseudo, scopeUrls(styleText(computed), source, build)]);
425
+ }
426
+ }
427
+ if (style.display === "list-item") rules.push(["::marker", textStyle(source, "::marker")]);
428
+ if (source.hasAttribute("placeholder")) rules.push(["::placeholder", textStyle(source, "::placeholder")]);
429
+ return rules;
430
+ }
431
+ function lookOf(style) {
432
+ return LOOK_PROPERTIES.map((name) => style.getPropertyValue(name)).join("|");
433
+ }
434
+ function defaultLook(source, colorScheme) {
435
+ const type = source.getAttribute("type") ?? "";
436
+ const key = `${source.localName}:${type}:${colorScheme}`;
437
+ const known = defaultLooks.get(key);
438
+ if (known !== void 0) return known;
439
+ const host = document.createElement("div");
440
+ host.style.display = "none";
441
+ host.style.colorScheme = colorScheme;
442
+ const probe = document.createElement(source.localName);
443
+ if (type) probe.setAttribute("type", type);
444
+ host.attachShadow({ mode: "open" }).appendChild(probe);
445
+ document.documentElement.appendChild(host);
446
+ const look = lookOf(getComputedStyle(probe));
447
+ host.remove();
448
+ defaultLooks.set(key, look);
449
+ return look;
450
+ }
451
+ function hasNativeLook(source, style) {
452
+ return FORM_CONTROLS.has(source.localName) && style.appearance !== "none" && lookOf(style) === defaultLook(source, style.colorScheme);
453
+ }
454
+ function classFor(source, isHtml, build) {
455
+ const style = getComputedStyle(source);
456
+ const skipped = isHtml && hasNativeLook(source, style) ? CONTROL_PAINT : null;
457
+ const base = scopeUrls(styleText(style, skipped), source, build);
458
+ const pseudos = pseudoRules(source, style, build);
459
+ const key = `${base}|${pseudos.join("|")}`;
460
+ const existing = build.classes.get(key);
461
+ if (existing) return existing;
462
+ const name = `${build.prefix}${build.classes.size}`;
463
+ build.classes.set(key, name);
464
+ build.rules.push(`.${name}{${base}}`);
465
+ for (const [pseudo, text] of pseudos) build.rules.push(`.${name}${pseudo}{${text}}`);
466
+ return name;
467
+ }
468
+ function copyOwnPaint(source, copy) {
469
+ const own = getComputedStyle(source);
470
+ const parent = source.parentElement ? getComputedStyle(source.parentElement) : null;
471
+ for (const name of PAINT_PROPERTIES) {
472
+ const value = own.getPropertyValue(name);
473
+ if (value && value !== parent?.getPropertyValue(name)) copy.style.setProperty(name, value);
474
+ }
475
+ }
476
+ function copyBitmap(source) {
477
+ const isVideo = source.localName === "video";
478
+ const width = isVideo ? source.videoWidth : source.width;
479
+ const height = isVideo ? source.videoHeight : source.height;
480
+ const bitmap = document.createElement("canvas");
481
+ bitmap.width = width || 1;
482
+ bitmap.height = height || 1;
483
+ if (width && height) drawInto(bitmap, source);
484
+ return bitmap;
485
+ }
486
+ function isBlockedAttribute(element, name, isHtml) {
487
+ if (name.startsWith("on") || BLOCKED_ATTRIBUTES.has(name)) return true;
488
+ const isLink = element.localName === "a" || element.localName === "area";
489
+ if (isLink && (name === "href" || name === "xlink:href")) return true;
490
+ return isHtml && name === "loading";
491
+ }
492
+ function copyAttributes(source, copy, isHtml, build) {
493
+ for (const attribute of Array.from(source.attributes)) {
494
+ const name = attribute.name.toLowerCase();
495
+ if (isBlockedAttribute(source, name, isHtml)) continue;
496
+ const value = isHtml ? attribute.value : scopeAttribute(source, name, attribute.value, build);
497
+ try {
498
+ copy.setAttributeNS(attribute.namespaceURI, attribute.name, value);
499
+ } catch {
500
+ continue;
501
+ }
502
+ }
503
+ }
504
+ function copyFormState(source, copy) {
505
+ if (source.localName === "input") {
506
+ const input = source;
507
+ const value = input.type === "password" ? "x".repeat(input.value.length) : input.value;
508
+ if (input.type !== "file") copy.setAttribute("value", value);
509
+ copy.toggleAttribute("checked", input.checked);
510
+ } else if (source.localName === "option") {
511
+ copy.toggleAttribute("selected", source.selected);
512
+ } else if (source.localName === "img") {
513
+ const image = source;
514
+ if (image.currentSrc) copy.setAttribute("src", image.currentSrc);
515
+ copy.setAttribute("decoding", "sync");
516
+ }
517
+ }
518
+ function childrenOf(source) {
519
+ if (source.shadowRoot) return Array.from(source.shadowRoot.childNodes);
520
+ if (source.localName === "slot") {
521
+ const assigned = source.assignedNodes();
522
+ if (assigned.length) return assigned;
523
+ }
524
+ return Array.from(source.childNodes);
525
+ }
526
+ function createCopy(source, isHtml, build) {
527
+ const tag = source.localName;
528
+ if (isHtml && (tag === "canvas" || tag === "video")) {
529
+ const bitmap = copyBitmap(source);
530
+ build.bitmaps.push(bitmap);
531
+ const copy = document.createElement("canvas");
532
+ copy.width = bitmap.width;
533
+ copy.height = bitmap.height;
534
+ return copy;
535
+ }
536
+ if (isHtml && (PLACEHOLDER_TAGS.has(tag) || tag.includes("-"))) return document.createElement("div");
537
+ return document.createElementNS(source.namespaceURI, source.localName);
538
+ }
539
+ function copyChildren(source, copy, build, isStyled) {
540
+ for (const child of childrenOf(source)) {
541
+ if (child.nodeType === Node.TEXT_NODE) {
542
+ copy.appendChild(document.createTextNode(child.nodeValue ?? ""));
543
+ build.nodeCount += 1;
544
+ } else if (child.nodeType === Node.ELEMENT_NODE) {
545
+ const childCopy = cloneElement(child, build, isStyled);
546
+ if (childCopy) copy.appendChild(childCopy);
547
+ }
548
+ }
549
+ }
550
+ function cloneElement(source, build, isStyled = true) {
551
+ const tag = source.localName;
552
+ if (DROPPED_TAGS.has(tag)) return null;
553
+ const isHtml = source.namespaceURI === HTML_NAMESPACE;
554
+ const copy = createCopy(source, isHtml, build);
555
+ if (copy.localName === tag) {
556
+ copyAttributes(source, copy, isHtml, build);
557
+ if (isHtml) copyFormState(source, copy);
558
+ }
559
+ if (isStyled) copy.setAttribute("class", classFor(source, isHtml, build));
560
+ else copyOwnPaint(source, copy);
561
+ build.nodeCount += 1;
562
+ if (source.scrollLeft || source.scrollTop) {
563
+ copy.setAttribute(SCROLL_ATTRIBUTE, `${source.scrollLeft},${source.scrollTop}`);
564
+ }
565
+ if (tag === "textarea") {
566
+ copy.textContent = source.value;
567
+ } else if (tag !== "canvas" && tag !== "video" && !(isHtml && PLACEHOLDER_TAGS.has(tag) && tag !== "slot")) {
568
+ copyChildren(source, copy, build, isStyled);
569
+ }
570
+ return copy;
571
+ }
572
+ function createDefinitions(build) {
573
+ const holder = document.createElementNS(SVG_NAMESPACE, "svg");
574
+ holder.setAttribute("class", "definitions");
575
+ for (const [scopedId, reference] of build.references) {
576
+ const target = reference.root.getElementById(reference.id);
577
+ const copy = target && cloneElement(target, build, !reference.isInstanced);
578
+ if (!copy) continue;
579
+ copy.setAttribute("id", scopedId);
580
+ holder.appendChild(copy);
581
+ }
582
+ return holder.childElementCount ? holder : null;
583
+ }
584
+
585
+ // src/core/visibility.ts
586
+ var VEIL = {
587
+ transition: "none",
588
+ visibility: "hidden",
589
+ "clip-path": "inset(50%)"
590
+ };
591
+ var VEIL_PROPERTIES = Object.keys(VEIL);
592
+ var VISUAL_PROPERTIES = ["visibility", "clip-path"];
593
+ var veils = /* @__PURE__ */ new WeakMap();
594
+ var forcedDisplay = /* @__PURE__ */ new WeakMap();
595
+ function styleOf(element) {
596
+ return element.style;
597
+ }
598
+ function save(style, name) {
599
+ return { value: style.getPropertyValue(name), priority: style.getPropertyPriority(name) };
600
+ }
601
+ function restore(element, style, name, saved) {
602
+ if (saved.value) style.setProperty(name, saved.value, saved.priority);
603
+ else style.removeProperty(name);
604
+ if (element.getAttribute("style") === "") element.removeAttribute("style");
605
+ }
606
+ function applyVeil(style) {
607
+ for (const name of VEIL_PROPERTIES) style.setProperty(name, VEIL[name], "important");
608
+ }
609
+ function liftVeil(element, style, saved) {
610
+ for (const name of VISUAL_PROPERTIES) restore(element, style, name, saved[name]);
611
+ }
612
+ function veil(element) {
613
+ const style = styleOf(element);
614
+ if (!style || veils.has(element)) return;
615
+ veils.set(element, {
616
+ transition: save(style, "transition"),
617
+ visibility: save(style, "visibility"),
618
+ "clip-path": save(style, "clip-path")
619
+ });
620
+ applyVeil(style);
621
+ }
622
+ function unveil(element) {
623
+ const style = styleOf(element);
624
+ const saved = veils.get(element);
625
+ if (!style || !saved) return;
626
+ veils.delete(element);
627
+ liftVeil(element, style, saved);
628
+ void getComputedStyle(element).visibility;
629
+ restore(element, style, "transition", saved.transition);
630
+ }
631
+ function withoutVeil(element, read) {
632
+ const style = styleOf(element);
633
+ const saved = veils.get(element);
634
+ if (!style || !saved) return read();
635
+ liftVeil(element, style, saved);
636
+ try {
637
+ return read();
638
+ } finally {
639
+ applyVeil(style);
640
+ }
641
+ }
642
+ function conceal(element) {
643
+ element.setAttribute("hidden", "");
644
+ const style = styleOf(element);
645
+ if (!style || forcedDisplay.has(element)) return;
646
+ if (getComputedStyle(element).display === "none") return;
647
+ forcedDisplay.set(element, save(style, "display"));
648
+ style.setProperty("display", "none", "important");
649
+ }
650
+ function reveal(element) {
651
+ element.removeAttribute("hidden");
652
+ const style = styleOf(element);
653
+ const saved = forcedDisplay.get(element);
654
+ if (!style || !saved) return;
655
+ forcedDisplay.delete(element);
656
+ restore(element, style, "display", saved);
657
+ }
658
+
659
+ // src/core/snapshot.ts
660
+ var IDENTITY_TRANSFORMS = /* @__PURE__ */ new Set([
661
+ "none",
662
+ "matrix(1, 0, 0, 1, 0, 0)",
663
+ "matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)"
664
+ ]);
665
+ var snapshotCount = 0;
666
+ function withoutTranslation(transform) {
667
+ const match = /^matrix(3d)?\((.+)\)$/.exec(transform);
668
+ if (!match?.[2]) return transform || "none";
669
+ const parts = match[2].split(",").map((part) => part.trim());
670
+ const offsets = match[1] ? [12, 13, 14] : [4, 5];
671
+ for (const index of offsets) parts[index] = "0";
672
+ return `matrix${match[1] ?? ""}(${parts.join(", ")})`;
673
+ }
674
+ function rootRule(element, rect, name) {
675
+ const box = element;
676
+ const computed = getComputedStyle(element);
677
+ const transform = withoutTranslation(computed.transform);
678
+ const isUntransformed = IDENTITY_TRANSFORMS.has(transform) && (!computed.rotate || computed.rotate === "none") && (!computed.scale || computed.scale === "none");
679
+ const width = isUntransformed ? rect.width : box.offsetWidth || rect.width;
680
+ const height = isUntransformed ? rect.height : box.offsetHeight || rect.height;
681
+ return `.${name}{position:absolute!important;inset:auto!important;left:${(rect.width - width) / 2}px!important;top:${(rect.height - height) / 2}px!important;width:${width}px!important;height:${height}px!important;margin:0!important;float:none!important;box-sizing:border-box!important;translate:none!important;transform:${transform}!important;transform-origin:50% 50%!important;}`;
682
+ }
683
+ function captureSnapshot(element) {
684
+ const rect = element.getBoundingClientRect();
685
+ if (rect.width < 1 || rect.height < 1) return null;
686
+ snapshotCount += 1;
687
+ const build = createBuild(`shatter-${snapshotCount}-`);
688
+ return withoutVeil(element, () => {
689
+ const template = cloneElement(element, build);
690
+ if (!template) return null;
691
+ const nodeCount = build.nodeCount;
692
+ const definitions = createDefinitions(build);
693
+ const rootName = `${build.prefix}root`;
694
+ template.classList.add(rootName);
695
+ build.rules.push(rootRule(element, rect, rootName));
696
+ return {
697
+ frame: { left: rect.left, top: rect.top, width: rect.width, height: rect.height },
698
+ template,
699
+ definitions,
700
+ rules: build.rules.join(""),
701
+ nodeCount,
702
+ bitmaps: build.bitmaps
703
+ };
704
+ });
705
+ }
706
+ function instantiate(snapshot, bitmapScale = 1) {
707
+ const node = snapshot.template.cloneNode(true);
708
+ if (!snapshot.bitmaps.length) return node;
709
+ const canvases = node.localName === "canvas" ? [node] : Array.from(node.querySelectorAll("canvas"));
710
+ canvases.forEach((element, index) => {
711
+ const bitmap = snapshot.bitmaps[index];
712
+ if (!bitmap) return;
713
+ const canvas = element;
714
+ canvas.width = Math.max(Math.round(bitmap.width * bitmapScale), 1);
715
+ canvas.height = Math.max(Math.round(bitmap.height * bitmapScale), 1);
716
+ drawInto(canvas, bitmap);
717
+ });
718
+ return node;
719
+ }
720
+ function restoreScroll(root) {
721
+ for (const element of Array.from(root.querySelectorAll(`[${SCROLL_ATTRIBUTE}]`))) {
722
+ const [left, top] = (element.getAttribute(SCROLL_ATTRIBUTE) ?? "0,0").split(",").map(Number);
723
+ element.scrollLeft = left ?? 0;
724
+ element.scrollTop = top ?? 0;
725
+ }
726
+ }
727
+
728
+ // src/core/piece.ts
729
+ var SEAM_BLEED = 0.6;
730
+ var OUTER_EDGE = 5e-4;
731
+ var SVG_NAMESPACE2 = "http://www.w3.org/2000/svg";
732
+ function createDiv(className) {
733
+ const element = document.createElement("div");
734
+ element.className = className;
735
+ return element;
736
+ }
737
+ function isOuterEdge(start, end) {
738
+ return start.x < OUTER_EDGE && end.x < OUTER_EDGE || start.x > 1 - OUTER_EDGE && end.x > 1 - OUTER_EDGE || start.y < OUTER_EDGE && end.y < OUTER_EDGE || start.y > 1 - OUTER_EDGE && end.y > 1 - OUTER_EDGE;
739
+ }
740
+ function crackPath(shard, local) {
741
+ let path = "";
742
+ shard.points.forEach((point, index) => {
743
+ const nextIndex = (index + 1) % shard.points.length;
744
+ const nextPoint = shard.points[nextIndex];
745
+ const start = local[index];
746
+ const end = local[nextIndex];
747
+ if (!nextPoint || !start || !end || isOuterEdge(point, nextPoint)) return;
748
+ path += `M${start.x.toFixed(2)} ${start.y.toFixed(2)}L${end.x.toFixed(2)} ${end.y.toFixed(2)}`;
749
+ });
750
+ return path;
751
+ }
752
+ function createCrackLine(path, color) {
753
+ const line = document.createElementNS(SVG_NAMESPACE2, "svg");
754
+ line.setAttribute("class", "line");
755
+ line.setAttribute("viewBox", "0 0 100 100");
756
+ line.setAttribute("preserveAspectRatio", "none");
757
+ const outline = document.createElementNS(SVG_NAMESPACE2, "path");
758
+ outline.setAttribute("d", path);
759
+ outline.setAttribute("stroke", color);
760
+ line.appendChild(outline);
761
+ return line;
762
+ }
763
+ function measureShard(shard, frame) {
764
+ const centerX = shard.center.x * frame.width;
765
+ const centerY = shard.center.y * frame.height;
766
+ const pixels = shard.points.map((point) => {
767
+ const x = point.x * frame.width;
768
+ const y = point.y * frame.height;
769
+ const distance = Math.hypot(x - centerX, y - centerY) || 1;
770
+ return {
771
+ x: x + (x - centerX) / distance * SEAM_BLEED,
772
+ y: y + (y - centerY) / distance * SEAM_BLEED
773
+ };
774
+ });
775
+ const left = Math.floor(Math.min(...pixels.map((point) => point.x)));
776
+ const top = Math.floor(Math.min(...pixels.map((point) => point.y)));
777
+ const width = Math.max(Math.ceil(Math.max(...pixels.map((point) => point.x))) - left, 1);
778
+ const height = Math.max(Math.ceil(Math.max(...pixels.map((point) => point.y))) - top, 1);
779
+ const local = pixels.map((point) => ({
780
+ x: (point.x - left) / width * 100,
781
+ y: (point.y - top) / height * 100
782
+ }));
783
+ return { centerX, centerY, left, top, width, height, local };
784
+ }
785
+ function createPiece(shard, snapshot, look) {
786
+ const { frame } = snapshot;
787
+ const { centerX, centerY, left, top, width, height, local } = measureShard(shard, frame);
788
+ const polygon = `polygon(${local.map((point) => `${point.x.toFixed(2)}% ${point.y.toFixed(2)}%`).join(",")})`;
789
+ const originX = (centerX - left) / width * 100;
790
+ const originY = (centerY - top) / height * 100;
791
+ const root = createDiv("piece");
792
+ root.style.cssText = `left:${frame.left + left}px;top:${frame.top + top}px;width:${width}px;height:${height}px;transform-origin:${originX.toFixed(2)}% ${originY.toFixed(2)}%;display:none;`;
793
+ const edge = createDiv("edge");
794
+ edge.style.cssText = `clip-path:${polygon};background:${look.edgeColor};transform:translateZ(${-look.depth}px);`;
795
+ const face = createDiv("face");
796
+ face.style.clipPath = polygon;
797
+ const content = createDiv("content");
798
+ content.style.cssText = `left:${-left}px;top:${-top}px;width:${frame.width}px;height:${frame.height}px;`;
799
+ content.appendChild(instantiate(snapshot, look.bitmapScale));
800
+ const shade = createDiv("shade");
801
+ face.append(content, shade);
802
+ root.append(edge, face);
803
+ const path = look.cracks ? crackPath(shard, local) : "";
804
+ const line = path ? createCrackLine(path, look.edgeColor) : null;
805
+ if (line) root.appendChild(line);
806
+ return {
807
+ root,
808
+ edge,
809
+ shade,
810
+ line,
811
+ x: frame.left + centerX,
812
+ y: frame.top + centerY,
813
+ visible: false,
814
+ scrollRestored: false,
815
+ edgeOpacity: 0,
816
+ shadeOpacity: 0,
817
+ lineOpacity: 0
818
+ };
819
+ }
820
+ function setPieceVisible(piece, visible) {
821
+ if (!piece || piece.visible === visible) return;
822
+ piece.visible = visible;
823
+ piece.root.style.display = visible ? "block" : "none";
824
+ if (visible && !piece.scrollRestored) {
825
+ piece.scrollRestored = true;
826
+ restoreScroll(piece.root);
827
+ }
828
+ }
829
+ function movePiece(piece, { x, y, z, axis, angle, scale, opacity }) {
830
+ piece.root.style.transform = `translate3d(${x.toFixed(2)}px,${y.toFixed(2)}px,${z.toFixed(2)}px) rotate3d(${axis.x.toFixed(3)},${axis.y.toFixed(3)},${axis.z.toFixed(3)},${angle.toFixed(3)}rad) scale(${scale.toFixed(3)})`;
831
+ piece.root.style.opacity = opacity.toFixed(2);
832
+ }
833
+ function setOpacity(element, current, next) {
834
+ if (Math.abs(current - next) < 0.01) return current;
835
+ element.style.opacity = next.toFixed(2);
836
+ return next;
837
+ }
838
+ function shadePiece(piece, weight, angle, crack) {
839
+ const facing = Math.abs(Math.cos(angle));
840
+ piece.edgeOpacity = setOpacity(piece.edge, piece.edgeOpacity, smoothstep(0.02, 0.35, weight));
841
+ piece.shadeOpacity = setOpacity(piece.shade, piece.shadeOpacity, weight * (0.16 + facing * 0.38));
842
+ if (piece.line) {
843
+ piece.lineOpacity = setOpacity(piece.line, piece.lineOpacity, Math.max(crack * (1 - weight), weight * 0.5));
844
+ }
845
+ }
846
+
847
+ // src/core/random.ts
848
+ function createRandom(seed) {
849
+ if (seed === void 0) return Math.random;
850
+ let state = seed >>> 0 || 1;
851
+ return () => {
852
+ state = state + 1831565813 >>> 0;
853
+ let value = state;
854
+ value = Math.imul(value ^ value >>> 15, value | 1);
855
+ value ^= value + Math.imul(value ^ value >>> 7, value | 61);
856
+ return ((value ^ value >>> 14) >>> 0) / 4294967296;
857
+ };
858
+ }
859
+
860
+ // src/core/run.ts
861
+ var DEFAULT_DURATION = 1800;
862
+ var DEFAULT_COLOR = "#8f897f";
863
+ var DEFAULT_EDGE_COLOR = "rgba(128, 122, 112, 0.92)";
864
+ var DEFAULT_Z_INDEX = 2147483e3;
865
+ var PERSPECTIVE = 1400;
866
+ var MIN_SHARDS = 10;
867
+ var MAX_SHARDS = 220;
868
+ var MAX_CLONED_NODES = 16e3;
869
+ var MAX_BITMAP_PIXELS = 32e6;
870
+ var NODES_PER_PIECE = 8;
871
+ var MAX_DUST = 900;
872
+ var MIST_COUNT = 36;
873
+ var SAFETY_MARGIN = 1200;
874
+ var running = /* @__PURE__ */ new WeakMap();
875
+ function finishRunning(element) {
876
+ running.get(element)?.finish();
877
+ }
878
+ function settledAnimation(result, onComplete) {
879
+ onComplete?.(result);
880
+ return { finished: Promise.resolve(result), finish() {
881
+ }, cancel() {
882
+ } };
883
+ }
884
+ function resolveShardCount(requested, area, nodesPerShard) {
885
+ const wanted = requested === "auto" ? Math.min(Math.max(Math.round(area / 2100), 16), 110) : Math.min(Math.max(Math.round(requested), 2), MAX_SHARDS);
886
+ const affordable = Math.floor(MAX_CLONED_NODES / Math.max(nodesPerShard, 1));
887
+ return affordable < MIN_SHARDS ? 0 : Math.min(wanted, affordable);
888
+ }
889
+ function areaOf(snapshot) {
890
+ return snapshot ? snapshot.frame.width * snapshot.frame.height : 0;
891
+ }
892
+ function bitmapPixels(snapshot) {
893
+ return (snapshot?.bitmaps ?? []).reduce((total, bitmap) => total + bitmap.width * bitmap.height, 0);
894
+ }
895
+ function bitmapScaleFor(from, to, shardCount) {
896
+ const pixels = (bitmapPixels(from) + bitmapPixels(to)) * shardCount;
897
+ return pixels > MAX_BITMAP_PIXELS ? Math.sqrt(MAX_BITMAP_PIXELS / pixels) : 1;
898
+ }
899
+ function centerOf(frame) {
900
+ return { x: frame.left + frame.width / 2, y: frame.top + frame.height / 2 };
901
+ }
902
+ function planFlight(from, main, options) {
903
+ const start = centerOf((from ?? main).frame);
904
+ const end = centerOf(main.frame);
905
+ const largest = Math.max(from?.frame.width ?? 0, from?.frame.height ?? 0, main.frame.width, main.frame.height);
906
+ return {
907
+ motion: options.motion ?? "vortex",
908
+ origin: options.origin ?? "right",
909
+ center: { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 },
910
+ radius: largest * 0.62 * (options.spread ?? 1),
911
+ depth: options.depth ?? Math.max(Math.min(main.frame.width, main.frame.height) * 0.016, 2)
912
+ };
913
+ }
914
+ function launchShard(shard, { from, to }, flight, look, stage, random) {
915
+ const seed = { a: random(), b: random(), c: random(), d: random() };
916
+ const axis = { x: seed.c - 0.5, y: seed.a - 0.5, z: seed.b - 0.5 };
917
+ const length = Math.hypot(axis.x, axis.y, axis.z) || 1;
918
+ const fromPiece = from ? createPiece(shard, from, look) : null;
919
+ const toPiece = to ? createPiece(shard, to, look) : null;
920
+ if (fromPiece) stage.appendChild(fromPiece.root);
921
+ if (toPiece) stage.appendChild(toPiece.root);
922
+ return {
923
+ seed,
924
+ delay: launchDelay(shard.center, flight.origin, seed.a),
925
+ axis: { x: axis.x / length, y: axis.y / length, z: axis.z / length },
926
+ turns: Math.PI * (2 + seed.b * 4),
927
+ shrink: 0.56 + seed.d * 0.4,
928
+ from: fromPiece,
929
+ to: toPiece
930
+ };
931
+ }
932
+ function createDebrisLayer(options, { host, shadow }, flight, frame, shardCount, random) {
933
+ const dust = options.dust === false ? 0 : typeof options.dust === "number" ? options.dust : shardCount * 8;
934
+ const mist = options.mist === false ? 0 : MIST_COUNT;
935
+ if (!(dust > 0 || mist > 0)) return null;
936
+ const canvas = document.createElement("canvas");
937
+ canvas.className = "debris";
938
+ shadow.appendChild(canvas);
939
+ return createDebris({
940
+ canvas,
941
+ color: resolveColor(host, options.color ?? DEFAULT_COLOR, DEFAULT_COLOR),
942
+ dust: Math.min(Math.max(Math.round(dust), 0), MAX_DUST),
943
+ mist,
944
+ motion: flight.motion,
945
+ origin: flight.origin,
946
+ radius: flight.radius,
947
+ perspective: PERSPECTIVE,
948
+ center: flight.center,
949
+ frame,
950
+ random
951
+ });
952
+ }
953
+ function buildScene(config, main, overlay, flight, shardCount) {
954
+ const { from, to, options } = config;
955
+ const { host, stage } = overlay;
956
+ const random = createRandom(options.seed);
957
+ stage.style.perspective = `${PERSPECTIVE}px`;
958
+ stage.style.perspectiveOrigin = `${flight.center.x}px ${flight.center.y}px`;
959
+ for (const snapshot of [from, to]) {
960
+ if (snapshot?.definitions) stage.appendChild(snapshot.definitions.cloneNode(true));
961
+ }
962
+ const shards = fracture(main.frame.width, main.frame.height, shardCount, random);
963
+ const look = {
964
+ depth: flight.depth,
965
+ edgeColor: resolveColor(host, options.edgeColor ?? DEFAULT_EDGE_COLOR, DEFAULT_EDGE_COLOR),
966
+ cracks: options.cracks ?? true,
967
+ bitmapScale: bitmapScaleFor(from, to, shards.length)
968
+ };
969
+ return {
970
+ shards: shards.map((shard) => launchShard(shard, config, flight, look, stage, random)),
971
+ debris: createDebrisLayer(options, overlay, flight, main.frame, shardCount, random)
972
+ };
973
+ }
974
+ function renderShard(shard, time, crack, flight) {
975
+ const { motion, center, radius } = flight;
976
+ const isOutOnly = !shard.to;
977
+ const isInOnly = !shard.from;
978
+ const raw = flightProgress(time, shard.delay);
979
+ const progress = isOutOnly ? raw * 0.5 : isInOnly ? 0.5 + raw * 0.5 : raw;
980
+ const usesTarget = isInOnly || !isOutOnly && progress >= 0.5;
981
+ const piece = usesTarget ? shard.to : shard.from;
982
+ if (!piece) return;
983
+ setPieceVisible(usesTarget ? shard.from : shard.to, false);
984
+ setPieceVisible(piece, true);
985
+ const weight = flightWeight(progress);
986
+ const point = flightPoint(motion, progress, shard.seed, radius);
987
+ const angle = weight * shard.turns;
988
+ let opacity = midpointFade(motion, progress);
989
+ if (isOutOnly) opacity *= 1 - smoothstep(0.72, 1, raw);
990
+ if (isInOnly) opacity *= smoothstep(0, 0.28, raw);
991
+ movePiece(piece, {
992
+ x: mix(piece.x, center.x + point.x, weight) - piece.x,
993
+ y: mix(piece.y, center.y + point.y, weight) - piece.y,
994
+ z: point.z * weight,
995
+ axis: shard.axis,
996
+ angle,
997
+ scale: mix(1, shard.shrink, weight),
998
+ opacity
999
+ });
1000
+ shadePiece(piece, weight, angle, crack);
1001
+ }
1002
+ function playScene(config, { host, stage }, flight, scene) {
1003
+ const { anchor, options } = config;
1004
+ const duration = Math.max(options.duration ?? DEFAULT_DURATION, 1);
1005
+ const anchorStart = anchor.getBoundingClientRect();
1006
+ const render = (time) => {
1007
+ const crack = smoothstep(0, 0.05, time) * (1 - smoothstep(0.8, 0.97, time));
1008
+ const now = anchor.getBoundingClientRect();
1009
+ const offsetX = now.width ? now.left - anchorStart.left : 0;
1010
+ const offsetY = now.width ? now.top - anchorStart.top : 0;
1011
+ stage.style.transform = offsetX || offsetY ? `translate(${offsetX}px,${offsetY}px)` : "";
1012
+ for (const shard of scene.shards) renderShard(shard, time, crack, flight);
1013
+ scene.debris?.draw(time, offsetX, offsetY);
1014
+ };
1015
+ let done = false;
1016
+ let frameId = 0;
1017
+ let startTime = null;
1018
+ let resolveFinished;
1019
+ const finished = new Promise((resolve) => {
1020
+ resolveFinished = resolve;
1021
+ });
1022
+ const handleVisibility = () => {
1023
+ if (document.hidden) animation.finish();
1024
+ };
1025
+ const complete = (result) => {
1026
+ if (done) return;
1027
+ done = true;
1028
+ cancelAnimationFrame(frameId);
1029
+ clearTimeout(safetyTimer);
1030
+ document.removeEventListener("visibilitychange", handleVisibility);
1031
+ for (const element of config.veiled) unveil(element);
1032
+ if (result === "cancelled") config.revert();
1033
+ else config.settle();
1034
+ host.remove();
1035
+ for (const element of config.elements) {
1036
+ if (running.get(element) === animation) running.delete(element);
1037
+ }
1038
+ resolveFinished(result);
1039
+ options.onComplete?.(result);
1040
+ };
1041
+ const animation = {
1042
+ finished,
1043
+ finish: () => complete("finished"),
1044
+ cancel: () => complete("cancelled")
1045
+ };
1046
+ const safetyTimer = setTimeout(animation.finish, duration + SAFETY_MARGIN);
1047
+ const tick = (now) => {
1048
+ if (done) return;
1049
+ if (!anchor.isConnected) {
1050
+ animation.finish();
1051
+ return;
1052
+ }
1053
+ startTime ??= now;
1054
+ const time = clamp01((now - startTime) / duration);
1055
+ render(time);
1056
+ if (time >= 1) animation.finish();
1057
+ else frameId = requestAnimationFrame(tick);
1058
+ };
1059
+ for (const element of config.elements) running.set(element, animation);
1060
+ for (const element of config.veiled) veil(element);
1061
+ document.addEventListener("visibilitychange", handleVisibility);
1062
+ render(0);
1063
+ if (document.hidden) animation.finish();
1064
+ else frameId = requestAnimationFrame(tick);
1065
+ return animation;
1066
+ }
1067
+ function startRun(config) {
1068
+ const { from, to, options } = config;
1069
+ const main = to ?? from;
1070
+ const nodesPerShard = (from?.nodeCount ?? 0) + (to?.nodeCount ?? 0) + NODES_PER_PIECE;
1071
+ const area = Math.max(areaOf(from), areaOf(to));
1072
+ const shardCount = main ? resolveShardCount(options.shards ?? "auto", area, nodesPerShard) : 0;
1073
+ if (!main || shardCount === 0) {
1074
+ config.settle();
1075
+ return settledAnimation("skipped", options.onComplete);
1076
+ }
1077
+ const flight = planFlight(from, main, options);
1078
+ const overlay = createOverlay(options.zIndex ?? DEFAULT_Z_INDEX, (from?.rules ?? "") + (to?.rules ?? ""));
1079
+ let scene;
1080
+ try {
1081
+ scene = buildScene(config, main, overlay, flight, shardCount);
1082
+ } catch {
1083
+ overlay.host.remove();
1084
+ config.settle();
1085
+ return settledAnimation("skipped", options.onComplete);
1086
+ }
1087
+ return playScene(config, overlay, flight, scene);
1088
+ }
1089
+
1090
+ // src/core/shatter.ts
1091
+ function canAnimate(options) {
1092
+ if (typeof document === "undefined" || !isShatterEnabled()) return false;
1093
+ return options.respectReducedMotion === false || !prefersReducedMotion();
1094
+ }
1095
+ function hideElement(element, options) {
1096
+ if (options.keepLayout) veil(element);
1097
+ else conceal(element);
1098
+ }
1099
+ function showElement(element) {
1100
+ reveal(element);
1101
+ unveil(element);
1102
+ }
1103
+ function isThenable(value) {
1104
+ return typeof value?.then === "function";
1105
+ }
1106
+ function shatterOut(element, options = {}) {
1107
+ if (typeof document === "undefined") return settledAnimation("skipped", options.onComplete);
1108
+ finishRunning(element);
1109
+ const snapshot = canAnimate(options) ? captureSnapshot(element) : null;
1110
+ if (!snapshot) {
1111
+ hideElement(element, options);
1112
+ return settledAnimation("skipped", options.onComplete);
1113
+ }
1114
+ return startRun({
1115
+ from: snapshot,
1116
+ to: null,
1117
+ anchor: element,
1118
+ elements: [element],
1119
+ veiled: [element],
1120
+ settle: () => hideElement(element, options),
1121
+ revert: () => {
1122
+ },
1123
+ options
1124
+ });
1125
+ }
1126
+ function shatterIn(element, options = {}) {
1127
+ if (typeof document === "undefined") return settledAnimation("skipped", options.onComplete);
1128
+ finishRunning(element);
1129
+ showElement(element);
1130
+ const snapshot = canAnimate(options) ? captureSnapshot(element) : null;
1131
+ if (!snapshot) return settledAnimation("skipped", options.onComplete);
1132
+ return startRun({
1133
+ from: null,
1134
+ to: snapshot,
1135
+ anchor: element,
1136
+ elements: [element],
1137
+ veiled: [element],
1138
+ settle: () => {
1139
+ },
1140
+ revert: () => hideElement(element, options),
1141
+ options
1142
+ });
1143
+ }
1144
+ function shatterTo(from, to, options = {}) {
1145
+ if (typeof document === "undefined" || from === to) return settledAnimation("skipped", options.onComplete);
1146
+ finishRunning(from);
1147
+ finishRunning(to);
1148
+ const animate = canAnimate(options);
1149
+ const before = animate ? captureSnapshot(from) : null;
1150
+ hideElement(from, options);
1151
+ showElement(to);
1152
+ const after = animate ? captureSnapshot(to) : null;
1153
+ if (!before && !after) return settledAnimation("skipped", options.onComplete);
1154
+ return startRun({
1155
+ from: before,
1156
+ to: after,
1157
+ anchor: after ? to : from,
1158
+ elements: [from, to],
1159
+ veiled: after ? [to] : [],
1160
+ settle: () => {
1161
+ },
1162
+ revert: () => {
1163
+ hideElement(to, options);
1164
+ showElement(from);
1165
+ },
1166
+ options
1167
+ });
1168
+ }
1169
+ function prepareShatter(element, options = {}) {
1170
+ finishRunning(element);
1171
+ const before = canAnimate(options) ? captureSnapshot(element) : null;
1172
+ return {
1173
+ play(playOptions = options) {
1174
+ if (!before || !canAnimate(playOptions)) return settledAnimation("skipped", playOptions.onComplete);
1175
+ finishRunning(element);
1176
+ return startRun({
1177
+ from: before,
1178
+ to: captureSnapshot(element),
1179
+ anchor: element,
1180
+ elements: [element],
1181
+ veiled: [element],
1182
+ settle: () => {
1183
+ },
1184
+ revert: () => {
1185
+ },
1186
+ options: playOptions
1187
+ });
1188
+ }
1189
+ };
1190
+ }
1191
+ function shatterUpdate(element, update, options = {}) {
1192
+ const prepared = prepareShatter(element, options);
1193
+ const pending = update();
1194
+ if (!isThenable(pending)) return prepared.play(options);
1195
+ let inner = null;
1196
+ let requested = null;
1197
+ const finished = Promise.resolve(pending).then(() => {
1198
+ inner = prepared.play(options);
1199
+ if (requested) inner[requested]();
1200
+ return inner.finished;
1201
+ });
1202
+ return {
1203
+ finished,
1204
+ finish() {
1205
+ requested = "finish";
1206
+ inner?.finish();
1207
+ },
1208
+ cancel() {
1209
+ requested = "cancel";
1210
+ inner?.cancel();
1211
+ }
1212
+ };
1213
+ }
1214
+
1215
+ export { conceal, isShatterEnabled, prepareShatter, reveal, setShatterEnabled, shatterIn, shatterOut, shatterTo, shatterUpdate };
1216
+ //# sourceMappingURL=chunk-GTAQR2GH.js.map
1217
+ //# sourceMappingURL=chunk-GTAQR2GH.js.map