@wojcieh/snow-drift 0.0.0-stage → 1.0.1

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,1611 @@
1
+ /*! @wojcieh/snow-drift v1.0.1 | MIT License | (c) 2026 Wojciech Marusiak (https://www.wojcieh.net) */
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/snow-drift.js
21
+ var snow_drift_exports = {};
22
+ __export(snow_drift_exports, {
23
+ BIN_PX: () => BIN_PX,
24
+ MODES: () => MODES,
25
+ SnowDriftElement: () => SnowDriftElement,
26
+ classifySurfaceShape: () => classifySurfaceShape,
27
+ defineSnowDrift: () => defineSnowDrift,
28
+ parseBorderRadiusPx: () => parseBorderRadiusPx
29
+ });
30
+ module.exports = __toCommonJS(snow_drift_exports);
31
+
32
+ // src/physics.js
33
+ var BIN_PX = 5;
34
+ var MAX_NEIGHBOR_SLOPE = 1.15;
35
+ var MODES = ["normal", "blizzard", "light", "off"];
36
+ var MODE_CONFIGS = {
37
+ blizzard: {
38
+ minMult: 2.3,
39
+ maxMult: 3.3,
40
+ speedMult: 1.9,
41
+ depositMult: 1.75,
42
+ gustMinWait: 90,
43
+ gustMaxWait: 240,
44
+ gustStrengthMin: 1.5,
45
+ gustStrengthMax: 3.4
46
+ },
47
+ light: {
48
+ minMult: 0.28,
49
+ maxMult: 0.52,
50
+ speedMult: 0.75,
51
+ depositMult: 0.14,
52
+ gustMinWait: 560,
53
+ gustMaxWait: 1200,
54
+ gustStrengthMin: 0.3,
55
+ gustStrengthMax: 0.85
56
+ },
57
+ normal: {
58
+ minMult: 0.5,
59
+ maxMult: 1.1,
60
+ speedMult: 0.9,
61
+ depositMult: 0.28,
62
+ gustMinWait: 360,
63
+ gustMaxWait: 880,
64
+ gustStrengthMin: 0.5,
65
+ gustStrengthMax: 1.75
66
+ }
67
+ };
68
+ function modeConfig(mode) {
69
+ return MODE_CONFIGS[mode] || MODE_CONFIGS.normal;
70
+ }
71
+ function parseBorderRadiusPx(rawValue, referenceSize) {
72
+ if (!rawValue || typeof rawValue !== "string") return 0;
73
+ const firstToken = rawValue.trim().split(/\s+/)[0] || "";
74
+ const num = parseFloat(firstToken);
75
+ if (!Number.isFinite(num) || num <= 0) return 0;
76
+ if (firstToken.endsWith("%")) {
77
+ return num / 100 * Math.max(0, referenceSize);
78
+ }
79
+ return num;
80
+ }
81
+ function classifySurfaceShape(width, height, topLeftRadiusPx, topRightRadiusPx, explicitShape = "") {
82
+ const clean = String(explicitShape || "").trim().toLowerCase();
83
+ if (clean === "circle" || clean === "pill" || clean === "flat") {
84
+ return clean;
85
+ }
86
+ const minDim = Math.min(width, height);
87
+ if (minDim <= 0) return "flat";
88
+ const avgR = (Math.min(topLeftRadiusPx, width * 0.5) + Math.min(topRightRadiusPx, width * 0.5)) * 0.5;
89
+ const aspect = width / Math.max(1, height);
90
+ if (minDim >= 36 && aspect >= 0.78 && aspect <= 1.28 && avgR >= minDim * 0.42) {
91
+ return "circle";
92
+ }
93
+ if (avgR >= height * 0.36) {
94
+ return "pill";
95
+ }
96
+ return "flat";
97
+ }
98
+ function ensureBinsArray(prev, width, binPx = BIN_PX) {
99
+ const n = Math.max(8, Math.ceil(width / binPx) + 1);
100
+ if (prev instanceof Float32Array && Math.abs(prev.length - n) <= 2) {
101
+ return prev;
102
+ }
103
+ const next = new Float32Array(n);
104
+ if (prev && prev.length > 0) {
105
+ for (let i = 0; i < n; i++) {
106
+ const oldIdx = Math.min(
107
+ prev.length - 1,
108
+ Math.floor(i / n * prev.length)
109
+ );
110
+ next[i] = prev[oldIdx];
111
+ }
112
+ }
113
+ return next;
114
+ }
115
+ function baseSurfaceY(surf, binIdx, binPx = BIN_PX) {
116
+ if (surf.shape === "circle") {
117
+ const xRel = binIdx * binPx - surf.radius;
118
+ const clamped = Math.max(
119
+ -surf.radius * 0.92,
120
+ Math.min(surf.radius * 0.92, xRel)
121
+ );
122
+ const dyArc = Math.sqrt(
123
+ Math.max(0, surf.radius * surf.radius - clamped * clamped)
124
+ );
125
+ return surf.top + surf.radius - dyArc + 1.5;
126
+ }
127
+ if (surf.baseProfile) {
128
+ const idx = Math.max(0, Math.min(surf.baseProfile.length - 1, binIdx));
129
+ return surf.top + surf.baseProfile[idx] + 0.5;
130
+ }
131
+ return surf.top + 1;
132
+ }
133
+ function slopeFactor(surf, binIdx, binPx = BIN_PX) {
134
+ if (surf.shape === "circle") {
135
+ const nx = (binIdx * binPx - surf.radius) / Math.max(1, surf.radius);
136
+ const c = Math.max(0, 1 - nx * nx * 1.35);
137
+ return Math.pow(c, 0.75);
138
+ }
139
+ if (binIdx - surf.minBin < 3) return (binIdx - surf.minBin + 1) * 0.28;
140
+ if (surf.maxBin - binIdx < 3) return (surf.maxBin - binIdx + 1) * 0.28;
141
+ return 1;
142
+ }
143
+ function relaxRange(arr, startIdx, endIdx, maxCap, maxSlope = MAX_NEIGHBOR_SLOPE) {
144
+ for (let i = startIdx; i < endIdx; i++) {
145
+ const diff = arr[i] - arr[i + 1];
146
+ if (diff > maxSlope) {
147
+ const move = (diff - maxSlope) * 0.48;
148
+ arr[i] -= move;
149
+ arr[i + 1] = Math.min(maxCap, arr[i + 1] + move);
150
+ } else if (diff < -maxSlope) {
151
+ const moveBack = (-diff - maxSlope) * 0.48;
152
+ arr[i + 1] -= moveBack;
153
+ arr[i] = Math.min(maxCap, arr[i] + moveBack);
154
+ }
155
+ }
156
+ for (let j = endIdx - 1; j >= startIdx; j--) {
157
+ const diff = arr[j] - arr[j + 1];
158
+ if (diff > maxSlope) {
159
+ const move = (diff - maxSlope) * 0.48;
160
+ arr[j] -= move;
161
+ arr[j + 1] = Math.min(maxCap, arr[j + 1] + move);
162
+ } else if (diff < -maxSlope) {
163
+ const moveBack = (-diff - maxSlope) * 0.48;
164
+ arr[j + 1] -= moveBack;
165
+ arr[j] = Math.min(maxCap, arr[j] + moveBack);
166
+ }
167
+ }
168
+ }
169
+ function depositOnSurface(surf, localBinFloat, radius, mult = 1, binPx = BIN_PX) {
170
+ if (surf.maxBin <= surf.minBin) return;
171
+ const arr = surf.bins;
172
+ const c = Math.max(surf.minBin, Math.min(surf.maxBin, Math.round(localBinFloat)));
173
+ const shapeBoost = surf.shape === "circle" ? 0.72 : surf.baseProfile ? 0.56 : 0.64;
174
+ const amount = radius * shapeBoost * mult;
175
+ for (let k = -4; k <= 4; k++) {
176
+ const idx = c + k;
177
+ if (idx < surf.minBin || idx > surf.maxBin) continue;
178
+ const sf = slopeFactor(surf, idx, binPx);
179
+ const cap = surf.maxH * 1.08 * Math.max(0.22, sf);
180
+ const weight = Math.exp(-(k * k) / 6.5) * sf;
181
+ arr[idx] = Math.min(cap, arr[idx] + amount * weight);
182
+ }
183
+ const sStart = Math.max(surf.minBin + 1, c - 6);
184
+ const sEnd = Math.min(surf.maxBin, c + 6);
185
+ relaxRange(arr, sStart, sEnd, surf.maxH * 1.08);
186
+ for (let s = sStart; s < sEnd; s++) {
187
+ arr[s] = (arr[s - 1] + arr[s] * 2.4 + arr[s + 1]) / 4.4;
188
+ }
189
+ arr[surf.minBin] *= 0.35;
190
+ arr[surf.maxBin] *= 0.35;
191
+ }
192
+ function depositBottom(bottomBins, localBinFloat, radius, maxH, mult = 1) {
193
+ const minBin = 0;
194
+ const maxBin = bottomBins.length - 1;
195
+ if (maxBin <= minBin) return;
196
+ const c = Math.max(minBin, Math.min(maxBin, Math.round(localBinFloat)));
197
+ const amount = radius * 0.62 * mult;
198
+ for (let k = -4; k <= 4; k++) {
199
+ const idx = c + k;
200
+ if (idx < minBin || idx > maxBin) continue;
201
+ const weight = Math.exp(-(k * k) / 6.5);
202
+ bottomBins[idx] = Math.min(maxH, bottomBins[idx] + amount * weight);
203
+ }
204
+ const sStart = Math.max(minBin, c - 8);
205
+ const sEnd = Math.min(maxBin, c + 8);
206
+ relaxRange(bottomBins, sStart, sEnd, maxH);
207
+ for (let s = Math.max(minBin + 1, c - 5); s < Math.min(maxBin, c + 5); s++) {
208
+ bottomBins[s] = (bottomBins[s - 1] + bottomBins[s] * 2.4 + bottomBins[s + 1]) / 4.4;
209
+ }
210
+ }
211
+ function findAvalanchePeak(surf, windCurrent = 0, binPx = BIN_PX) {
212
+ const gustPush = Math.abs(windCurrent) > 1.35 ? 0.84 : 0.93;
213
+ const threshold = surf.maxH * gustPush;
214
+ let bestIdx = -1;
215
+ let bestRatio = 0;
216
+ for (let b = surf.minBin + 1; b < surf.maxBin; b++) {
217
+ const localCap = Math.max(
218
+ 4.5,
219
+ surf.maxH * Math.max(0.32, slopeFactor(surf, b, binPx))
220
+ );
221
+ const ratio = surf.bins[b] / (localCap * gustPush);
222
+ if (surf.bins[b] >= Math.min(threshold, localCap * gustPush) && ratio > bestRatio) {
223
+ bestRatio = ratio;
224
+ bestIdx = b;
225
+ }
226
+ }
227
+ if (bestIdx === -1) return null;
228
+ return { peakIdx: bestIdx, ratio: bestRatio };
229
+ }
230
+ function shearAvalanche(surf, peakIdx, windCurrent = 0, binPx = BIN_PX, chunkBudget = 80, rng = Math.random) {
231
+ const arr = surf.bins;
232
+ const span = surf.shape === "circle" ? 10 : Math.min(
233
+ 26,
234
+ Math.max(11, Math.round((surf.maxBin - surf.minBin) * 0.32))
235
+ );
236
+ const sBin = Math.max(surf.minBin, peakIdx - span);
237
+ const eBin = Math.min(surf.maxBin, peakIdx + span);
238
+ const midBin = (surf.minBin + surf.maxBin) * 0.5;
239
+ let slideDir = 0;
240
+ if (surf.shape === "circle") {
241
+ if (Math.abs(peakIdx - midBin) > 1.5) slideDir = peakIdx > midBin ? 1 : -1;
242
+ else {
243
+ slideDir = Math.abs(windCurrent) > 0.25 ? windCurrent > 0 ? 1 : -1 : rng() < 0.5 ? -1 : 1;
244
+ }
245
+ } else {
246
+ if (peakIdx - surf.minBin < 9) slideDir = -1;
247
+ else if (surf.maxBin - peakIdx < 9) slideDir = 1;
248
+ else {
249
+ slideDir = Math.abs(windCurrent) > 0.35 ? windCurrent > 0 ? 0.65 : -0.65 : -0.35 + rng() * 0.7;
250
+ }
251
+ }
252
+ const spawned = [];
253
+ for (let b = sBin; b <= eBin; b++) {
254
+ const hVal = arr[b];
255
+ if (hVal < 2.2) continue;
256
+ const distRatio = 1 - Math.abs(b - peakIdx) / (span + 1);
257
+ const shedFraction = Math.max(0.25, Math.min(0.86, 0.85 * distRatio + 0.12));
258
+ const shedH = hVal * shedFraction;
259
+ arr[b] = hVal - shedH;
260
+ const numChunks = Math.min(3, Math.max(1, Math.round(shedH / 4.2)));
261
+ const baseY = baseSurfaceY(surf, b, binPx);
262
+ const xPos = surf.left + b * binPx;
263
+ for (let c = 0; c < numChunks; c++) {
264
+ if (spawned.length >= chunkBudget) break;
265
+ spawned.push({
266
+ x: xPos + (-2 + rng() * 4),
267
+ y: baseY - rng() * hVal * 0.8 + 2,
268
+ r: 1.5 + rng() * 2.5,
269
+ vx: slideDir * (0.45 + rng() * 1.15) + windCurrent * 0.22 + (-0.25 + rng() * 0.5),
270
+ vy: 0.35 + rng() * 1.05,
271
+ alpha: 0.68 + rng() * 0.26,
272
+ originEl: surf.el || null
273
+ });
274
+ }
275
+ }
276
+ for (let pass = 0; pass < 2; pass++) {
277
+ const start = Math.max(surf.minBin + 1, sBin - 2);
278
+ const end = Math.min(surf.maxBin, eBin + 2);
279
+ for (let s = start; s < end; s++) {
280
+ arr[s] = (arr[s - 1] + arr[s] * 2 + arr[s + 1]) * 0.25;
281
+ }
282
+ }
283
+ return spawned;
284
+ }
285
+
286
+ // src/snow-drift.js
287
+ var DEFAULT_STORAGE_KEY = "snow-drift-mode";
288
+ var MAX_POOL = 360;
289
+ var MAX_CHUNKS = 280;
290
+ var MODE_LABELS = {
291
+ normal: "Snow: Normal",
292
+ blizzard: "Snow: Blizzard",
293
+ light: "Snow: Light",
294
+ off: "Snow: Off"
295
+ };
296
+ var SNOWFLAKE_SVG = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 2v20M4.93 4.93l14.14 14.14M2 12h20M4.93 19.07L19.07 4.93"/><path d="m10 4 2 2 2-2M10 20l2-2 2 2M4 10l2 2-2 2M20 10l-2 2 2 2"/></svg>`;
297
+ function parseBoolAttr(val, fallback) {
298
+ if (val === null || val === void 0) return fallback;
299
+ const v = String(val).trim().toLowerCase();
300
+ if (v === "" || v === "true" || v === "1" || v === "yes" || v === "on") return true;
301
+ if (v === "false" || v === "0" || v === "no" || v === "off") return false;
302
+ return fallback;
303
+ }
304
+ function parseNumAttr(val, fallback, min, max) {
305
+ const n = parseFloat(val);
306
+ if (!Number.isFinite(n)) return fallback;
307
+ return Math.max(min, Math.min(max, n));
308
+ }
309
+ function parseRgbLuminance(cssColor) {
310
+ if (!cssColor || cssColor === "transparent") return null;
311
+ const m = cssColor.match(
312
+ /rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,/\s]+([\d.]+))?\s*\)/i
313
+ );
314
+ if (!m) return null;
315
+ const alpha = m[4] !== void 0 ? parseFloat(m[4]) : 1;
316
+ if (alpha < 0.15) return null;
317
+ const r = parseFloat(m[1]);
318
+ const g = parseFloat(m[2]);
319
+ const b = parseFloat(m[3]);
320
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
321
+ }
322
+ function detectFixedOrSticky(el) {
323
+ let cur = el;
324
+ while (cur && cur !== document.body && cur !== document.documentElement) {
325
+ const pos = window.getComputedStyle(cur).position;
326
+ if (pos === "fixed" || pos === "sticky") return true;
327
+ cur = cur.parentElement;
328
+ }
329
+ return false;
330
+ }
331
+ var BaseElement = typeof HTMLElement !== "undefined" ? HTMLElement : class {
332
+ };
333
+ var SnowDriftElement = class extends BaseElement {
334
+ static get observedAttributes() {
335
+ return [
336
+ "mode",
337
+ "surfaces",
338
+ "text-surfaces",
339
+ "floor",
340
+ "bury",
341
+ "avalanches",
342
+ "interactive",
343
+ "controls",
344
+ "controls-position",
345
+ "toggle-selector",
346
+ "theme",
347
+ "density",
348
+ "wind",
349
+ "z-index",
350
+ "storage-key",
351
+ "respect-reduced-motion",
352
+ "preseed"
353
+ ];
354
+ }
355
+ constructor() {
356
+ super();
357
+ if (typeof window === "undefined") return;
358
+ this._shadow = this.attachShadow({ mode: "open" });
359
+ this._w = 0;
360
+ this._h = 0;
361
+ this._bottomBins = new Float32Array(0);
362
+ this._visibleSurfaces = [];
363
+ this._trackedElements = /* @__PURE__ */ new Set();
364
+ this._flakes = [];
365
+ this._chunks = [];
366
+ this._rafId = null;
367
+ this._idleHandle = null;
368
+ this._usingIdleCallback = false;
369
+ this._frameCounter = 0;
370
+ this._lastScrollY = 0;
371
+ this._mouseX = -9999;
372
+ this._mouseY = -9999;
373
+ this._densityWaveFactor = 1;
374
+ this._densityTargetFactor = 1;
375
+ this._nextDensityShiftFrame = 180;
376
+ this._windCurrent = 0;
377
+ this._windTarget = 0;
378
+ this._gustFramesLeft = 0;
379
+ this._nextGustFrame = 240;
380
+ this._currentMode = "normal";
381
+ this._isDark = true;
382
+ this._boundExternalToggles = /* @__PURE__ */ new Map();
383
+ this._themeObserver = null;
384
+ this._connected = false;
385
+ this._didPreseed = false;
386
+ this._onScroll = this._handleScroll.bind(this);
387
+ this._onPointerMove = this._handlePointerMove.bind(this);
388
+ this._onResize = this._handleResize.bind(this);
389
+ this._onVisibility = this._handleVisibility.bind(this);
390
+ this._tickBound = this._tick.bind(this);
391
+ this._renderShadowDOM();
392
+ }
393
+ _renderShadowDOM() {
394
+ this._shadow.innerHTML = `<style>:host{display:contents}canvas{position:fixed;inset:0;width:100vw;height:100vh;pointer-events:none;z-index:var(--snow-drift-z,9990);display:none}.sd-toggle{position:fixed;z-index:calc(var(--snow-drift-z,9990) + 1);display:none;align-items:center;gap:8px;min-height:38px;padding:7px 13px;border-radius:999px;border:1px solid rgba(148,163,184,.26);background:rgba(15,23,42,.82);color:#e2e8f0;backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);font:500 13px/1.2 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;letter-spacing:-.01em;cursor:pointer;user-select:none;box-shadow:0 6px 20px rgba(2,6,23,.24);transition:transform .18s cubic-bezier(.23,1,.32,1),background-color .18s ease,border-color .18s ease,color .18s ease}.sd-toggle[data-visible=true]{display:inline-flex}.sd-toggle[data-pos=bottom-right]{right:18px;bottom:18px}.sd-toggle[data-pos=bottom-left]{left:18px;bottom:18px}.sd-toggle[data-pos=top-right]{right:18px;top:18px}.sd-toggle[data-pos=top-left]{left:18px;top:18px}.sd-toggle[data-light=true]{background:rgba(255,255,255,.88);color:#1e293b;border-color:rgba(100,116,139,.25);box-shadow:0 6px 20px rgba(15,23,42,.08)}.sd-toggle:hover{border-color:rgba(56,189,248,.55);color:#38bdf8}.sd-toggle[data-light=true]:hover{border-color:rgba(2,132,199,.45);color:#0284c7}.sd-toggle:active{transform:scale(.97)}.sd-toggle:focus-visible{outline:2px solid #38bdf8;outline-offset:2px}.sd-toggle svg{width:16px;height:16px;flex-shrink:0;opacity:.78;transition:transform .22s cubic-bezier(.23,1,.32,1),opacity .2s ease}.sd-toggle[data-snow-active=true] svg{opacity:1;color:#38bdf8}.sd-toggle[data-light=true][data-snow-active=true] svg{color:#0284c7}.sd-toggle[data-snow-mode=blizzard] svg{animation:sd-spin 3.2s linear infinite}@keyframes sd-spin{to{transform:rotate(360deg)}}@media (prefers-reduced-motion:reduce){.sd-toggle[data-snow-mode=blizzard] svg{animation:none}}@media print{canvas,.sd-toggle{display:none!important}}</style><canvas part="canvas" aria-hidden="true"></canvas><button type="button" class="sd-toggle" part="toggle" aria-pressed="true">${SNOWFLAKE_SVG}<span class="sd-label" part="label">Snow: Normal</span></button>`;
395
+ this._canvas = this._shadow.querySelector("canvas");
396
+ this._ctx = this._canvas ? this._canvas.getContext("2d") : null;
397
+ this._builtinBtn = this._shadow.querySelector(".sd-toggle");
398
+ this._builtinLabel = this._shadow.querySelector(".sd-label");
399
+ if (this._builtinBtn) {
400
+ this._builtinBtn.addEventListener("click", () => this.cycleMode());
401
+ }
402
+ }
403
+ connectedCallback() {
404
+ if (typeof window === "undefined" || !this._ctx) return;
405
+ this._connected = true;
406
+ this._syncZIndex();
407
+ this._syncControlsVisibility();
408
+ this._resolveInitialMode();
409
+ this._updateThemeState();
410
+ this._bindExternalToggles();
411
+ window.addEventListener("scroll", this._onScroll, { passive: true });
412
+ window.addEventListener("pointermove", this._onPointerMove, { passive: true });
413
+ window.addEventListener("resize", this._onResize, { passive: true });
414
+ document.addEventListener("visibilitychange", this._onVisibility);
415
+ if (typeof MutationObserver !== "undefined") {
416
+ this._themeObserver = new MutationObserver(() => this._updateThemeState());
417
+ this._themeObserver.observe(document.documentElement, {
418
+ attributes: true,
419
+ attributeFilter: ["class", "data-theme", "data-scheme", "data-color-mode", "data-bs-theme", "style"]
420
+ });
421
+ if (document.body) {
422
+ this._themeObserver.observe(document.body, {
423
+ attributes: true,
424
+ attributeFilter: ["class", "data-theme", "data-scheme", "style"]
425
+ });
426
+ }
427
+ }
428
+ if (document.fonts && document.fonts.ready) {
429
+ document.fonts.ready.then(() => {
430
+ if (this._connected && this.active && this._w > 0) {
431
+ this.refresh();
432
+ }
433
+ }).catch(() => {
434
+ });
435
+ }
436
+ if (typeof window.requestIdleCallback === "function") {
437
+ this._usingIdleCallback = true;
438
+ this._idleHandle = window.requestIdleCallback(() => {
439
+ this._idleHandle = null;
440
+ if (!this._connected) return;
441
+ this._handleResize();
442
+ this._syncModeState(true);
443
+ this._applyInitialPreseed();
444
+ });
445
+ } else {
446
+ this._usingIdleCallback = false;
447
+ this._idleHandle = window.setTimeout(() => {
448
+ this._idleHandle = null;
449
+ if (!this._connected) return;
450
+ this._handleResize();
451
+ this._syncModeState(true);
452
+ this._applyInitialPreseed();
453
+ }, 120);
454
+ }
455
+ }
456
+ disconnectedCallback() {
457
+ this._connected = false;
458
+ if (typeof window === "undefined") return;
459
+ if (this._idleHandle !== null) {
460
+ if (this._usingIdleCallback && typeof window.cancelIdleCallback === "function") {
461
+ window.cancelIdleCallback(this._idleHandle);
462
+ } else {
463
+ clearTimeout(this._idleHandle);
464
+ }
465
+ this._idleHandle = null;
466
+ }
467
+ if (this._rafId !== null) {
468
+ cancelAnimationFrame(this._rafId);
469
+ this._rafId = null;
470
+ }
471
+ window.removeEventListener("scroll", this._onScroll);
472
+ window.removeEventListener("pointermove", this._onPointerMove);
473
+ window.removeEventListener("resize", this._onResize);
474
+ document.removeEventListener("visibilitychange", this._onVisibility);
475
+ if (this._themeObserver) {
476
+ this._themeObserver.disconnect();
477
+ this._themeObserver = null;
478
+ }
479
+ this._unbindExternalToggles();
480
+ }
481
+ attributeChangedCallback(name, oldVal, newVal) {
482
+ if (oldVal === newVal || !this._connected) return;
483
+ switch (name) {
484
+ case "mode":
485
+ if (newVal && MODES.includes(newVal) && newVal !== this._currentMode) {
486
+ this._setModeInternal(newVal, false, false);
487
+ }
488
+ break;
489
+ case "z-index":
490
+ this._syncZIndex();
491
+ break;
492
+ case "controls":
493
+ case "controls-position":
494
+ this._syncControlsVisibility();
495
+ break;
496
+ case "toggle-selector":
497
+ this._bindExternalToggles();
498
+ this._syncToggleAttributes();
499
+ break;
500
+ case "theme":
501
+ this._updateThemeState();
502
+ break;
503
+ case "surfaces":
504
+ case "text-surfaces":
505
+ this.refresh();
506
+ break;
507
+ case "floor":
508
+ if (!this._floorEnabled) this._bottomBins.fill(0);
509
+ break;
510
+ default:
511
+ break;
512
+ }
513
+ }
514
+ // --- Public Properties & Methods ---
515
+ get mode() {
516
+ return this._currentMode;
517
+ }
518
+ set mode(nextMode) {
519
+ const clean = String(nextMode || "").trim().toLowerCase();
520
+ if (!MODES.includes(clean)) return;
521
+ this._setModeInternal(clean, true, true);
522
+ }
523
+ get active() {
524
+ return this._currentMode !== "off";
525
+ }
526
+ cycleMode() {
527
+ const idx = MODES.indexOf(this._currentMode);
528
+ const next = MODES[(idx + 1) % MODES.length];
529
+ this._setModeInternal(next, true, true);
530
+ return next;
531
+ }
532
+ clearDrifts() {
533
+ this._bottomBins.fill(0);
534
+ this._chunks.length = 0;
535
+ for (const el of this._trackedElements) {
536
+ if (el && el.__snowDriftStore) {
537
+ const store = el.__snowDriftStore;
538
+ for (const key of Object.keys(store)) {
539
+ if (store[key] instanceof Float32Array) {
540
+ store[key].fill(0);
541
+ }
542
+ }
543
+ }
544
+ }
545
+ }
546
+ /**
547
+ * Pre-fills drifts across visible surfaces and floor (0..1 fraction of max height).
548
+ */
549
+ seedDrifts(fraction = 0.65) {
550
+ const f = Math.max(0.05, Math.min(1, Number(fraction) || 0.65));
551
+ if (this._w === 0) this._handleResize();
552
+ else this.refresh();
553
+ for (let i = 0; i < this._visibleSurfaces.length; i++) {
554
+ const surf = this._visibleSurfaces[i];
555
+ const textScale = surf.shape === "text" ? 0.52 : 1;
556
+ for (let b = surf.minBin; b <= surf.maxBin; b++) {
557
+ const sf = slopeFactor(surf, b, BIN_PX);
558
+ const wave = 0.78 + 0.22 * Math.sin(b * 0.28 + i * 1.7);
559
+ surf.bins[b] = Math.max(surf.bins[b], surf.maxH * f * textScale * sf * wave);
560
+ }
561
+ surf.bins[surf.minBin] *= 0.35;
562
+ surf.bins[surf.maxBin] *= 0.35;
563
+ }
564
+ if (this._floorEnabled && this._bottomBins.length > 2) {
565
+ const seedCap = Math.min(68, Math.max(30, this._h * 0.075));
566
+ for (let b = 0; b < this._bottomBins.length; b++) {
567
+ const wave = 0.72 + 0.28 * Math.sin(b * 0.14 + 0.8);
568
+ this._bottomBins[b] = Math.max(
569
+ this._bottomBins[b],
570
+ seedCap * f * 0.55 * wave
571
+ );
572
+ }
573
+ }
574
+ }
575
+ /**
576
+ * Triggers a snow avalanche on a specific element, all loaded surfaces ("all"),
577
+ * or the single fullest visible surface when omitted.
578
+ */
579
+ triggerAvalanche(target) {
580
+ if (!this.active) return 0;
581
+ this.refresh();
582
+ let candidates = [];
583
+ if (target === "all" || target && target.all === true) {
584
+ candidates = this._visibleSurfaces.filter((s) => this._surfaceMaxSnow(s) > 2.4);
585
+ } else if (typeof HTMLElement !== "undefined" && target instanceof HTMLElement) {
586
+ candidates = this._visibleSurfaces.filter((s) => s.el === target);
587
+ } else {
588
+ let best = null;
589
+ let bestScore = 2.4;
590
+ for (let i = 0; i < this._visibleSurfaces.length; i++) {
591
+ const s = this._visibleSurfaces[i];
592
+ const maxSnow = this._surfaceMaxSnow(s);
593
+ if (maxSnow > bestScore) {
594
+ bestScore = maxSnow;
595
+ best = s;
596
+ }
597
+ }
598
+ if (best) candidates = [best];
599
+ }
600
+ let triggered = 0;
601
+ for (const surf of candidates) {
602
+ let peakIdx = Math.round((surf.minBin + surf.maxBin) * 0.5);
603
+ let peakVal = -1;
604
+ for (let b = surf.minBin; b <= surf.maxBin; b++) {
605
+ if (surf.bins[b] > peakVal) {
606
+ peakVal = surf.bins[b];
607
+ peakIdx = b;
608
+ }
609
+ }
610
+ if (peakVal > 2.2) {
611
+ this._runAvalancheOnSurface(surf, peakIdx);
612
+ triggered++;
613
+ }
614
+ }
615
+ return triggered;
616
+ }
617
+ refresh() {
618
+ if (typeof window === "undefined" || !this._ctx) return;
619
+ this._lastScrollY = window.pageYOffset || document.documentElement.scrollTop || 0;
620
+ const list = [];
621
+ const textSel = (this.getAttribute("text-surfaces") || "").trim();
622
+ if (textSel) {
623
+ let textNodes = [];
624
+ try {
625
+ textNodes = document.querySelectorAll(textSel);
626
+ } catch (_) {
627
+ }
628
+ for (let t = 0; t < textNodes.length; t++) {
629
+ const el = textNodes[t];
630
+ if (el.hasAttribute("data-snow-ignore")) continue;
631
+ this._trackedElements.add(el);
632
+ this._collectWordSurfaces(el, list);
633
+ }
634
+ }
635
+ const surfSel = (this.getAttribute("surfaces") || "").trim();
636
+ if (surfSel) {
637
+ let nodes = [];
638
+ try {
639
+ nodes = document.querySelectorAll(surfSel);
640
+ } catch (_) {
641
+ }
642
+ for (let i = 0; i < nodes.length; i++) {
643
+ const el = nodes[i];
644
+ if (el.hasAttribute("data-snow-ignore")) continue;
645
+ if (el.offsetParent === null && window.getComputedStyle(el).position !== "fixed") {
646
+ continue;
647
+ }
648
+ const r = el.getBoundingClientRect();
649
+ if (r.width < 48 || r.height < 18) continue;
650
+ if (r.top < -50 || r.top > this._h + 90) continue;
651
+ this._trackedElements.add(el);
652
+ const cs = window.getComputedStyle(el);
653
+ const tlRad = parseBorderRadiusPx(cs.borderTopLeftRadius, Math.min(r.width, r.height));
654
+ const trRad = parseBorderRadiusPx(cs.borderTopRightRadius, Math.min(r.width, r.height));
655
+ const shape = classifySurfaceShape(
656
+ r.width,
657
+ r.height,
658
+ tlRad,
659
+ trRad,
660
+ el.getAttribute("data-snow-shape")
661
+ );
662
+ const bins = this._ensureElementBins(el, "main", r.width);
663
+ let padPx = 8;
664
+ let defaultMaxH = 20;
665
+ if (shape === "circle") {
666
+ padPx = r.width * 0.12;
667
+ defaultMaxH = Math.min(24, Math.max(12, r.width * 0.2));
668
+ } else if (shape === "pill") {
669
+ padPx = Math.min(20, r.height * 0.4);
670
+ defaultMaxH = 14;
671
+ } else {
672
+ padPx = Math.max(5, Math.min(16, Math.max(tlRad, trRad) * 0.65 || 8));
673
+ defaultMaxH = r.height < 44 ? 14 : Math.min(40, Math.max(20, Math.round(r.width * 0.07)));
674
+ }
675
+ const customMaxH = parseFloat(el.getAttribute("data-snow-max-height"));
676
+ const maxH = Number.isFinite(customMaxH) && customMaxH > 2 ? customMaxH : defaultMaxH;
677
+ const padBins = Math.max(1, Math.round(padPx / BIN_PX));
678
+ const maxBin = Math.max(padBins, bins.length - 1 - padBins);
679
+ if (maxBin <= padBins + 1) continue;
680
+ if (el.__snowStickyCached === void 0 || this._frameCounter % 120 === 0) {
681
+ el.__snowStickyCached = detectFixedOrSticky(el);
682
+ }
683
+ list.push({
684
+ el,
685
+ shape,
686
+ isSticky: Boolean(el.__snowStickyCached),
687
+ left: r.left,
688
+ right: r.right,
689
+ top: r.top,
690
+ width: r.width,
691
+ radius: shape === "circle" ? r.width * 0.5 : 0,
692
+ maxH,
693
+ bins,
694
+ baseProfile: null,
695
+ minBin: padBins,
696
+ maxBin,
697
+ cooldownUntil: el.__snowCooldown || 0
698
+ });
699
+ }
700
+ }
701
+ list.sort((a, b) => a.top - b.top);
702
+ this._visibleSurfaces = list;
703
+ }
704
+ // --- Internal Helpers ---
705
+ get _floorEnabled() {
706
+ return parseBoolAttr(this.getAttribute("floor"), true);
707
+ }
708
+ get _avalanchesEnabled() {
709
+ return parseBoolAttr(this.getAttribute("avalanches"), true);
710
+ }
711
+ get _interactiveEnabled() {
712
+ return parseBoolAttr(this.getAttribute("interactive"), true);
713
+ }
714
+ get _densityMultiplier() {
715
+ return parseNumAttr(this.getAttribute("density"), 1, 0.15, 4);
716
+ }
717
+ get _windMultiplier() {
718
+ return parseNumAttr(this.getAttribute("wind"), 1, 0, 4);
719
+ }
720
+ get _storageKey() {
721
+ const raw = this.getAttribute("storage-key");
722
+ if (raw === null) return DEFAULT_STORAGE_KEY;
723
+ const clean = raw.trim();
724
+ if (!clean || clean === "none" || clean === "false") return null;
725
+ return clean;
726
+ }
727
+ get _buryEnabled() {
728
+ const raw = (this.getAttribute("bury") || "blizzard").trim().toLowerCase();
729
+ if (raw === "true" || raw === "1" || raw === "always") return true;
730
+ if (raw === "false" || raw === "0" || raw === "never") return false;
731
+ return this._currentMode === "blizzard";
732
+ }
733
+ _maxBottomHeight() {
734
+ if (this._buryEnabled) return Math.max(68, this._h);
735
+ return Math.min(68, Math.max(30, this._h * 0.075));
736
+ }
737
+ _surfaceMaxSnow(surf) {
738
+ let m = 0;
739
+ for (let b = surf.minBin; b <= surf.maxBin; b++) {
740
+ if (surf.bins[b] > m) m = surf.bins[b];
741
+ }
742
+ return m;
743
+ }
744
+ _ensureElementBins(el, key, width) {
745
+ if (!el.__snowDriftStore) el.__snowDriftStore = {};
746
+ const bins = ensureBinsArray(el.__snowDriftStore[key], width, BIN_PX);
747
+ el.__snowDriftStore[key] = bins;
748
+ return bins;
749
+ }
750
+ _collectWordSurfaces(el, outList) {
751
+ const elRect = el.getBoundingClientRect();
752
+ if (elRect.width < 48 || elRect.height < 18) return;
753
+ if (elRect.top < -60 || elRect.top > this._h + 80) return;
754
+ const cs = window.getComputedStyle(el);
755
+ this._ctx.save();
756
+ this._ctx.font = `${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`;
757
+ const range = document.createRange();
758
+ const words = [];
759
+ let currentWord = null;
760
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
761
+ let textNode;
762
+ while (textNode = walker.nextNode()) {
763
+ const text = textNode.nodeValue || "";
764
+ for (let i = 0; i < text.length; i++) {
765
+ const ch = text[i];
766
+ if (/\s/.test(ch)) {
767
+ currentWord = null;
768
+ continue;
769
+ }
770
+ range.setStart(textNode, i);
771
+ range.setEnd(textNode, i + 1);
772
+ const r = range.getBoundingClientRect();
773
+ if (r.width <= 0 || r.height <= 0) continue;
774
+ let inkOffset;
775
+ const m = this._ctx.measureText(ch);
776
+ if (typeof m.fontBoundingBoxAscent === "number" && typeof m.actualBoundingBoxAscent === "number" && typeof m.fontBoundingBoxDescent === "number" && m.fontBoundingBoxAscent > 0) {
777
+ const fontBoxH = m.fontBoundingBoxAscent + m.fontBoundingBoxDescent;
778
+ const halfLeading = Math.max(0, (r.height - fontBoxH) * 0.5);
779
+ inkOffset = halfLeading + Math.max(0, m.fontBoundingBoxAscent - m.actualBoundingBoxAscent);
780
+ } else {
781
+ const isTall = /[A-Z0-9bdfhkltijĄĆĘŁŃÓŚŹŻÄÖÜß]/.test(ch);
782
+ inkOffset = r.height * (isTall ? 0.17 : 0.34);
783
+ }
784
+ const charInfo = {
785
+ left: r.left,
786
+ right: r.right,
787
+ top: r.top,
788
+ inkY: r.top + inkOffset
789
+ };
790
+ if (!currentWord || Math.abs(r.top - currentWord.lineTop) > r.height * 0.45) {
791
+ currentWord = { lineTop: r.top, chars: [charInfo] };
792
+ words.push(currentWord);
793
+ } else {
794
+ currentWord.chars.push(charInfo);
795
+ }
796
+ }
797
+ }
798
+ this._ctx.restore();
799
+ if (el.__snowStickyCached === void 0 || this._frameCounter % 120 === 0) {
800
+ el.__snowStickyCached = detectFixedOrSticky(el);
801
+ }
802
+ for (let wi = 0; wi < words.length; wi++) {
803
+ const chars = words[wi].chars;
804
+ if (chars.length === 0) continue;
805
+ let left = Infinity;
806
+ let right = -Infinity;
807
+ let top = Infinity;
808
+ for (let c = 0; c < chars.length; c++) {
809
+ if (chars[c].left < left) left = chars[c].left;
810
+ if (chars[c].right > right) right = chars[c].right;
811
+ if (chars[c].top < top) top = chars[c].top;
812
+ }
813
+ const width = right - left;
814
+ if (width < 22 || top < -40 || top > this._h + 80) continue;
815
+ const bins = this._ensureElementBins(el, `word_${wi}`, width);
816
+ const n = bins.length;
817
+ const profile = new Float32Array(n);
818
+ profile.fill(-1);
819
+ for (let c = 0; c < chars.length; c++) {
820
+ const ch = chars[c];
821
+ const bStart = Math.max(0, Math.floor((ch.left - left) / BIN_PX));
822
+ const bEnd = Math.min(n - 1, Math.ceil((ch.right - left) / BIN_PX));
823
+ const relY = ch.inkY - top;
824
+ for (let b = bStart; b <= bEnd; b++) {
825
+ if (profile[b] < 0 || relY < profile[b]) {
826
+ profile[b] = relY;
827
+ }
828
+ }
829
+ }
830
+ let lastValid = 0;
831
+ for (let b = 0; b < n; b++) {
832
+ if (profile[b] >= 0) lastValid = profile[b];
833
+ else profile[b] = lastValid;
834
+ }
835
+ const smoothed = new Float32Array(n);
836
+ smoothed[0] = profile[0];
837
+ smoothed[n - 1] = profile[n - 1];
838
+ for (let b = 1; b < n - 1; b++) {
839
+ smoothed[b] = (profile[b - 1] + profile[b] * 2 + profile[b + 1]) * 0.25;
840
+ }
841
+ const minBin = 1;
842
+ const maxBin = Math.max(minBin, n - 2);
843
+ if (maxBin <= minBin + 1) continue;
844
+ const fontPx = parseFloat(cs.fontSize) || 48;
845
+ const textMaxH = Math.min(10.5, Math.max(5.5, fontPx * 0.145));
846
+ outList.push({
847
+ el,
848
+ shape: "text",
849
+ isSticky: Boolean(el.__snowStickyCached),
850
+ left,
851
+ right,
852
+ top,
853
+ width,
854
+ radius: 0,
855
+ maxH: textMaxH,
856
+ bins,
857
+ baseProfile: smoothed,
858
+ minBin,
859
+ maxBin,
860
+ cooldownUntil: el.__snowCooldown || 0
861
+ });
862
+ }
863
+ }
864
+ _syncZIndex() {
865
+ const z = parseInt(this.getAttribute("z-index") || "9990", 10);
866
+ this.style.setProperty("--snow-drift-z", String(Number.isFinite(z) ? z : 9990));
867
+ }
868
+ _syncControlsVisibility() {
869
+ if (!this._builtinBtn) return;
870
+ const hasControls = this.hasAttribute("controls") && parseBoolAttr(this.getAttribute("controls"), true);
871
+ const posRaw = (this.getAttribute("controls-position") || "bottom-right").trim().toLowerCase();
872
+ const pos = ["bottom-right", "bottom-left", "top-right", "top-left"].includes(posRaw) ? posRaw : "bottom-right";
873
+ this._builtinBtn.setAttribute("data-visible", String(hasControls));
874
+ this._builtinBtn.setAttribute("data-pos", pos);
875
+ }
876
+ _resolveInitialMode() {
877
+ const respectRM = parseBoolAttr(this.getAttribute("respect-reduced-motion"), true);
878
+ const prefersReduced = respectRM && window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
879
+ let saved = null;
880
+ const key = this._storageKey;
881
+ if (key) {
882
+ try {
883
+ saved = localStorage.getItem(key);
884
+ } catch (_) {
885
+ }
886
+ }
887
+ const attrMode = (this.getAttribute("mode") || "").trim().toLowerCase();
888
+ if (saved && MODES.includes(saved)) {
889
+ this._currentMode = saved;
890
+ } else if (prefersReduced) {
891
+ this._currentMode = "off";
892
+ } else if (MODES.includes(attrMode)) {
893
+ this._currentMode = attrMode;
894
+ } else {
895
+ this._currentMode = "normal";
896
+ }
897
+ }
898
+ _applyInitialPreseed() {
899
+ if (this._didPreseed || !this.active) return;
900
+ const raw = this.getAttribute("preseed");
901
+ if (raw === null) return;
902
+ this._didPreseed = true;
903
+ const frac = raw.trim() === "" ? 0.55 : parseNumAttr(raw, 0.55, 0.05, 1);
904
+ this.seedDrifts(frac);
905
+ }
906
+ _updateThemeState() {
907
+ const explicit = (this.getAttribute("theme") || "auto").trim().toLowerCase();
908
+ if (explicit === "dark") {
909
+ this._isDark = true;
910
+ } else if (explicit === "light") {
911
+ this._isDark = false;
912
+ } else {
913
+ this._isDark = this._detectPageDark();
914
+ }
915
+ if (this._builtinBtn) {
916
+ this._builtinBtn.setAttribute("data-light", String(!this._isDark));
917
+ }
918
+ }
919
+ _detectPageDark() {
920
+ const docEl = document.documentElement;
921
+ const body = document.body;
922
+ const checkAttrs = ["data-theme", "data-scheme", "data-color-mode", "data-bs-theme"];
923
+ for (const node of [docEl, body]) {
924
+ if (!node) continue;
925
+ for (const attr of checkAttrs) {
926
+ const val = (node.getAttribute(attr) || "").toLowerCase();
927
+ if (val.includes("light")) return false;
928
+ if (val.includes("dark")) return true;
929
+ }
930
+ if (node.classList.contains("light") || node.classList.contains("theme-light")) {
931
+ return false;
932
+ }
933
+ if (node.classList.contains("dark") || node.classList.contains("theme-dark")) {
934
+ return true;
935
+ }
936
+ }
937
+ for (const node of [body, docEl]) {
938
+ if (!node) continue;
939
+ const lum = parseRgbLuminance(window.getComputedStyle(node).backgroundColor);
940
+ if (lum !== null) return lum < 140;
941
+ }
942
+ if (window.matchMedia && window.matchMedia("(prefers-color-scheme: light)").matches) {
943
+ return false;
944
+ }
945
+ return true;
946
+ }
947
+ _bindExternalToggles() {
948
+ this._unbindExternalToggles();
949
+ const selectors = ["[data-snow-drift-toggle]"];
950
+ const custom = (this.getAttribute("toggle-selector") || "").trim();
951
+ if (custom) selectors.push(custom);
952
+ let els = [];
953
+ try {
954
+ els = document.querySelectorAll(selectors.join(", "));
955
+ } catch (_) {
956
+ }
957
+ for (let i = 0; i < els.length; i++) {
958
+ const btn = els[i];
959
+ const onClick = (e) => {
960
+ e.preventDefault();
961
+ this.cycleMode();
962
+ };
963
+ const onKeyDown = (e) => {
964
+ if (btn.tagName !== "BUTTON" && (e.key === "Enter" || e.key === " ")) {
965
+ e.preventDefault();
966
+ this.cycleMode();
967
+ }
968
+ };
969
+ btn.addEventListener("click", onClick);
970
+ btn.addEventListener("keydown", onKeyDown);
971
+ this._boundExternalToggles.set(btn, { onClick, onKeyDown });
972
+ }
973
+ }
974
+ _unbindExternalToggles() {
975
+ for (const [btn, handlers] of this._boundExternalToggles.entries()) {
976
+ btn.removeEventListener("click", handlers.onClick);
977
+ btn.removeEventListener("keydown", handlers.onKeyDown);
978
+ }
979
+ this._boundExternalToggles.clear();
980
+ }
981
+ _syncToggleAttributes() {
982
+ const active = this.active;
983
+ const label = MODE_LABELS[this._currentMode] || "Snow: Normal";
984
+ if (this._builtinBtn && this._builtinLabel) {
985
+ this._builtinLabel.textContent = label;
986
+ this._builtinBtn.setAttribute("aria-pressed", String(active));
987
+ this._builtinBtn.setAttribute("data-snow-active", String(active));
988
+ this._builtinBtn.setAttribute("data-snow-mode", this._currentMode);
989
+ }
990
+ for (const btn of this._boundExternalToggles.keys()) {
991
+ btn.setAttribute("aria-pressed", String(active));
992
+ btn.setAttribute("data-snow-active", String(active));
993
+ btn.setAttribute("data-snow-mode", this._currentMode);
994
+ const labelTarget = btn.querySelector("[data-snow-drift-label]");
995
+ if (labelTarget) {
996
+ labelTarget.textContent = label;
997
+ }
998
+ }
999
+ }
1000
+ _setModeInternal(nextMode, persist, emitEvent) {
1001
+ this._currentMode = nextMode;
1002
+ if (this.getAttribute("mode") !== nextMode) {
1003
+ this.setAttribute("mode", nextMode);
1004
+ }
1005
+ if (persist && this._storageKey) {
1006
+ try {
1007
+ localStorage.setItem(this._storageKey, nextMode);
1008
+ } catch (_) {
1009
+ }
1010
+ }
1011
+ this._syncModeState(false);
1012
+ if (emitEvent) {
1013
+ this.dispatchEvent(
1014
+ new CustomEvent("snow-drift:change", {
1015
+ bubbles: true,
1016
+ composed: true,
1017
+ detail: { mode: nextMode, active: this.active }
1018
+ })
1019
+ );
1020
+ }
1021
+ }
1022
+ _syncModeState(seedInitialFlakes) {
1023
+ const active = this.active;
1024
+ this._syncToggleAttributes();
1025
+ if (this._canvas) {
1026
+ this._canvas.style.display = active ? "block" : "none";
1027
+ }
1028
+ if (active) {
1029
+ if (this._w === 0) this._handleResize();
1030
+ else this.refresh();
1031
+ this._pickNewWeatherTargets(true);
1032
+ if (this._currentMode === "blizzard") {
1033
+ this._windTarget = (Math.random() < 0.5 ? -1 : 1) * (1.8 + Math.random() * 1.2) * this._windMultiplier;
1034
+ this._gustFramesLeft = 260;
1035
+ }
1036
+ if (seedInitialFlakes) {
1037
+ const want = this._desiredFlakeCount();
1038
+ let countNow = 0;
1039
+ for (let i = 0; i < this._flakes.length; i++) {
1040
+ if (this._flakes[i].active) countNow++;
1041
+ }
1042
+ for (let i = 0; i < this._flakes.length && countNow < want; i++) {
1043
+ if (!this._flakes[i].active) {
1044
+ this._flakes[i].active = true;
1045
+ this._spawnFlakeCoords(this._flakes[i], true);
1046
+ countNow++;
1047
+ }
1048
+ }
1049
+ }
1050
+ if (!this._rafId && !document.hidden) {
1051
+ this._rafId = requestAnimationFrame(this._tickBound);
1052
+ }
1053
+ } else {
1054
+ if (this._rafId !== null) {
1055
+ cancelAnimationFrame(this._rafId);
1056
+ this._rafId = null;
1057
+ }
1058
+ for (let i = 0; i < this._flakes.length; i++) {
1059
+ this._flakes[i].active = false;
1060
+ }
1061
+ this.clearDrifts();
1062
+ if (this._w > 0 && this._ctx) {
1063
+ this._ctx.clearRect(0, 0, this._w, this._h);
1064
+ }
1065
+ }
1066
+ }
1067
+ _spawnFlakeCoords(f, initialSpread) {
1068
+ f.fg = Math.random() < 0.34;
1069
+ if (initialSpread) {
1070
+ f.x = Math.random() * Math.max(this._w, 320);
1071
+ f.y = Math.random() * Math.max(this._h, 320);
1072
+ return;
1073
+ }
1074
+ const absWind = Math.abs(this._windCurrent);
1075
+ if (absWind > 0.55 && this._bottomBins.length > 2) {
1076
+ const fromLeft = this._windCurrent > 0;
1077
+ const edgeBin = fromLeft ? 0 : this._bottomBins.length - 1;
1078
+ const openSkyH = Math.max(0, this._h - this._bottomBins[edgeBin] - 24);
1079
+ const skyRatio = this._h > 0 ? openSkyH / this._h : 0;
1080
+ if (openSkyH > 48 && Math.random() < Math.min(0.38, absWind * 0.14) * skyRatio) {
1081
+ f.x = fromLeft ? -6 - Math.random() * 10 : this._w + 6 + Math.random() * 10;
1082
+ f.y = Math.random() * openSkyH * 0.85;
1083
+ return;
1084
+ }
1085
+ }
1086
+ f.x = Math.random() * this._w;
1087
+ f.y = -8 - Math.random() * 36;
1088
+ }
1089
+ _makeFlake(active, initialSpread) {
1090
+ const r = 1.05 + Math.random() * 2.55;
1091
+ const f = {
1092
+ active,
1093
+ fg: false,
1094
+ x: 0,
1095
+ y: 0,
1096
+ r,
1097
+ vy: 0.52 + r * 0.34 + Math.random() * 0.55,
1098
+ vx: -0.22 + Math.random() * 0.44,
1099
+ windSens: 0.65 + (3.8 - r) * 0.28,
1100
+ phase: Math.random() * Math.PI * 2,
1101
+ alpha: 0.28 + Math.random() * 0.54
1102
+ };
1103
+ this._spawnFlakeCoords(f, initialSpread);
1104
+ return f;
1105
+ }
1106
+ _ensurePool(initialSpread) {
1107
+ const cap = this._w < 768 ? 200 : MAX_POOL;
1108
+ while (this._flakes.length < cap) {
1109
+ this._flakes.push(this._makeFlake(false, initialSpread));
1110
+ }
1111
+ if (this._flakes.length > cap) {
1112
+ this._flakes.length = cap;
1113
+ }
1114
+ }
1115
+ _desiredFlakeCount() {
1116
+ if (!this.active) return 0;
1117
+ const base = Math.min(115, Math.max(48, Math.floor(this._w / 13.5)));
1118
+ const raw = Math.round(base * this._densityWaveFactor * this._densityMultiplier);
1119
+ const cap = this._w < 768 ? 200 : MAX_POOL;
1120
+ return Math.max(14, Math.min(cap, raw));
1121
+ }
1122
+ _pickNewWeatherTargets(immediate) {
1123
+ const cfg = modeConfig(this._currentMode);
1124
+ this._densityTargetFactor = cfg.minMult + Math.random() * (cfg.maxMult - cfg.minMult);
1125
+ if (immediate) this._densityWaveFactor = this._densityTargetFactor;
1126
+ this._nextDensityShiftFrame = this._frameCounter + Math.round(360 + Math.random() * 620);
1127
+ }
1128
+ _updateWeather() {
1129
+ const cfg = modeConfig(this._currentMode);
1130
+ const windMult = this._windMultiplier;
1131
+ if (this._frameCounter >= this._nextDensityShiftFrame) {
1132
+ this._pickNewWeatherTargets(false);
1133
+ }
1134
+ this._densityWaveFactor += (this._densityTargetFactor - this._densityWaveFactor) * 8e-3;
1135
+ if (this._gustFramesLeft > 0) {
1136
+ this._gustFramesLeft--;
1137
+ if (this._gustFramesLeft === 0) {
1138
+ this._windTarget = (this._currentMode === "blizzard" ? (Math.random() < 0.5 ? -1 : 1) * (0.6 + Math.random() * 0.8) : -0.18 + Math.random() * 0.36) * windMult;
1139
+ this._nextGustFrame = this._frameCounter + Math.round(
1140
+ cfg.gustMinWait + Math.random() * (cfg.gustMaxWait - cfg.gustMinWait)
1141
+ );
1142
+ }
1143
+ } else if (this._frameCounter >= this._nextGustFrame) {
1144
+ const dir = Math.random() < 0.5 ? -1 : 1;
1145
+ const strength = (cfg.gustStrengthMin + Math.random() * (cfg.gustStrengthMax - cfg.gustStrengthMin)) * windMult;
1146
+ this._windTarget = dir * strength;
1147
+ this._gustFramesLeft = Math.round(160 + Math.random() * 260);
1148
+ }
1149
+ const gustFlutter = this._gustFramesLeft > 0 ? Math.sin(this._frameCounter * 0.045) * 0.18 * windMult : 0;
1150
+ this._windCurrent += (this._windTarget + gustFlutter - this._windCurrent) * 0.022;
1151
+ }
1152
+ _runAvalancheOnSurface(surf, peakIdx) {
1153
+ const budget = Math.max(0, MAX_CHUNKS - this._chunks.length);
1154
+ const spawned = shearAvalanche(
1155
+ surf,
1156
+ peakIdx,
1157
+ this._windCurrent,
1158
+ BIN_PX,
1159
+ budget
1160
+ );
1161
+ for (let i = 0; i < spawned.length; i++) {
1162
+ this._chunks.push(spawned[i]);
1163
+ }
1164
+ surf.cooldownUntil = this._frameCounter + 95;
1165
+ if (surf.el) surf.el.__snowCooldown = surf.cooldownUntil;
1166
+ this.dispatchEvent(
1167
+ new CustomEvent("snow-drift:avalanche", {
1168
+ bubbles: true,
1169
+ composed: true,
1170
+ detail: { element: surf.el || null, shape: surf.shape }
1171
+ })
1172
+ );
1173
+ }
1174
+ _checkAvalanches() {
1175
+ if (!this._avalanchesEnabled) return;
1176
+ for (let i = 0; i < this._visibleSurfaces.length; i++) {
1177
+ const surf = this._visibleSurfaces[i];
1178
+ if (this._frameCounter < surf.cooldownUntil) continue;
1179
+ if (surf.top < -8 || surf.top > this._h - 16) continue;
1180
+ const hit = findAvalanchePeak(surf, this._windCurrent, BIN_PX);
1181
+ if (hit && (hit.ratio >= 1.02 || hit.ratio >= 0.96 && Math.random() < 0.25)) {
1182
+ this._runAvalancheOnSurface(surf, hit.peakIdx);
1183
+ }
1184
+ }
1185
+ }
1186
+ _drawSurfaceDrift(surf, isDark) {
1187
+ const arr = surf.bins;
1188
+ const startBin = surf.minBin;
1189
+ const endBin = surf.maxBin;
1190
+ if (endBin <= startBin + 1) return;
1191
+ const ctx = this._ctx;
1192
+ let idx = startBin;
1193
+ while (idx <= endBin) {
1194
+ while (idx <= endBin && arr[idx] <= 0.22) idx++;
1195
+ if (idx > endBin) break;
1196
+ const runStart = Math.max(startBin, idx - 1);
1197
+ while (idx <= endBin && arr[idx] > 0.22) idx++;
1198
+ const runEnd = Math.min(endBin, idx);
1199
+ if (runEnd <= runStart) continue;
1200
+ let minBaseY = Infinity;
1201
+ let maxBaseY = -Infinity;
1202
+ for (let k = runStart; k <= runEnd; k++) {
1203
+ const by = baseSurfaceY(surf, k, BIN_PX);
1204
+ if (by < minBaseY) minBaseY = by;
1205
+ if (by > maxBaseY) maxBaseY = by;
1206
+ }
1207
+ const grad = ctx.createLinearGradient(0, minBaseY - surf.maxH, 0, maxBaseY + 2);
1208
+ if (isDark) {
1209
+ grad.addColorStop(0, "rgba(242, 248, 255, 0.92)");
1210
+ grad.addColorStop(1, "rgba(198, 216, 236, 0.96)");
1211
+ } else {
1212
+ grad.addColorStop(0, "rgba(218, 234, 250, 0.95)");
1213
+ grad.addColorStop(1, "rgba(168, 198, 228, 0.97)");
1214
+ }
1215
+ ctx.beginPath();
1216
+ const firstX = surf.left + runStart * BIN_PX;
1217
+ const firstBaseY = baseSurfaceY(surf, runStart, BIN_PX);
1218
+ ctx.moveTo(firstX, firstBaseY);
1219
+ ctx.lineTo(firstX, firstBaseY - arr[runStart]);
1220
+ for (let j = runStart + 1; j < runEnd; j++) {
1221
+ const x0 = surf.left + j * BIN_PX;
1222
+ const y0 = baseSurfaceY(surf, j, BIN_PX) - arr[j];
1223
+ const x1 = surf.left + (j + 1) * BIN_PX;
1224
+ const y1 = baseSurfaceY(surf, j + 1, BIN_PX) - arr[j + 1];
1225
+ ctx.quadraticCurveTo(x0, y0, (x0 + x1) * 0.5, (y0 + y1) * 0.5);
1226
+ }
1227
+ const lastX = surf.left + runEnd * BIN_PX;
1228
+ const lastBaseY = baseSurfaceY(surf, runEnd, BIN_PX);
1229
+ ctx.lineTo(lastX, lastBaseY - arr[runEnd]);
1230
+ ctx.lineTo(lastX, lastBaseY);
1231
+ if (surf.shape === "circle" || surf.baseProfile) {
1232
+ for (let b = runEnd - 1; b >= runStart; b--) {
1233
+ ctx.lineTo(surf.left + b * BIN_PX, baseSurfaceY(surf, b, BIN_PX));
1234
+ }
1235
+ }
1236
+ ctx.closePath();
1237
+ ctx.fillStyle = grad;
1238
+ ctx.fill();
1239
+ if (!isDark) {
1240
+ ctx.strokeStyle = "rgba(132, 170, 208, 0.52)";
1241
+ ctx.lineWidth = 0.9;
1242
+ ctx.stroke();
1243
+ }
1244
+ }
1245
+ }
1246
+ _drawBottomDrift(maxH, isDark) {
1247
+ if (!this._floorEnabled) return;
1248
+ const endBin = this._bottomBins.length - 1;
1249
+ if (endBin <= 1) return;
1250
+ let peak = 0;
1251
+ for (let i = 0; i <= endBin; i++) {
1252
+ if (this._bottomBins[i] > peak) peak = this._bottomBins[i];
1253
+ }
1254
+ if (peak <= 0.25) return;
1255
+ const ctx = this._ctx;
1256
+ const grad = ctx.createLinearGradient(
1257
+ 0,
1258
+ Math.max(0, this._h - peak - 8),
1259
+ 0,
1260
+ this._h
1261
+ );
1262
+ if (isDark) {
1263
+ grad.addColorStop(0, "rgba(244, 249, 255, 0.92)");
1264
+ grad.addColorStop(0.4, "rgba(218, 232, 246, 0.95)");
1265
+ grad.addColorStop(1, "rgba(188, 210, 234, 0.97)");
1266
+ } else {
1267
+ grad.addColorStop(0, "rgba(218, 234, 250, 0.94)");
1268
+ grad.addColorStop(1, "rgba(170, 200, 230, 0.97)");
1269
+ }
1270
+ ctx.beginPath();
1271
+ ctx.moveTo(0, this._h);
1272
+ ctx.lineTo(0, this._h - this._bottomBins[0]);
1273
+ for (let j = 1; j < endBin; j++) {
1274
+ const x0 = j * BIN_PX;
1275
+ const y0 = this._h - this._bottomBins[j];
1276
+ const x1 = (j + 1) * BIN_PX;
1277
+ const y1 = this._h - this._bottomBins[j + 1];
1278
+ ctx.quadraticCurveTo(x0, y0, (x0 + x1) * 0.5, (y0 + y1) * 0.5);
1279
+ }
1280
+ ctx.lineTo(endBin * BIN_PX, this._h - this._bottomBins[endBin]);
1281
+ ctx.lineTo(endBin * BIN_PX, this._h);
1282
+ ctx.closePath();
1283
+ ctx.fillStyle = grad;
1284
+ ctx.fill();
1285
+ if (!isDark) {
1286
+ ctx.strokeStyle = "rgba(132, 170, 208, 0.5)";
1287
+ ctx.lineWidth = 0.9;
1288
+ ctx.stroke();
1289
+ }
1290
+ for (const btn of this._boundExternalToggles.keys()) {
1291
+ if (!btn || btn.offsetParent === null) continue;
1292
+ const tr = btn.getBoundingClientRect();
1293
+ if (tr.width < 16 || tr.height < 16) continue;
1294
+ const midBin = Math.max(
1295
+ 0,
1296
+ Math.min(endBin, Math.round((tr.left + tr.width * 0.5) / BIN_PX))
1297
+ );
1298
+ if (this._h - this._bottomBins[midBin] < tr.bottom + 4) {
1299
+ ctx.save();
1300
+ ctx.globalCompositeOperation = "destination-out";
1301
+ const pad = 4;
1302
+ ctx.beginPath();
1303
+ if (ctx.roundRect) {
1304
+ ctx.roundRect(tr.left - pad, tr.top - pad, tr.width + pad * 2, tr.height + pad * 2, 10);
1305
+ } else {
1306
+ ctx.rect(tr.left - pad, tr.top - pad, tr.width + pad * 2, tr.height + pad * 2);
1307
+ }
1308
+ ctx.fillStyle = "rgba(0, 0, 0, 0.92)";
1309
+ ctx.fill();
1310
+ ctx.restore();
1311
+ }
1312
+ }
1313
+ }
1314
+ _tick() {
1315
+ if (!this.active || document.hidden || !this._connected) {
1316
+ this._rafId = null;
1317
+ return;
1318
+ }
1319
+ this._frameCounter++;
1320
+ if (this._frameCounter % 12 === 0) {
1321
+ this.refresh();
1322
+ }
1323
+ this._updateWeather();
1324
+ if (this._frameCounter % 15 === 0) {
1325
+ this._checkAvalanches();
1326
+ }
1327
+ const maxBottomH = this._maxBottomHeight();
1328
+ if (this._frameCounter % 2 === 0 && this._floorEnabled && this._bottomBins.length > 2) {
1329
+ for (let rp = 0; rp < 3; rp++) {
1330
+ relaxRange(this._bottomBins, 0, this._bottomBins.length - 1, maxBottomH);
1331
+ }
1332
+ }
1333
+ if (this._frameCounter % 30 === 0 && this._floorEnabled && !this._buryEnabled) {
1334
+ for (let cb = 0; cb < this._bottomBins.length; cb++) {
1335
+ if (this._bottomBins[cb] > maxBottomH) {
1336
+ this._bottomBins[cb] = maxBottomH + (this._bottomBins[cb] - maxBottomH) * 0.88;
1337
+ } else if (this._bottomBins[cb] > 42) {
1338
+ this._bottomBins[cb] *= 0.99;
1339
+ }
1340
+ }
1341
+ }
1342
+ const cfg = modeConfig(this._currentMode);
1343
+ const targetActive = this._desiredFlakeCount();
1344
+ let activeNow = 0;
1345
+ for (let a = 0; a < this._flakes.length; a++) {
1346
+ if (this._flakes[a].active) activeNow++;
1347
+ }
1348
+ let spawnBudget = Math.min(2, Math.max(0, targetActive - activeNow));
1349
+ if (spawnBudget > 0) {
1350
+ for (let sp = 0; sp < this._flakes.length && spawnBudget > 0; sp++) {
1351
+ if (!this._flakes[sp].active) {
1352
+ this._flakes[sp].active = true;
1353
+ this._spawnFlakeCoords(this._flakes[sp], false);
1354
+ activeNow++;
1355
+ spawnBudget--;
1356
+ }
1357
+ }
1358
+ }
1359
+ const isDark = this._isDark;
1360
+ const ctx = this._ctx;
1361
+ ctx.clearRect(0, 0, this._w, this._h);
1362
+ const interactive = this._interactiveEnabled;
1363
+ const floorOn = this._floorEnabled;
1364
+ for (let i = 0; i < this._flakes.length; i++) {
1365
+ const f = this._flakes[i];
1366
+ if (!f.active) continue;
1367
+ f.phase += 0.014 * cfg.speedMult;
1368
+ f.y += f.vy * cfg.speedMult;
1369
+ f.x += f.vx + this._windCurrent * f.windSens + Math.sin(f.phase) * 0.35;
1370
+ if (interactive) {
1371
+ const dx = f.x - this._mouseX;
1372
+ const dy = f.y - this._mouseY;
1373
+ const d2 = dx * dx + dy * dy;
1374
+ if (d2 < 1600 && d2 > 1) {
1375
+ const inv = 1 / Math.sqrt(d2);
1376
+ f.x += dx * inv * 2.2;
1377
+ f.y += dy * inv * 1.4;
1378
+ }
1379
+ }
1380
+ if (f.x > this._w + 16) {
1381
+ const leftGroundY = this._h - (this._bottomBins[0] || 0);
1382
+ if (floorOn && f.y >= leftGroundY - 18) {
1383
+ this._spawnFlakeCoords(f, false);
1384
+ continue;
1385
+ }
1386
+ f.x = -8;
1387
+ } else if (f.x < -16) {
1388
+ const rightGroundY = this._h - (this._bottomBins[this._bottomBins.length - 1] || 0);
1389
+ if (floorOn && f.y >= rightGroundY - 18) {
1390
+ this._spawnFlakeCoords(f, false);
1391
+ continue;
1392
+ }
1393
+ f.x = this._w + 8;
1394
+ }
1395
+ let recycled = false;
1396
+ if (f.x >= 0 && f.x <= this._w) {
1397
+ const gBin = Math.max(
1398
+ 0,
1399
+ Math.min(this._bottomBins.length - 1, Math.round(f.x / BIN_PX))
1400
+ );
1401
+ const groundY = floorOn ? this._h - this._bottomBins[gBin] : this._h + 999;
1402
+ if (floorOn && f.y >= groundY - f.r) {
1403
+ depositBottom(this._bottomBins, f.x / BIN_PX, f.r, maxBottomH, cfg.depositMult);
1404
+ recycled = true;
1405
+ } else if (!f.fg) {
1406
+ for (let sIdx = 0; sIdx < this._visibleSurfaces.length; sIdx++) {
1407
+ const surf = this._visibleSurfaces[sIdx];
1408
+ if (surf.top < -10 || surf.top >= groundY || surf.top > this._h - 14) continue;
1409
+ const minX = surf.left + surf.minBin * BIN_PX;
1410
+ const maxX = surf.left + surf.maxBin * BIN_PX;
1411
+ if (f.x < minX || f.x > maxX) continue;
1412
+ const localBin = (f.x - surf.left) / BIN_PX;
1413
+ const bIdx = Math.max(surf.minBin, Math.min(surf.maxBin, Math.round(localBin)));
1414
+ const baseY = baseSurfaceY(surf, bIdx, BIN_PX);
1415
+ if (baseY < 6 || baseY >= groundY || baseY > this._h - 12) continue;
1416
+ const topSurfaceY = baseY - surf.bins[bIdx];
1417
+ if (f.y >= topSurfaceY - f.r && f.y <= baseY + 4.5) {
1418
+ depositOnSurface(surf, localBin, f.r * 0.88, cfg.depositMult, BIN_PX);
1419
+ recycled = true;
1420
+ break;
1421
+ }
1422
+ }
1423
+ } else if (!floorOn && f.y > this._h + 8) {
1424
+ recycled = true;
1425
+ }
1426
+ if (!recycled && !floorOn && f.y > this._h + 8) {
1427
+ recycled = true;
1428
+ }
1429
+ } else if (f.y > this._h + 12) {
1430
+ recycled = true;
1431
+ }
1432
+ if (recycled) {
1433
+ if (activeNow > targetActive) {
1434
+ f.active = false;
1435
+ activeNow--;
1436
+ continue;
1437
+ }
1438
+ this._spawnFlakeCoords(f, false);
1439
+ }
1440
+ ctx.beginPath();
1441
+ ctx.arc(f.x, f.y, f.r, 0, Math.PI * 2);
1442
+ ctx.fillStyle = isDark ? `rgba(232, 240, 248, ${f.alpha.toFixed(2)})` : `rgba(112, 152, 192, ${(f.alpha * 0.92).toFixed(2)})`;
1443
+ ctx.fill();
1444
+ }
1445
+ for (let k = this._chunks.length - 1; k >= 0; k--) {
1446
+ const ch = this._chunks[k];
1447
+ ch.vy = Math.min(5.6, ch.vy + 0.095);
1448
+ ch.vx = ch.vx * 0.992 + this._windCurrent * 0.012;
1449
+ ch.x += ch.vx;
1450
+ ch.y += ch.vy;
1451
+ ch.alpha -= 3e-3;
1452
+ if (ch.alpha <= 0.06 || ch.x < 0 || ch.x > this._w || ch.y > this._h + 24) {
1453
+ this._chunks.splice(k, 1);
1454
+ continue;
1455
+ }
1456
+ let caught = false;
1457
+ for (let cs = 0; cs < this._visibleSurfaces.length; cs++) {
1458
+ const cSurf = this._visibleSurfaces[cs];
1459
+ if (cSurf.el && cSurf.el === ch.originEl) continue;
1460
+ if (cSurf.top < 12 || cSurf.top > this._h - 18) continue;
1461
+ const cMinX = cSurf.left + cSurf.minBin * BIN_PX;
1462
+ const cMaxX = cSurf.left + cSurf.maxBin * BIN_PX;
1463
+ if (ch.x < cMinX || ch.x > cMaxX) continue;
1464
+ const cLocal = (ch.x - cSurf.left) / BIN_PX;
1465
+ const cBin = Math.max(cSurf.minBin, Math.min(cSurf.maxBin, Math.round(cLocal)));
1466
+ const cBase = baseSurfaceY(cSurf, cBin, BIN_PX);
1467
+ const cTop = cBase - cSurf.bins[cBin];
1468
+ if (ch.y >= cTop - ch.r && ch.y <= cBase + 6 && Math.random() < 0.44) {
1469
+ depositOnSurface(cSurf, cLocal, ch.r * 1.15, 1.15, BIN_PX);
1470
+ caught = true;
1471
+ break;
1472
+ }
1473
+ }
1474
+ if (caught) {
1475
+ this._chunks.splice(k, 1);
1476
+ continue;
1477
+ }
1478
+ if (floorOn) {
1479
+ const bgBin = Math.max(
1480
+ 0,
1481
+ Math.min(this._bottomBins.length - 1, Math.round(ch.x / BIN_PX))
1482
+ );
1483
+ if (ch.y >= this._h - this._bottomBins[bgBin] - ch.r) {
1484
+ depositBottom(this._bottomBins, ch.x / BIN_PX, ch.r * 0.95, maxBottomH, 1);
1485
+ this._chunks.splice(k, 1);
1486
+ continue;
1487
+ }
1488
+ }
1489
+ ctx.beginPath();
1490
+ ctx.arc(ch.x, ch.y, ch.r, 0, Math.PI * 2);
1491
+ ctx.fillStyle = isDark ? `rgba(238, 246, 255, ${ch.alpha.toFixed(2)})` : `rgba(128, 166, 204, ${ch.alpha.toFixed(2)})`;
1492
+ ctx.fill();
1493
+ }
1494
+ for (let d = 0; d < this._visibleSurfaces.length; d++) {
1495
+ const vs = this._visibleSurfaces[d];
1496
+ if (vs.top > -32 && vs.top < this._h + 20) {
1497
+ this._drawSurfaceDrift(vs, isDark);
1498
+ }
1499
+ }
1500
+ this._drawBottomDrift(maxBottomH, isDark);
1501
+ this._rafId = requestAnimationFrame(this._tickBound);
1502
+ }
1503
+ _handleScroll() {
1504
+ if (!this.active || this._visibleSurfaces.length === 0) return;
1505
+ const curY = window.pageYOffset || document.documentElement.scrollTop || 0;
1506
+ const dy = curY - this._lastScrollY;
1507
+ this._lastScrollY = curY;
1508
+ if (dy !== 0) {
1509
+ for (let i = 0; i < this._visibleSurfaces.length; i++) {
1510
+ if (!this._visibleSurfaces[i].isSticky) {
1511
+ this._visibleSurfaces[i].top -= dy;
1512
+ }
1513
+ }
1514
+ }
1515
+ }
1516
+ _handlePointerMove(e) {
1517
+ const prevX = this._mouseX;
1518
+ this._mouseX = e.clientX;
1519
+ this._mouseY = e.clientY;
1520
+ if (!this.active || !this._interactiveEnabled) return;
1521
+ const vxHint = prevX > -9e3 ? Math.max(-4, Math.min(4, (e.clientX - prevX) * 0.18)) : 0;
1522
+ if (this._floorEnabled && this._bottomBins.length > 0) {
1523
+ const bc = Math.max(
1524
+ 0,
1525
+ Math.min(this._bottomBins.length - 1, Math.round(this._mouseX / BIN_PX))
1526
+ );
1527
+ let brushedFloor = 0;
1528
+ for (let k = -10; k <= 10; k++) {
1529
+ const bIdx = bc + k;
1530
+ if (bIdx < 0 || bIdx >= this._bottomBins.length) continue;
1531
+ const snowTopY = this._h - this._bottomBins[bIdx];
1532
+ if (this._mouseY >= snowTopY - 24) {
1533
+ const falloff = 1 - Math.abs(k) / 11;
1534
+ const targetDepth = Math.max(0, this._h - this._mouseY - 18 * falloff);
1535
+ const shaved = this._bottomBins[bIdx] - 15 * falloff;
1536
+ const before = this._bottomBins[bIdx];
1537
+ const after = Math.max(0, Math.min(before, Math.max(targetDepth, shaved)));
1538
+ brushedFloor += before - after;
1539
+ this._bottomBins[bIdx] = after;
1540
+ }
1541
+ }
1542
+ if (brushedFloor > 6 && this._chunks.length < MAX_CHUNKS) {
1543
+ this._chunks.push({
1544
+ x: this._mouseX + (-4 + Math.random() * 8),
1545
+ y: Math.min(this._h - 8, this._mouseY + 4),
1546
+ r: 1.4 + Math.random() * 1.8,
1547
+ vx: vxHint + (-0.8 + Math.random() * 1.6),
1548
+ vy: -1.4 - Math.random() * 1.4,
1549
+ alpha: 0.72,
1550
+ originEl: null
1551
+ });
1552
+ }
1553
+ }
1554
+ for (let i = 0; i < this._visibleSurfaces.length; i++) {
1555
+ const surf = this._visibleSurfaces[i];
1556
+ if (this._mouseX < surf.left - 14 || this._mouseX > surf.right + 14) continue;
1557
+ const lc = Math.round((this._mouseX - surf.left) / BIN_PX);
1558
+ let brushed = 0;
1559
+ for (let m = -8; m <= 8; m++) {
1560
+ const cIdx = lc + m;
1561
+ if (cIdx < surf.minBin || cIdx > surf.maxBin) continue;
1562
+ const by = baseSurfaceY(surf, cIdx, BIN_PX);
1563
+ if (Math.abs(this._mouseY - (by - surf.bins[cIdx] * 0.5)) < 26) {
1564
+ const before = surf.bins[cIdx];
1565
+ const after = Math.max(0, before - 9 * (1 - Math.abs(m) / 9));
1566
+ brushed += before - after;
1567
+ surf.bins[cIdx] = after;
1568
+ }
1569
+ }
1570
+ if (brushed > 5 && this._chunks.length < MAX_CHUNKS) {
1571
+ this._chunks.push({
1572
+ x: this._mouseX + (-3 + Math.random() * 6),
1573
+ y: this._mouseY - 2,
1574
+ r: 1.3 + Math.random() * 1.9,
1575
+ vx: vxHint + (-0.9 + Math.random() * 1.8),
1576
+ vy: -1.2 - Math.random() * 1.2,
1577
+ alpha: 0.74,
1578
+ originEl: surf.el || null
1579
+ });
1580
+ }
1581
+ }
1582
+ }
1583
+ _handleResize() {
1584
+ if (!this._canvas || !this._ctx) return;
1585
+ const dpr = Math.min(window.devicePixelRatio || 1, 2);
1586
+ this._w = window.innerWidth || document.documentElement.clientWidth || 1280;
1587
+ this._h = window.innerHeight || document.documentElement.clientHeight || 720;
1588
+ this._canvas.width = Math.floor(this._w * dpr);
1589
+ this._canvas.height = Math.floor(this._h * dpr);
1590
+ this._ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
1591
+ this._bottomBins = ensureBinsArray(this._bottomBins, this._w, BIN_PX);
1592
+ this._ensurePool(true);
1593
+ this.refresh();
1594
+ }
1595
+ _handleVisibility() {
1596
+ if (document.hidden && this._rafId !== null) {
1597
+ cancelAnimationFrame(this._rafId);
1598
+ this._rafId = null;
1599
+ } else if (!document.hidden && this.active && this._rafId === null) {
1600
+ this.refresh();
1601
+ this._rafId = requestAnimationFrame(this._tickBound);
1602
+ }
1603
+ }
1604
+ };
1605
+ function defineSnowDrift(tagName = "snow-drift") {
1606
+ if (typeof window !== "undefined" && typeof customElements !== "undefined" && !customElements.get(tagName)) {
1607
+ customElements.define(tagName, SnowDriftElement);
1608
+ }
1609
+ return SnowDriftElement;
1610
+ }
1611
+ defineSnowDrift();