zum-framework 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.
package/dist/zum.cjs ADDED
@@ -0,0 +1,3615 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
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
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
20
+
21
+ // Zum.js
22
+ var Zum_exports = {};
23
+ __export(Zum_exports, {
24
+ Zum: () => Zum,
25
+ ZumActivity: () => ZumActivity,
26
+ default: () => Zum_default
27
+ });
28
+ module.exports = __toCommonJS(Zum_exports);
29
+ var hasDOM = () => typeof window !== "undefined" && typeof document !== "undefined";
30
+ var ZumRef = { _debugEnabled: false };
31
+ var ZUM_DEBUG = typeof window !== "undefined" && (window.__ZUM_DEBUG__ === true || typeof process !== "undefined" && process.env && process.env.NODE_ENV !== "production");
32
+ var zlog = (...a) => {
33
+ if (ZUM_DEBUG || ZumRef._debugEnabled) console.log(...a);
34
+ };
35
+ var zwarn = (...a) => {
36
+ if (ZUM_DEBUG || ZumRef._debugEnabled) console.warn(...a);
37
+ };
38
+ var zerr = (...a) => {
39
+ console.error(...a);
40
+ };
41
+ var _Zum = class _Zum {
42
+ // ═══ UTILITIES ═══
43
+ static addBeforeUnloadHandler(fn) {
44
+ if (typeof fn !== "function") return () => {
45
+ };
46
+ if (!_Zum._beforeUnloadAttached && typeof window !== "undefined") {
47
+ window.addEventListener("beforeunload", () => {
48
+ _Zum._beforeUnloadHandlers.forEach((f) => {
49
+ try {
50
+ f();
51
+ } catch (e) {
52
+ zerr(e);
53
+ }
54
+ });
55
+ });
56
+ _Zum._beforeUnloadAttached = true;
57
+ }
58
+ _Zum._beforeUnloadHandlers.add(fn);
59
+ return () => _Zum._beforeUnloadHandlers.delete(fn);
60
+ }
61
+ static _debounce(func, wait) {
62
+ let timeout;
63
+ const debounced = function(...args) {
64
+ const later = () => {
65
+ clearTimeout(timeout);
66
+ func(...args);
67
+ };
68
+ clearTimeout(timeout);
69
+ timeout = setTimeout(later, wait);
70
+ };
71
+ debounced.cancel = () => {
72
+ clearTimeout(timeout);
73
+ timeout = null;
74
+ };
75
+ debounced.flush = (...args) => {
76
+ clearTimeout(timeout);
77
+ timeout = null;
78
+ func(...args);
79
+ };
80
+ return debounced;
81
+ }
82
+ static _isObject(item) {
83
+ return item && typeof item === "object" && !Array.isArray(item);
84
+ }
85
+ static _deepMerge(target, source) {
86
+ const output = { ...target };
87
+ if (_Zum._isObject(target) && _Zum._isObject(source)) {
88
+ Object.keys(source).forEach((key) => {
89
+ if (_Zum._isObject(source[key])) {
90
+ if (!(key in target)) output[key] = source[key];
91
+ else output[key] = _Zum._deepMerge(target[key], source[key]);
92
+ } else if (Array.isArray(source[key])) {
93
+ output[key] = source[key];
94
+ } else {
95
+ output[key] = source[key];
96
+ }
97
+ });
98
+ }
99
+ return output;
100
+ }
101
+ static _escapeHtml(str) {
102
+ return String(str).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
103
+ }
104
+ static _scheduleAutoSave(el, componentName, autoSaveDelay) {
105
+ if (!(autoSaveDelay > 0)) return;
106
+ if (!el.__debouncedSave) {
107
+ el.__debouncedSave = _Zum._debounce(() => {
108
+ if (!el.__isDestroyed) _Zum.saveComponent(componentName, el);
109
+ }, autoSaveDelay);
110
+ }
111
+ el.__debouncedSave();
112
+ }
113
+ static _scheduleOnUpdate(el, payload) {
114
+ if (!el.__onUpdate) return;
115
+ el.__pendingUpdate = payload;
116
+ if (el.__onUpdateScheduled) return;
117
+ el.__onUpdateScheduled = true;
118
+ queueMicrotask(() => {
119
+ el.__onUpdateScheduled = false;
120
+ const p = el.__pendingUpdate;
121
+ el.__pendingUpdate = null;
122
+ if (p && el.__onUpdate) {
123
+ try {
124
+ el.__onUpdate.call(el, p);
125
+ } catch (e) {
126
+ zerr(e);
127
+ }
128
+ }
129
+ });
130
+ }
131
+ // ═══ REACTIVE STATE ═══
132
+ static _createReactiveState(obj, componentName, el, autoSaveDelay) {
133
+ return new Proxy(obj, {
134
+ set: (target, property, value) => {
135
+ const oldValue = target[property];
136
+ if (oldValue === value && (typeof value !== "object" || value === null)) return true;
137
+ if (typeof value === "object" && value !== null) {
138
+ value = _Zum._createReactiveState(value, componentName, el, autoSaveDelay);
139
+ }
140
+ target[property] = value;
141
+ _Zum._scheduleAutoSave(el, componentName, autoSaveDelay);
142
+ if (el.__isMounted && el.__onUpdate) {
143
+ _Zum._scheduleOnUpdate(el, { property, oldValue, newValue: value, state: target });
144
+ }
145
+ if (el.__stateWatchers && el.__stateWatchers[property]) {
146
+ el.__stateWatchers[property].forEach((cb) => {
147
+ try {
148
+ cb(value, oldValue, target);
149
+ } catch (e) {
150
+ zerr(e);
151
+ }
152
+ });
153
+ }
154
+ return true;
155
+ },
156
+ get: (target, property) => {
157
+ const value = target[property];
158
+ if (Array.isArray(value)) {
159
+ return new Proxy(value, {
160
+ get: (arrTarget, arrProperty) => {
161
+ const arrValue = arrTarget[arrProperty];
162
+ if (typeof arrValue === "function") {
163
+ const mutating = ["push", "pop", "shift", "unshift", "splice", "sort", "reverse"];
164
+ if (mutating.includes(arrProperty)) {
165
+ return function(...args) {
166
+ const oldSnapshot = [...arrTarget];
167
+ const result = Array.prototype[arrProperty].apply(arrTarget, args);
168
+ _Zum._scheduleAutoSave(el, componentName, autoSaveDelay);
169
+ if (el.__isMounted && el.__onUpdate) {
170
+ _Zum._scheduleOnUpdate(el, { property, oldValue: oldSnapshot, newValue: arrTarget, state: target });
171
+ }
172
+ if (el.__stateWatchers && el.__stateWatchers[property]) {
173
+ el.__stateWatchers[property].forEach((cb) => {
174
+ try {
175
+ cb(arrTarget, oldSnapshot, target);
176
+ } catch (e) {
177
+ zerr(e);
178
+ }
179
+ });
180
+ }
181
+ return result;
182
+ };
183
+ }
184
+ }
185
+ return arrValue;
186
+ }
187
+ });
188
+ }
189
+ return value;
190
+ }
191
+ });
192
+ }
193
+ static get ready() {
194
+ if (!_Zum._readyPromise) {
195
+ _Zum._readyPromise = (async () => {
196
+ if (!hasDOM()) return true;
197
+ _Zum._injectAnimationStyles();
198
+ _Zum._initAutoContrast();
199
+ return true;
200
+ })();
201
+ }
202
+ return _Zum._readyPromise;
203
+ }
204
+ // ═══ COMPONENT FACTORY ═══
205
+ static create(tag, options = {}) {
206
+ if (tag && typeof tag === "object" && !(tag instanceof HTMLElement)) {
207
+ options = tag;
208
+ tag = options.tag || "div";
209
+ }
210
+ if (!tag) tag = "div";
211
+ return new _Zum(tag, options).getElement();
212
+ }
213
+ static createMany(defaultComp, components = [], distribution = "33/33/33") {
214
+ if (!hasDOM()) return null;
215
+ if (components.length > 3) {
216
+ zwarn(`Zum.createMany: received ${components.length} components but only 3 are supported.`);
217
+ }
218
+ const comps = components.slice(0, 3);
219
+ let sizes = distribution.split("/").map((s) => parseFloat(s.trim()));
220
+ if (sizes.length === 0 || sizes.some(isNaN)) {
221
+ const eq = 100 / Math.max(comps.length, 1);
222
+ sizes = comps.map(() => eq);
223
+ }
224
+ while (sizes.length < comps.length) sizes.push(100 / Math.max(comps.length, 1));
225
+ const totalSize = sizes.reduce((a, b) => a + b, 0);
226
+ if (totalSize > 0 && totalSize !== 100) sizes = sizes.map((s) => s * 100 / totalSize);
227
+ const container = document.createElement("div");
228
+ container.className = "Zum-many-container";
229
+ container.style.cssText = "width: 100%; max-width: 100%; height: 100dvh; height: 100vh; overflow: hidden; position: relative; margin: 0; padding: 0; box-sizing: border-box;";
230
+ const defaultComponent = defaultComp instanceof HTMLElement ? defaultComp : defaultComp ? _Zum.create(defaultComp.tag || "div", defaultComp) : null;
231
+ const effectiveDefault = defaultComponent || (comps[0] ? comps[0] instanceof HTMLElement ? comps[0] : _Zum.create(comps[0].tag || "div", { ...comps[0], useShadow: false }) : null);
232
+ const resolvedComps = comps.map((c) => c instanceof HTMLElement ? c : _Zum.create(c.tag || "div", c));
233
+ let currentActiveLayout = null;
234
+ const mobileScrollContainer = document.createElement("div");
235
+ mobileScrollContainer.className = "Zum-many-mobile-scroll";
236
+ mobileScrollContainer.style.cssText = "width: 100%; max-width: 100%; height: 100%; overflow-y: auto; overflow-x: hidden; -webkit-overflow-scrolling: touch; box-sizing: border-box;";
237
+ if (effectiveDefault) mobileScrollContainer.appendChild(effectiveDefault);
238
+ const mobileWrapper = document.createElement("div");
239
+ mobileWrapper.setAttribute("data-layout", "mobile");
240
+ mobileWrapper.style.cssText = "width: 100%; max-width: 100%; height: 100%; overflow: hidden; box-sizing: border-box;";
241
+ mobileWrapper.appendChild(mobileScrollContainer);
242
+ const panelsContainer = document.createElement("div");
243
+ panelsContainer.className = "Zum-many-panels";
244
+ const GAP = 16;
245
+ panelsContainer.style.cssText = `display: flex; gap: ${GAP}px; width: 100%; height: 100%; overflow: hidden; box-sizing: border-box;`;
246
+ const totalGaps = (resolvedComps.length - 1) * GAP;
247
+ resolvedComps.forEach((comp, i) => {
248
+ const panel = document.createElement("div");
249
+ panel.className = "Zum-many-panel";
250
+ const percent = sizes[i] || 100 / resolvedComps.length;
251
+ const flexBasis = `calc(${percent}% - ${(totalGaps * (percent / 100)).toFixed(2)}px)`;
252
+ panel.style.cssText = `flex: 0 0 ${flexBasis}; width: ${flexBasis}; max-width: ${flexBasis}; height: 100%; min-height: 0; display: flex; flex-direction: column; box-sizing: border-box; overflow: hidden;`;
253
+ const scrollContainer = document.createElement("div");
254
+ scrollContainer.className = "Zum-many-panel-scroll";
255
+ scrollContainer.style.cssText = "width: 100%; height: 100%; flex: 1 1 auto; min-height: 0; overflow-y: auto; overflow-x: hidden; -webkit-overflow-scrolling: touch; box-sizing: border-box;";
256
+ scrollContainer.appendChild(comp);
257
+ panel.appendChild(scrollContainer);
258
+ panelsContainer.appendChild(panel);
259
+ });
260
+ const desktopWrapper = document.createElement("div");
261
+ desktopWrapper.setAttribute("data-layout", "desktop");
262
+ desktopWrapper.style.cssText = "width: 100%; height: 100%; overflow: hidden; box-sizing: border-box;";
263
+ desktopWrapper.appendChild(panelsContainer);
264
+ if (!document.getElementById("Zum-many-styles")) {
265
+ const styleEl = document.createElement("style");
266
+ styleEl.id = "Zum-many-styles";
267
+ styleEl.textContent = `
268
+ .Zum-many-container { width: 100% !important; height: 100vh; height: 100dvh; overflow: hidden; }
269
+ @media (max-width: 767px) {
270
+ .Zum-many-container [data-layout="desktop"] { display: none !important; }
271
+ .Zum-many-container [data-layout="mobile"] { display: block !important; }
272
+ }
273
+ `;
274
+ document.head.appendChild(styleEl);
275
+ }
276
+ const isDesktop = () => window.innerWidth >= 768;
277
+ const arrange = () => {
278
+ const target = isDesktop() ? "desktop" : "mobile";
279
+ if (currentActiveLayout === target) return;
280
+ if (target === "desktop") {
281
+ if (mobileWrapper.parentNode === container) container.removeChild(mobileWrapper);
282
+ container.appendChild(desktopWrapper);
283
+ container.setAttribute("data-layout", "desktop");
284
+ } else {
285
+ if (desktopWrapper.parentNode === container) container.removeChild(desktopWrapper);
286
+ container.appendChild(mobileWrapper);
287
+ container.setAttribute("data-layout", "mobile");
288
+ }
289
+ currentActiveLayout = target;
290
+ };
291
+ arrange();
292
+ let raf = null;
293
+ const resizeHandler = () => {
294
+ if (raf) return;
295
+ raf = requestAnimationFrame(() => {
296
+ arrange();
297
+ raf = null;
298
+ });
299
+ };
300
+ window.addEventListener("resize", resizeHandler);
301
+ container.__cleanupResize = () => {
302
+ window.removeEventListener("resize", resizeHandler);
303
+ if (raf) cancelAnimationFrame(raf);
304
+ raf = null;
305
+ };
306
+ container.__droppedCount = Math.max(0, components.length - 3);
307
+ container.__destroyMany = () => {
308
+ container.__isDestroyed = true;
309
+ try {
310
+ container.__cleanupResize();
311
+ } catch (_) {
312
+ }
313
+ };
314
+ return container;
315
+ }
316
+ // ═══ CONSTRUCTOR & BUILD ═══
317
+ constructor(tag, options = {}) {
318
+ this.tag = tag || "div";
319
+ this.options = options;
320
+ this.elementWrapper = document.createElement("div");
321
+ this.elementWrapper.style.display = "contents";
322
+ this._initWithoutLicense();
323
+ }
324
+ getElement() {
325
+ return this.elementWrapper;
326
+ }
327
+ async _initWithoutLicense() {
328
+ await _Zum.ready;
329
+ this._buildComponent();
330
+ }
331
+ static _injectAnimationStyles() {
332
+ if (_Zum._animationsInjected) return;
333
+ if (typeof document === "undefined") return;
334
+ const styleEl = document.createElement("style");
335
+ styleEl.setAttribute("data-Zum-animations", "true");
336
+ styleEl.textContent = Object.values(_Zum.animations).map((a) => a.keyframes).join("\n");
337
+ (document.head || document.documentElement).appendChild(styleEl);
338
+ _Zum._animationsInjected = true;
339
+ }
340
+ static _parseAnim(input) {
341
+ if (!input) return null;
342
+ if (typeof input === "object") return { ...input, __raw: true };
343
+ const tokens = String(input).trim().toLowerCase().split(/\s+/);
344
+ const spec = { verb: "fade", direction: null, duration: 500, easing: null, delay: 0, scroll: false, repeat: false, stagger: 0, staggerTarget: "> *", loop: false, forceMotion: false, disableMotion: false };
345
+ const VERBS = ["fade", "slide", "zoom", "scale", "flip", "rotate", "blur", "bounce", "shake", "pulse", "reveal"];
346
+ const DIRS = ["up", "down", "left", "right"];
347
+ const EASINGS = { "ease": "ease", "ease-in": "ease-in", "ease-out": "ease-out", "ease-in-out": "ease-in-out", "linear": "linear", "bounce": "cubic-bezier(.34,1.56,.64,1)", "spring": "cubic-bezier(.16,1,.3,1)", "snap": "cubic-bezier(.5,-0.5,.5,1.5)" };
348
+ const DURATIONS = { fast: 250, normal: 500, slow: 800, slower: 1200 };
349
+ let verbSet = false;
350
+ for (const t of tokens) {
351
+ if (VERBS.includes(t) && !verbSet) {
352
+ spec.verb = t;
353
+ verbSet = true;
354
+ } else if (DIRS.includes(t)) {
355
+ spec.direction = t;
356
+ } else if (/^\d+$/.test(t)) {
357
+ spec.duration = parseInt(t, 10);
358
+ } else if (t in DURATIONS) {
359
+ spec.duration = DURATIONS[t];
360
+ } else if (t in EASINGS) {
361
+ spec.easing = EASINGS[t];
362
+ } else if (t.startsWith("delay-")) {
363
+ spec.delay = parseInt(t.slice(6), 10) || 0;
364
+ } else if (t === "on-scroll") {
365
+ spec.scroll = true;
366
+ } else if (t === "repeat") {
367
+ spec.scroll = true;
368
+ spec.repeat = true;
369
+ } else if (t === "loop") {
370
+ spec.loop = true;
371
+ } else if (t === "force-motion") {
372
+ spec.forceMotion = true;
373
+ } else if (t === "no-motion") {
374
+ spec.disableMotion = true;
375
+ } else if (t === "stagger") {
376
+ spec.stagger = 80;
377
+ } else if (t.startsWith("stagger-")) {
378
+ spec.stagger = parseInt(t.slice(8), 10) || 80;
379
+ } else if (t.startsWith("target-")) {
380
+ spec.staggerTarget = "." + t.slice(7);
381
+ }
382
+ }
383
+ if (!spec.easing) spec.easing = "cubic-bezier(.2,.8,.2,1)";
384
+ return spec;
385
+ }
386
+ static _resolveAnimName(spec) {
387
+ const cap = (s) => s[0].toUpperCase() + s.slice(1);
388
+ const map = { fade: "fade", slide: spec.direction ? `slide${cap(spec.direction)}` : "slideUp", flip: "flipIn", rotate: "rotateIn", zoom: "scale", scale: "scale", blur: "blurIn", bounce: "bounce", shake: "shake", pulse: "pulse", reveal: "reveal" };
389
+ return map[spec.verb] || "fade";
390
+ }
391
+ static _applyScrollAnim(el, spec) {
392
+ if (!hasDOM()) return;
393
+ const name = _Zum._resolveAnimName(spec);
394
+ _Zum._injectAnimationStyles();
395
+ el.style.opacity = "0";
396
+ el.style.willChange = "opacity, transform";
397
+ const play = () => {
398
+ if (!el.__isDestroyed) el.style.animation = `${name} ${spec.duration}ms ${spec.easing} ${spec.delay}ms both`;
399
+ };
400
+ const reset = () => {
401
+ el.style.animation = "none";
402
+ el.style.opacity = "0";
403
+ };
404
+ const obs = new IntersectionObserver((entries) => {
405
+ for (const entry of entries) {
406
+ if (entry.isIntersecting) {
407
+ play();
408
+ if (!spec.repeat) obs.unobserve(el);
409
+ } else if (spec.repeat) reset();
410
+ }
411
+ }, { threshold: 0.15, rootMargin: "0px 0px -10% 0px" });
412
+ (el.__zumAnimObservers || (el.__zumAnimObservers = [])).push(obs);
413
+ obs.observe(el);
414
+ }
415
+ static _applyStaggerAnim(el, spec) {
416
+ if (!hasDOM()) return;
417
+ const name = _Zum._resolveAnimName(spec);
418
+ _Zum._injectAnimationStyles();
419
+ const children = spec.staggerTarget === "> *" ? Array.from(el.children) : Array.from(el.querySelectorAll(spec.staggerTarget));
420
+ children.forEach((child, i) => {
421
+ child.style.animation = `${name} ${spec.duration}ms ${spec.easing} ${spec.delay + i * spec.stagger}ms both`;
422
+ });
423
+ }
424
+ _applyAnimation(el, anim, direction = "in") {
425
+ var _a;
426
+ if (!anim || !hasDOM()) return;
427
+ const reduced = (_a = window.matchMedia) == null ? void 0 : _a.call(window, "(prefers-reduced-motion: reduce)").matches;
428
+ const spec = _Zum._parseAnim(anim);
429
+ if (!spec) return;
430
+ if (reduced && _Zum.respectReducedMotion && !spec.forceMotion && direction === "in") return;
431
+ if (spec.disableMotion) return;
432
+ if (spec.__raw) return;
433
+ if (spec.scroll) return _Zum._applyScrollAnim(el, spec);
434
+ if (spec.stagger) return _Zum._applyStaggerAnim(el, spec);
435
+ const name = _Zum._resolveAnimName(spec);
436
+ _Zum._injectAnimationStyles();
437
+ el.style.animation = `${name} ${spec.duration}ms ${spec.easing} ${spec.delay}ms both`;
438
+ if (spec.loop) el.style.animationIterationCount = "infinite";
439
+ }
440
+ static animate(el, anim = "fade", options = {}) {
441
+ if (!el || !anim) return;
442
+ const spec = _Zum._parseAnim(anim);
443
+ if (!spec) return;
444
+ if (options.duration) spec.duration = options.duration;
445
+ if (options.easing) spec.easing = options.easing;
446
+ if (options.delay) spec.delay = options.delay;
447
+ if (spec.__raw) return;
448
+ if (spec.scroll) return _Zum._applyScrollAnim(el, spec);
449
+ if (spec.stagger) return _Zum._applyStaggerAnim(el, spec);
450
+ const name = _Zum._resolveAnimName(spec);
451
+ _Zum._injectAnimationStyles();
452
+ el.style.animation = `${name} ${spec.duration}ms ${spec.easing} ${spec.delay}ms both`;
453
+ if (spec.loop) el.style.animationIterationCount = "infinite";
454
+ }
455
+ static async animateOut(el, anim = "fade", options = {}) {
456
+ var _a, _b;
457
+ if (!el || !anim) return;
458
+ const spec = _Zum._parseAnim(anim);
459
+ if (!spec) return;
460
+ const name = _Zum._resolveAnimName(spec);
461
+ const preset = _Zum.animations[name];
462
+ if (!preset) return;
463
+ _Zum._injectAnimationStyles();
464
+ const dur = spec.duration || options.duration || (((_a = preset.options) == null ? void 0 : _a.duration) || 600);
465
+ const eas = spec.easing || options.easing || (((_b = preset.options) == null ? void 0 : _b.easing) || "ease");
466
+ return new Promise((resolve) => {
467
+ let done = false;
468
+ const finish = () => {
469
+ if (done) return;
470
+ done = true;
471
+ el.removeEventListener("animationend", finish);
472
+ resolve();
473
+ };
474
+ el.addEventListener("animationend", finish);
475
+ el.style.animation = `${name}Out ${dur}ms ${eas} ${spec.delay || 0}ms both`;
476
+ setTimeout(finish, dur + (spec.delay || 0) + 100);
477
+ });
478
+ }
479
+ // ═══ AUTO-CONTRAST ═══
480
+ static _initAutoContrast() {
481
+ if (_Zum._contrastInitialized) return;
482
+ if (!hasDOM()) return;
483
+ const styleEl = document.createElement("style");
484
+ styleEl.setAttribute("data-Zum-contrast", "true");
485
+ styleEl.textContent = `
486
+ .zum-contrast, .zum-contrast * { transition: color 0.3s ease-in-out !important; }
487
+ .zum-contrast-text { transition: color 0.3s ease-in-out !important; }
488
+ @media (prefers-color-scheme: dark) { .zum-contrast-text { color: #f1f5f9 !important; } }
489
+ @media (prefers-color-scheme: light) { .zum-contrast-text { color: #0f172a !important; } }
490
+ `;
491
+ document.head.appendChild(styleEl);
492
+ const mutationObserver = new MutationObserver((mutations) => {
493
+ mutations.forEach((mutation) => {
494
+ if (mutation.addedNodes) {
495
+ mutation.addedNodes.forEach((node) => {
496
+ if (node.nodeType === Node.ELEMENT_NODE) {
497
+ setTimeout(() => _Zum._applyContrastToElement(node), 50);
498
+ }
499
+ });
500
+ }
501
+ });
502
+ });
503
+ if (document.body) {
504
+ mutationObserver.observe(document.body, { childList: true, subtree: true });
505
+ }
506
+ if (document.readyState === "loading") {
507
+ document.addEventListener("DOMContentLoaded", () => setTimeout(() => _Zum._applyContrastToAll(), 100));
508
+ } else {
509
+ setTimeout(() => _Zum._applyContrastToAll(), 100);
510
+ }
511
+ const darkModeMediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
512
+ const onSystemChange = () => setTimeout(() => _Zum._applyContrastToAll(), 50);
513
+ if (darkModeMediaQuery.addEventListener) {
514
+ darkModeMediaQuery.addEventListener("change", onSystemChange);
515
+ } else if (darkModeMediaQuery.addListener) {
516
+ darkModeMediaQuery.addListener(onSystemChange);
517
+ }
518
+ _Zum._contrastInitialized = true;
519
+ zlog("\u2705 Auto-contrast system initialized");
520
+ }
521
+ static _getRealBackground(el) {
522
+ let current = el;
523
+ let attempts = 0;
524
+ while (current && attempts < 30) {
525
+ const bg = getComputedStyle(current).backgroundColor;
526
+ if (bg && bg !== "rgba(0, 0, 0, 0)" && bg !== "transparent" && bg !== "") return bg;
527
+ if (current !== el && _Zum._contrastProcessing.has(current)) break;
528
+ if (current.parentElement) current = current.parentElement;
529
+ else if (current.parentNode && current.parentNode.host) current = current.parentNode.host;
530
+ else current = null;
531
+ attempts++;
532
+ }
533
+ const theme = _Zum.getTheme();
534
+ return theme ? theme.colors.background : "#ffffff";
535
+ }
536
+ static _applyContrastToAll() {
537
+ if (!hasDOM() || !document.body) return;
538
+ const skip = "input, textarea, select, img, svg, canvas, video, audio, script, style, meta, link, title, br, hr";
539
+ const process2 = (el) => {
540
+ if (!el || !el.matches) return;
541
+ if (el.matches(skip)) return;
542
+ if (!el.textContent || !el.textContent.trim()) return;
543
+ if (_Zum._contrastProcessed.has(el) && el.dataset.contrastColor) return;
544
+ const bg = _Zum._getRealBackground(el);
545
+ const lum = _Zum._calculateLuminance(bg);
546
+ const color = lum > 0.5 ? "#0f172a" : "#f1f5f9";
547
+ el.style.setProperty("color", color, "important");
548
+ el.dataset.contrastColor = color;
549
+ el.classList.add("zum-contrast-text");
550
+ _Zum._contrastProcessed.add(el);
551
+ };
552
+ const walk = (root) => {
553
+ if (!root || !root.querySelectorAll) return;
554
+ root.querySelectorAll("*").forEach((el) => {
555
+ process2(el);
556
+ if (el.shadowRoot) walk(el.shadowRoot);
557
+ });
558
+ };
559
+ walk(document.body);
560
+ zlog("\u2705 Contrast applied to all elements");
561
+ }
562
+ static _applyContrastToElement(element) {
563
+ if (!element || !hasDOM()) return;
564
+ const skip = "input, textarea, select, img, svg, canvas, video, audio, script, style, meta, link, title, br, hr";
565
+ const process2 = (el) => {
566
+ if (!el || !el.matches) return;
567
+ if (el.matches(skip)) return;
568
+ if (!el.textContent || !el.textContent.trim()) return;
569
+ if (_Zum._contrastProcessed.has(el) && el.dataset.contrastColor) return;
570
+ const bg = _Zum._getRealBackground(el);
571
+ const lum = _Zum._calculateLuminance(bg);
572
+ const color = lum > 0.5 ? "#0f172a" : "#f1f5f9";
573
+ el.style.setProperty("color", color, "important");
574
+ el.dataset.contrastColor = color;
575
+ el.classList.add("zum-contrast-text");
576
+ _Zum._contrastProcessed.add(el);
577
+ };
578
+ _Zum._contrastProcessing.add(element);
579
+ process2(element);
580
+ const walk = (root) => {
581
+ if (!root || !root.querySelectorAll) return;
582
+ root.querySelectorAll("*").forEach((el) => {
583
+ process2(el);
584
+ if (el.shadowRoot) walk(el.shadowRoot);
585
+ });
586
+ };
587
+ walk(element);
588
+ element.classList.add("zum-contrast");
589
+ setTimeout(() => _Zum._contrastProcessing.delete(element), 250);
590
+ }
591
+ static _resolveColorToRgb(color) {
592
+ if (!color) return null;
593
+ if (typeof document === "undefined") return null;
594
+ if (color.startsWith("#") || color.startsWith("rgb")) return color;
595
+ const probe = document.createElement("span");
596
+ probe.style.color = color;
597
+ probe.style.display = "none";
598
+ document.body.appendChild(probe);
599
+ const resolved = getComputedStyle(probe).color;
600
+ document.body.removeChild(probe);
601
+ return resolved || null;
602
+ }
603
+ static _calculateLuminance(color) {
604
+ if (!color) return 0.5;
605
+ const resolved = _Zum._resolveColorToRgb(color);
606
+ if (!resolved) return 0.5;
607
+ let r, g, b;
608
+ if (resolved.startsWith("#")) {
609
+ const hex = resolved.replace("#", "");
610
+ if (hex.length === 3) {
611
+ r = parseInt(hex[0] + hex[0], 16);
612
+ g = parseInt(hex[1] + hex[1], 16);
613
+ b = parseInt(hex[2] + hex[2], 16);
614
+ } else if (hex.length === 6) {
615
+ r = parseInt(hex.slice(0, 2), 16);
616
+ g = parseInt(hex.slice(2, 4), 16);
617
+ b = parseInt(hex.slice(4, 6), 16);
618
+ } else return 0.5;
619
+ } else if (resolved.startsWith("rgb")) {
620
+ const m = resolved.match(/[\d.]+/g);
621
+ if (m && m.length >= 3) {
622
+ r = parseFloat(m[0]);
623
+ g = parseFloat(m[1]);
624
+ b = parseFloat(m[2]);
625
+ } else return 0.5;
626
+ } else return 0.5;
627
+ return (0.299 * r + 0.587 * g + 0.114 * b) / 255;
628
+ }
629
+ static getContrastColor(backgroundColor, options = {}) {
630
+ var _a, _b;
631
+ const { mode = "luminance", foreground = null } = options;
632
+ const lum = _Zum._calculateLuminance(backgroundColor);
633
+ const threshold = (_b = (_a = _Zum.themeSettings) == null ? void 0 : _a.contrastThreshold) != null ? _b : 0.5;
634
+ if (mode === "wcag" && foreground) {
635
+ const fgLum = _Zum._calculateLuminance(foreground);
636
+ const ratio = (Math.max(lum, fgLum) + 0.05) / (Math.min(lum, fgLum) + 0.05);
637
+ return ratio >= 4.5 ? foreground : lum > threshold ? "#0f172a" : "#f1f5f9";
638
+ }
639
+ return lum > threshold ? "#0f172a" : "#f1f5f9";
640
+ }
641
+ static getThemeContrastColor(backgroundColor) {
642
+ var _a, _b;
643
+ const lum = _Zum._calculateLuminance(backgroundColor);
644
+ return lum > ((_b = (_a = _Zum.themeSettings) == null ? void 0 : _a.contrastThreshold) != null ? _b : 0.5) ? "#0f172a" : "#f1f5f9";
645
+ }
646
+ static applyContrast(el) {
647
+ if (!el) return;
648
+ _Zum._contrastProcessed.delete(el);
649
+ delete el.dataset.contrastColor;
650
+ _Zum._applyContrastToElement(el);
651
+ }
652
+ static refreshContrast() {
653
+ if (!hasDOM() || !document.body) return;
654
+ const reset = (root) => {
655
+ if (!root || !root.querySelectorAll) return;
656
+ root.querySelectorAll("*").forEach((el) => {
657
+ _Zum._contrastProcessed.delete(el);
658
+ delete el.dataset.contrastColor;
659
+ if (el.shadowRoot) reset(el.shadowRoot);
660
+ });
661
+ };
662
+ reset(document.body);
663
+ _Zum._applyContrastToAll();
664
+ zlog("\u{1F3A8} Contrast refreshed everywhere");
665
+ }
666
+ // ═══ COMPONENT BUILDING ═══
667
+ _buildComponent() {
668
+ if (!hasDOM()) return;
669
+ const {
670
+ html = "",
671
+ style = {},
672
+ className = "",
673
+ events = {},
674
+ children = [],
675
+ attributes = {},
676
+ css = "",
677
+ script = "",
678
+ props = {},
679
+ state = {},
680
+ websocket = null,
681
+ onMount = null,
682
+ onDestroy = null,
683
+ onUpdate = null,
684
+ anim = "fade",
685
+ autoSave = false,
686
+ autoSaveDelay = 500,
687
+ exclude = [],
688
+ render = null,
689
+ autoContrast = true,
690
+ safe = true
691
+ } = this.options;
692
+ const el = document.createElement(this.tag);
693
+ el.__isDestroyed = false;
694
+ this._applyAnimation(el, anim);
695
+ const componentName = (props == null ? void 0 : props.componentId) || (props == null ? void 0 : props.name) || `component-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
696
+ el.__componentName = componentName;
697
+ if (className) el.className = className;
698
+ Object.assign(el.style, style);
699
+ if (html) {
700
+ let processedHtml = html;
701
+ Object.entries(props).forEach(([key, value]) => {
702
+ const placeholder = `{{${key}}}`;
703
+ if (typeof value === "string" || typeof value === "number") {
704
+ const safeValue = safe ? _Zum._escapeHtml(value) : String(value);
705
+ processedHtml = processedHtml.split(placeholder).join(safeValue);
706
+ }
707
+ });
708
+ el.innerHTML = processedHtml;
709
+ }
710
+ const saveDelay = autoSave ? autoSaveDelay : 0;
711
+ if (autoSave) {
712
+ const autoState = _Zum._autoGenerateState(el, exclude);
713
+ el.__state = _Zum._createReactiveState(autoState, componentName, el, saveDelay);
714
+ } else if (state && typeof state === "object") {
715
+ el.__state = _Zum._createReactiveState({ ...state }, componentName, el, 0);
716
+ } else {
717
+ el.__state = {};
718
+ }
719
+ if (render) _Zum._setupAutoRender(el, render);
720
+ Object.entries(attributes).forEach(([k, v]) => el.setAttribute(k, v));
721
+ el.__props = props;
722
+ if (websocket) {
723
+ const { url, protocols = [], onopen = null, onmessage = null, onclose = null, onerror = null, autoReconnect = false, reconnectInterval = 3e3, maxReconnects = Infinity } = websocket;
724
+ el.__wsQueue = [];
725
+ el.__reconnectAttempts = 0;
726
+ el.__createWebSocket = function() {
727
+ if (el.__websocketDestroyed) return;
728
+ try {
729
+ const ws = protocols.length > 0 ? new WebSocket(url, protocols) : new WebSocket(url);
730
+ el.__websocket = ws;
731
+ ws.onopen = (event) => {
732
+ while (el.__wsQueue.length && ws.readyState === WebSocket.OPEN) {
733
+ const q = el.__wsQueue.shift();
734
+ try {
735
+ ws.send(typeof q === "string" ? q : JSON.stringify(q));
736
+ } catch (e) {
737
+ zerr(e);
738
+ }
739
+ }
740
+ el.__reconnectAttempts = 0;
741
+ if (onopen) onopen.call(el, event, ws);
742
+ };
743
+ ws.onmessage = (event) => {
744
+ if (onmessage) onmessage.call(el, event, ws);
745
+ };
746
+ ws.onclose = (event) => {
747
+ if (onclose) onclose.call(el, event, ws);
748
+ if (autoReconnect && !el.__websocketDestroyed && el.__reconnectAttempts < maxReconnects) {
749
+ el.__reconnectAttempts++;
750
+ setTimeout(() => {
751
+ if (!el.__websocketDestroyed) el.__createWebSocket();
752
+ }, reconnectInterval);
753
+ }
754
+ };
755
+ ws.onerror = (event) => {
756
+ if (onerror) onerror.call(el, event, ws);
757
+ };
758
+ } catch (error) {
759
+ zerr("WebSocket creation failed:", error);
760
+ }
761
+ };
762
+ el.sendWebSocket = (data) => {
763
+ if (el.__websocket && el.__websocket.readyState === WebSocket.OPEN) {
764
+ try {
765
+ el.__websocket.send(typeof data === "string" ? data : JSON.stringify(data));
766
+ } catch (e) {
767
+ zerr(e);
768
+ }
769
+ } else {
770
+ el.__wsQueue.push(data);
771
+ }
772
+ };
773
+ el.closeWebSocket = (code = 1e3, reason = "") => {
774
+ el.__websocketDestroyed = true;
775
+ if (el.__websocket) el.__websocket.close(code, reason);
776
+ };
777
+ setTimeout(() => el.__createWebSocket(), 10);
778
+ }
779
+ el.__events = [];
780
+ Object.entries(events).forEach(([event, handler]) => {
781
+ el.addEventListener(event, handler);
782
+ el.__events.push({ event, handler });
783
+ });
784
+ const processedChildren = children.filter(Boolean).map((child) => {
785
+ if (child instanceof HTMLElement) return child;
786
+ if (typeof child === "object" && !Array.isArray(child))
787
+ return _Zum.create(child.tag || "div", { ...child, useShadow: false, props: { ...props, ...child.props } });
788
+ return child;
789
+ });
790
+ processedChildren.filter((c) => c instanceof HTMLElement).forEach((c) => el.appendChild(c));
791
+ el.__onMount = onMount;
792
+ el.__onDestroy = onDestroy;
793
+ if (onUpdate) {
794
+ const existing = el.__onUpdate;
795
+ if (existing) {
796
+ el.__onUpdate = function(data) {
797
+ try {
798
+ existing.call(this, data);
799
+ } catch (e) {
800
+ zerr(e);
801
+ }
802
+ try {
803
+ onUpdate.call(this, data);
804
+ } catch (e) {
805
+ zerr(e);
806
+ }
807
+ };
808
+ } else {
809
+ el.__onUpdate = onUpdate;
810
+ }
811
+ }
812
+ setTimeout(() => {
813
+ if (el.__isDestroyed) return;
814
+ el.__isMounted = true;
815
+ if (autoSave) _Zum._autoBindFormElements(el);
816
+ if (el.__onMount) {
817
+ try {
818
+ el.__onMount.call(el);
819
+ } catch (e) {
820
+ zerr(e);
821
+ }
822
+ }
823
+ if (autoContrast !== false) {
824
+ setTimeout(() => {
825
+ if (!el.__isDestroyed) _Zum._applyContrastToElement(el);
826
+ }, 50);
827
+ }
828
+ }, 0);
829
+ if (css) {
830
+ const styleEl = document.createElement("style");
831
+ styleEl.textContent = css;
832
+ styleEl.setAttribute("data-Zum-css", "true");
833
+ document.head.appendChild(styleEl);
834
+ el.__ZumCss = styleEl;
835
+ }
836
+ if (script) setTimeout(() => {
837
+ if (!el.__isDestroyed) _Zum._executeScriptWithState(script, el);
838
+ }, 10);
839
+ this.elementWrapper.appendChild(el);
840
+ }
841
+ static _executeScriptWithState(script, element) {
842
+ try {
843
+ if (typeof script === "function") script.call(element, element.__state);
844
+ else if (typeof script === "string") new Function("state", script).call(element, element.__state);
845
+ } catch (error) {
846
+ zerr("Error executing script with state:", error);
847
+ }
848
+ }
849
+ // ═══ COMPONENT: addComponents ═══
850
+ static addComponents(...components) {
851
+ if (!hasDOM()) return null;
852
+ const flat = [];
853
+ const flatten = (item) => {
854
+ if (Array.isArray(item)) item.forEach(flatten);
855
+ else if (item) flat.push(item);
856
+ };
857
+ components.forEach(flatten);
858
+ if (flat.length === 0) return null;
859
+ const wrapper = document.createElement("div");
860
+ wrapper.style.display = "contents";
861
+ const mergedState = {};
862
+ const mergedProps = {};
863
+ const mergedChildren = [];
864
+ const mergedEvents = {};
865
+ const onMountFns = [];
866
+ const onDestroyFns = [];
867
+ const onUpdateFns = [];
868
+ const onRefreshFns = [];
869
+ const cssBlocks = [];
870
+ const scriptFns = [];
871
+ flat.forEach((comp, index) => {
872
+ if (comp instanceof HTMLElement) {
873
+ mergedChildren.push(comp);
874
+ return;
875
+ }
876
+ if (typeof comp === "string") {
877
+ const textEl = document.createElement("div");
878
+ textEl.textContent = comp;
879
+ mergedChildren.push(textEl);
880
+ return;
881
+ }
882
+ if (typeof comp !== "object") return;
883
+ if (comp.events && typeof comp.events === "object") {
884
+ Object.entries(comp.events).forEach(([eventName, handler]) => {
885
+ if (!mergedEvents[eventName]) mergedEvents[eventName] = [];
886
+ if (typeof handler === "function") mergedEvents[eventName].push(handler);
887
+ });
888
+ }
889
+ if (comp.state) {
890
+ Object.keys(comp.state).forEach((k) => {
891
+ if (k in mergedState) zwarn(`Zum.addComponents: state key "${k}" overrides an earlier value.`);
892
+ mergedState[k] = comp.state[k];
893
+ });
894
+ }
895
+ if (comp.props) Object.assign(mergedProps, comp.props);
896
+ if (typeof comp.onMount === "function") onMountFns.push(comp.onMount);
897
+ if (typeof comp.onDestroy === "function") onDestroyFns.push(comp.onDestroy);
898
+ if (typeof comp.onUpdate === "function") onUpdateFns.push(comp.onUpdate);
899
+ if (typeof comp.onRefresh === "function") onRefreshFns.push(comp.onRefresh);
900
+ if (typeof comp.css === "string" && comp.css.trim()) {
901
+ cssBlocks.push(`/* --- Component ${index + 1}: ${comp.tag || "div"} --- */
902
+ ${comp.css}`);
903
+ }
904
+ if (typeof comp.script === "function") scriptFns.push(comp.script);
905
+ else if (typeof comp.script === "string" && comp.script.trim()) {
906
+ scriptFns.push(new Function("state", comp.script));
907
+ }
908
+ const childOptions = { ...comp };
909
+ delete childOptions.events;
910
+ delete childOptions.state;
911
+ delete childOptions.onMount;
912
+ delete childOptions.onDestroy;
913
+ delete childOptions.onUpdate;
914
+ delete childOptions.onRefresh;
915
+ mergedChildren.push(_Zum.create(comp.tag || "div", childOptions));
916
+ });
917
+ const combinedEvents = {};
918
+ Object.entries(mergedEvents).forEach(([eventName, handlers]) => {
919
+ combinedEvents[eventName] = function(event) {
920
+ handlers.forEach((handler) => {
921
+ try {
922
+ handler.call(this, event);
923
+ } catch (error) {
924
+ zerr(`addComponent event (${eventName}):`, error);
925
+ }
926
+ });
927
+ };
928
+ });
929
+ const combinedOnMount = function() {
930
+ onMountFns.forEach((fn) => {
931
+ try {
932
+ fn.call(this);
933
+ } catch (e) {
934
+ zerr(e);
935
+ }
936
+ });
937
+ };
938
+ const combinedOnDestroy = function() {
939
+ onDestroyFns.forEach((fn) => {
940
+ try {
941
+ fn.call(this);
942
+ } catch (e) {
943
+ zerr(e);
944
+ }
945
+ });
946
+ };
947
+ const combinedOnUpdate = function(data) {
948
+ onUpdateFns.forEach((fn) => {
949
+ try {
950
+ fn.call(this, data);
951
+ } catch (e) {
952
+ zerr(e);
953
+ }
954
+ });
955
+ };
956
+ const combinedOnRefresh = function() {
957
+ onRefreshFns.forEach((fn) => {
958
+ try {
959
+ fn.call(this);
960
+ } catch (e) {
961
+ zerr(e);
962
+ }
963
+ });
964
+ };
965
+ const combined = _Zum.create("div", {
966
+ children: mergedChildren,
967
+ props: mergedProps,
968
+ state: mergedState,
969
+ events: combinedEvents,
970
+ css: cssBlocks.join("\n\n"),
971
+ script: scriptFns.length > 0 ? function() {
972
+ scriptFns.forEach((fn) => {
973
+ try {
974
+ fn.call(this, this.__state);
975
+ } catch (e) {
976
+ zerr("addComponent script:", e);
977
+ }
978
+ });
979
+ } : null,
980
+ onMount: onMountFns.length > 0 ? combinedOnMount : null,
981
+ onDestroy: onDestroyFns.length > 0 ? combinedOnDestroy : null,
982
+ onUpdate: onUpdateFns.length > 0 ? combinedOnUpdate : null,
983
+ onRefresh: onRefreshFns.length > 0 ? combinedOnRefresh : null,
984
+ style: { display: "contents" }
985
+ });
986
+ wrapper.appendChild(combined);
987
+ wrapper.__combinedComponent = combined;
988
+ wrapper.__childCount = mergedChildren.length;
989
+ const innerState = { ...mergedState };
990
+ wrapper.__state = new Proxy(innerState, {
991
+ set: (t, p, v) => {
992
+ t[p] = v;
993
+ if (wrapper.__innerState && wrapper.__innerState[p] !== v) {
994
+ try {
995
+ wrapper.__innerState[p] = v;
996
+ } catch (e) {
997
+ zerr(e);
998
+ }
999
+ }
1000
+ return true;
1001
+ },
1002
+ get: (t, p) => t[p]
1003
+ });
1004
+ setTimeout(() => {
1005
+ const inner = combined.firstElementChild;
1006
+ if (inner && inner.__state) {
1007
+ wrapper.__innerState = inner.__state;
1008
+ Object.keys(inner.__state).forEach((k) => {
1009
+ if (!(k in innerState)) innerState[k] = inner.__state[k];
1010
+ });
1011
+ }
1012
+ }, 0);
1013
+ zlog(`\u2705 addComponents: combined ${mergedChildren.length} components`);
1014
+ return wrapper;
1015
+ }
1016
+ // ═══ createList ═══
1017
+ static createList(items, renderItem) {
1018
+ return _Zum.create("div", {
1019
+ style: { display: "flex", flexDirection: "column", gap: "8px" },
1020
+ children: items.map((item) => renderItem(item))
1021
+ });
1022
+ }
1023
+ // ═══ setAttributeComp ═══
1024
+ static setAttributeComp(el, attrs = {}) {
1025
+ const target = el.__isShadowHost ? el : el.__hostElement || el;
1026
+ if (!target || !(target instanceof HTMLElement)) return;
1027
+ Object.entries(attrs).forEach(([k, v]) => target.setAttribute(k, v));
1028
+ }
1029
+ // ═══ LIFECYCLE ═══
1030
+ static destroy(element) {
1031
+ if (!element) return;
1032
+ element.__isDestroyed = true;
1033
+ const safe = (fn) => {
1034
+ try {
1035
+ fn();
1036
+ } catch (e) {
1037
+ zerr("Zum.destroy cleanup error:", e);
1038
+ }
1039
+ };
1040
+ safe(() => {
1041
+ if (element.__destroyMany) element.__destroyMany();
1042
+ });
1043
+ safe(() => {
1044
+ if (element.__cleanupResize) element.__cleanupResize();
1045
+ });
1046
+ safe(() => {
1047
+ if (element.__zumAnimObservers) {
1048
+ element.__zumAnimObservers.forEach((o) => {
1049
+ try {
1050
+ o.disconnect();
1051
+ } catch (_) {
1052
+ }
1053
+ });
1054
+ element.__zumAnimObservers.length = 0;
1055
+ }
1056
+ });
1057
+ safe(() => {
1058
+ if (element.__websocket) {
1059
+ try {
1060
+ element.__websocket.close(1e3, "destroyed");
1061
+ } catch (_) {
1062
+ }
1063
+ element.__websocketDestroyed = true;
1064
+ }
1065
+ });
1066
+ safe(() => {
1067
+ if (element.__debouncedSave && element.__debouncedSave.cancel) element.__debouncedSave.cancel();
1068
+ });
1069
+ safe(() => {
1070
+ if (element.__state) {
1071
+ try {
1072
+ Object.freeze(element.__state);
1073
+ } catch (_) {
1074
+ }
1075
+ }
1076
+ if (element.__stateWatchers) Object.keys(element.__stateWatchers).forEach((k) => {
1077
+ element.__stateWatchers[k].length = 0;
1078
+ });
1079
+ element.__onUpdate = null;
1080
+ element.__onMount = null;
1081
+ });
1082
+ safe(() => {
1083
+ if (element.__onDestroy) element.__onDestroy.call(element);
1084
+ });
1085
+ safe(() => {
1086
+ if (element.__ZumCss && element.__ZumCss.parentNode) element.__ZumCss.parentNode.removeChild(element.__ZumCss);
1087
+ });
1088
+ safe(() => {
1089
+ const toRemove = element.__hostElement || element;
1090
+ if (toRemove && toRemove.parentNode) toRemove.parentNode.removeChild(toRemove);
1091
+ });
1092
+ }
1093
+ static isMounted(element) {
1094
+ return element.__isMounted === true;
1095
+ }
1096
+ static triggerUpdate(element, updateData = {}) {
1097
+ if (element.__onUpdate && element.__isMounted) element.__onUpdate.call(element, updateData);
1098
+ }
1099
+ static triggerRefresh(el) {
1100
+ let targetEl = el;
1101
+ if (el.style && el.style.display === "contents" && el.children.length > 0) {
1102
+ for (let child of el.children) {
1103
+ if (child.__onRefresh) {
1104
+ targetEl = child;
1105
+ break;
1106
+ }
1107
+ if (child.__shadowRoot) {
1108
+ for (let shadowChild of child.__shadowRoot.children) {
1109
+ if (shadowChild.__onRefresh) {
1110
+ targetEl = shadowChild;
1111
+ break;
1112
+ }
1113
+ }
1114
+ if (targetEl !== el) break;
1115
+ }
1116
+ }
1117
+ }
1118
+ if (targetEl.__onRefresh && typeof targetEl.__onRefresh === "function") {
1119
+ try {
1120
+ targetEl.__onRefresh.call(targetEl);
1121
+ } catch (error) {
1122
+ zerr("\u274C onRefresh failed:", error);
1123
+ }
1124
+ }
1125
+ }
1126
+ static async triggerRestore() {
1127
+ _Zum._hasRestored = false;
1128
+ sessionStorage.removeItem("__Zum_loaded");
1129
+ sessionStorage.removeItem("__Zum_refreshing");
1130
+ const temp = new _Zum("div", { html: "<div></div>" });
1131
+ await temp._checkAndRestore();
1132
+ }
1133
+ // ═══ STATE PERSISTENCE ═══
1134
+ static getKey() {
1135
+ return localStorage.getItem("app-name");
1136
+ }
1137
+ static popLastComponent() {
1138
+ const key = _Zum.getKey();
1139
+ try {
1140
+ const configsJson = localStorage.getItem(key);
1141
+ if (!configsJson) return null;
1142
+ const configs = JSON.parse(configsJson);
1143
+ if (!Array.isArray(configs) || configs.length === 0) return null;
1144
+ const popped = configs.pop();
1145
+ if (configs.length === 0) localStorage.removeItem(key);
1146
+ else localStorage.setItem(key, JSON.stringify(configs));
1147
+ return popped;
1148
+ } catch (error) {
1149
+ zerr("\u274C Error popping component:", error);
1150
+ return null;
1151
+ }
1152
+ }
1153
+ static saveComponent(name, el) {
1154
+ const key = _Zum.getKey();
1155
+ if (!key) return;
1156
+ let targetEl = el;
1157
+ if (el.style && el.style.display === "contents" && el.children.length > 0) {
1158
+ for (let child of el.children) {
1159
+ if (child.__ZumComponent) {
1160
+ targetEl = child;
1161
+ break;
1162
+ }
1163
+ if (child.__shadowRoot) {
1164
+ for (let sc of child.__shadowRoot.children) {
1165
+ if (sc.__ZumComponent) {
1166
+ targetEl = sc;
1167
+ break;
1168
+ }
1169
+ }
1170
+ if (targetEl !== el) break;
1171
+ }
1172
+ if (child.__isShadowHost) {
1173
+ targetEl = child;
1174
+ break;
1175
+ }
1176
+ }
1177
+ }
1178
+ if (!targetEl.__ZumComponent && targetEl.querySelector) {
1179
+ const found = targetEl.querySelector("[__ZumComponent]");
1180
+ if (found == null ? void 0 : found.__ZumComponent) targetEl = found;
1181
+ }
1182
+ if (!targetEl.__ZumComponent) {
1183
+ zerr("\u274C Cannot save component: no __ZumComponent found");
1184
+ return;
1185
+ }
1186
+ const options = targetEl.__ZumComponent.options;
1187
+ const currentState = {};
1188
+ if (targetEl.__state) {
1189
+ Object.keys(targetEl.__state).forEach((key2) => {
1190
+ currentState[key2] = targetEl.__state[key2];
1191
+ });
1192
+ }
1193
+ const config = {
1194
+ name,
1195
+ tag: targetEl.__ZumComponent.tag,
1196
+ html: options.html,
1197
+ css: options.css,
1198
+ script: options.script ? options.script.toString() : null,
1199
+ onRefresh: options.onRefresh ? options.onRefresh.toString() : null,
1200
+ props: options.props || {},
1201
+ state: currentState
1202
+ };
1203
+ try {
1204
+ let configs = JSON.parse(localStorage.getItem(key)) || [];
1205
+ configs = configs.filter((item) => item.name !== name);
1206
+ configs.push(config);
1207
+ localStorage.setItem(key, JSON.stringify(configs));
1208
+ zlog(`\u2705 Saved component: ${name}`);
1209
+ } catch (error) {
1210
+ zerr("\u274C Failed to save component:", error);
1211
+ }
1212
+ }
1213
+ static async restoreComponents() {
1214
+ const key = _Zum.getKey();
1215
+ if (!key) return [];
1216
+ try {
1217
+ const configs = JSON.parse(localStorage.getItem(key));
1218
+ if (!configs || configs.length === 0) {
1219
+ zlog("\u2139\uFE0F No components to restore");
1220
+ return [];
1221
+ }
1222
+ zlog(`\u{1F504} Restoring ${configs.length} components...`);
1223
+ const restored = [];
1224
+ for (let i = 0; i < configs.length; i++) {
1225
+ const conf = configs[i];
1226
+ let scriptFn = null, onRefreshFn = null;
1227
+ if (conf.script) {
1228
+ try {
1229
+ scriptFn = new Function("return " + conf.script)();
1230
+ if (typeof scriptFn !== "function") {
1231
+ zwarn("\u26A0\uFE0F Restored script is not a function for:", conf.name);
1232
+ scriptFn = null;
1233
+ }
1234
+ } catch (error) {
1235
+ zerr("\u274C Failed to restore script:", error);
1236
+ }
1237
+ }
1238
+ if (conf.onRefresh) {
1239
+ try {
1240
+ onRefreshFn = new Function("return " + conf.onRefresh)();
1241
+ } catch (error) {
1242
+ zerr("\u274C Failed to restore onRefresh:", error);
1243
+ }
1244
+ }
1245
+ const comp = _Zum.create(conf.tag, {
1246
+ html: conf.html,
1247
+ css: conf.css,
1248
+ script: scriptFn,
1249
+ onRefresh: onRefreshFn,
1250
+ props: conf.props || {},
1251
+ state: conf.state || {}
1252
+ });
1253
+ if (scriptFn && typeof scriptFn === "function") {
1254
+ let targetComp = comp;
1255
+ if (comp.style && comp.style.display === "contents" && comp.children.length > 0) {
1256
+ for (let child of comp.children) {
1257
+ if (child.__ZumComponent) {
1258
+ targetComp = child;
1259
+ break;
1260
+ }
1261
+ if (child.__shadowRoot) {
1262
+ for (let sc of child.__shadowRoot.children) {
1263
+ if (sc.__ZumComponent) {
1264
+ targetComp = sc;
1265
+ break;
1266
+ }
1267
+ }
1268
+ if (targetComp !== comp) break;
1269
+ }
1270
+ }
1271
+ }
1272
+ setTimeout(() => {
1273
+ try {
1274
+ scriptFn.call(targetComp, targetComp.__state);
1275
+ } catch (error) {
1276
+ zerr("\u274C Script execution failed:", conf.name, error);
1277
+ }
1278
+ }, 20);
1279
+ }
1280
+ restored.push(comp);
1281
+ }
1282
+ zlog(`\u2705 Successfully restored ${restored.length} components`);
1283
+ return restored;
1284
+ } catch (error) {
1285
+ zerr("\u274C Failed to restore components:", error);
1286
+ return [];
1287
+ }
1288
+ }
1289
+ static wipeConfigs() {
1290
+ const key = _Zum.getKey();
1291
+ try {
1292
+ if (key) localStorage.removeItem(key);
1293
+ zlog("All Zum component configs wiped");
1294
+ } catch (error) {
1295
+ zerr("\u274C Failed to wipe configs:", error);
1296
+ }
1297
+ }
1298
+ static clearComponents() {
1299
+ const key = _Zum.getKey();
1300
+ if (key) {
1301
+ localStorage.removeItem(key);
1302
+ zlog("\u{1F5D1}\uFE0F Component configs cleared");
1303
+ }
1304
+ }
1305
+ async _checkAndRestore() {
1306
+ if (_Zum._hasRestored) return;
1307
+ try {
1308
+ const key = _Zum.getKey();
1309
+ if (!key) {
1310
+ _Zum._hasRestored = true;
1311
+ return;
1312
+ }
1313
+ const configsJson = localStorage.getItem(key);
1314
+ if (!configsJson) {
1315
+ _Zum._hasRestored = true;
1316
+ return;
1317
+ }
1318
+ const configs = JSON.parse(configsJson);
1319
+ if (!Array.isArray(configs) || configs.length === 0) {
1320
+ _Zum._hasRestored = true;
1321
+ return;
1322
+ }
1323
+ await _Zum.restoreComponents();
1324
+ _Zum._hasRestored = true;
1325
+ } catch (error) {
1326
+ zerr("\u274C Error during restore:", error);
1327
+ _Zum._hasRestored = true;
1328
+ }
1329
+ }
1330
+ static createSkeleton(type = _Zum.SKELETON_TYPES.DEFAULT, el, options = {}) {
1331
+ const config = { ..._Zum.DEFAULT_SKELETON_OPTIONS, ...options };
1332
+ const template = _Zum._getSkeletonTemplate(type, config.count);
1333
+ const skeleton = _Zum.create("div", {
1334
+ className: `skeleton skeleton-${type} ${config.customClass}`.trim(),
1335
+ html: template,
1336
+ attributes: {
1337
+ "data-skeleton": type,
1338
+ "role": "status",
1339
+ "aria-live": "polite",
1340
+ "aria-label": `Loading ${type.replace(/-/g, " ")}`
1341
+ },
1342
+ useShadow: false
1343
+ });
1344
+ _Zum.mount(skeleton, el);
1345
+ return skeleton;
1346
+ }
1347
+ static removeSkeleton(el, options = {}) {
1348
+ var _a;
1349
+ const config = { ..._Zum.REMOVE_SKELETON_OPTIONS, ...options };
1350
+ const skeletonElement = _Zum._findSkeletonElement(el, config.selector);
1351
+ if (!skeletonElement) {
1352
+ (_a = config.callback) == null ? void 0 : _a.call(config);
1353
+ return null;
1354
+ }
1355
+ const performRemoval = () => {
1356
+ var _a2;
1357
+ const parent = skeletonElement.parentNode;
1358
+ if (parent) parent.removeChild(skeletonElement);
1359
+ (_a2 = config.callback) == null ? void 0 : _a2.call(config);
1360
+ };
1361
+ if (config.animate && config.animationType !== "none") {
1362
+ skeletonElement.style.transition = `all ${config.duration}ms ease-out`;
1363
+ skeletonElement.style.opacity = "0";
1364
+ const timeoutId = setTimeout(performRemoval, config.duration + config.delay);
1365
+ return {
1366
+ element: skeletonElement,
1367
+ cancel: () => {
1368
+ clearTimeout(timeoutId);
1369
+ skeletonElement.style.transition = "none";
1370
+ performRemoval();
1371
+ }
1372
+ };
1373
+ }
1374
+ performRemoval();
1375
+ return null;
1376
+ }
1377
+ static hasSkeleton(el) {
1378
+ return !!_Zum._findSkeletonElement(el);
1379
+ }
1380
+ static toggleSkeleton(el, show) {
1381
+ const skeletonElement = _Zum._findSkeletonElement(el);
1382
+ if (!skeletonElement) return false;
1383
+ const shouldShow = typeof show === "boolean" ? show : skeletonElement.style.display === "none";
1384
+ skeletonElement.style.display = shouldShow ? "" : "none";
1385
+ return shouldShow;
1386
+ }
1387
+ static _findSkeletonElement(el, selector = ".skeleton") {
1388
+ var _a;
1389
+ if (!el) return null;
1390
+ if (el.querySelector) return el.querySelector(selector);
1391
+ if ((_a = el.el) == null ? void 0 : _a.querySelector) return el.el.querySelector(selector);
1392
+ const shadowRoot = _Zum.getShadowRoot(el);
1393
+ if (shadowRoot) return shadowRoot.querySelector(selector);
1394
+ return null;
1395
+ }
1396
+ static _getSkeletonTemplate(type, count) {
1397
+ const templates = {
1398
+ [_Zum.SKELETON_TYPES.DEFAULT]: () => `
1399
+ <div class="skeleton-default" style="padding: 20px;">
1400
+ ${Array(count).fill(0).map(() => `<div style="height: 16px; background: #e5e7eb; border-radius: 4px; margin-bottom: 12px; animation: pulse 1.5s infinite;"></div>`).join("")}
1401
+ </div>
1402
+ <style>@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }</style>
1403
+ `,
1404
+ [_Zum.SKELETON_TYPES.FEED_PAGE]: () => `
1405
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
1406
+ ${Array(count || 2).fill(0).map(() => `
1407
+ <div style="background: white; border-radius: 8px; padding: 15px; margin-bottom: 15px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
1408
+ <div style="display: flex; align-items: center; margin-bottom: 10px;">
1409
+ <div style="width: 40px; height: 40px; border-radius: 50%; background: #e5e7eb; animation: pulse 1.5s infinite;"></div>
1410
+ <div style="margin-left: 10px; flex: 1;">
1411
+ <div style="height: 12px; background: #e5e7eb; border-radius: 4px; width: 60%; animation: pulse 1.5s infinite;"></div>
1412
+ </div>
1413
+ </div>
1414
+ <div style="height: 200px; background: #e5e7eb; border-radius: 4px; animation: pulse 1.5s infinite;"></div>
1415
+ <div style="height: 12px; background: #e5e7eb; border-radius: 4px; margin-top: 10px; width: 80%; animation: pulse 1.5s infinite;"></div>
1416
+ </div>
1417
+ `).join("")}
1418
+ </div>
1419
+ <style>@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }</style>
1420
+ `,
1421
+ [_Zum.SKELETON_TYPES.PROFILE_PAGE]: () => `
1422
+ <div style="max-width: 800px; margin: 0 auto; padding: 20px;">
1423
+ <div style="height: 180px; background: #e5e7eb; border-radius: 8px; animation: pulse 1.5s infinite;"></div>
1424
+ <div style="width: 100px; height: 100px; border-radius: 50%; background: #e5e7eb; margin: -50px auto 0; border: 4px solid white; animation: pulse 1.5s infinite;"></div>
1425
+ <div style="height: 16px; background: #e5e7eb; border-radius: 4px; width: 40%; margin: 20px auto; animation: pulse 1.5s infinite;"></div>
1426
+ <div style="height: 12px; background: #e5e7eb; border-radius: 4px; width: 80%; margin: 10px auto; animation: pulse 1.5s infinite;"></div>
1427
+ </div>
1428
+ <style>@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }</style>
1429
+ `,
1430
+ [_Zum.SKELETON_TYPES.CHAT_PAGE]: () => `
1431
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
1432
+ ${Array(count).fill(0).map(() => `
1433
+ <div style="display: flex; align-items: center; padding: 10px; border-bottom: 1px solid #f0f0f0;">
1434
+ <div style="width: 48px; height: 48px; border-radius: 50%; background: #e5e7eb; animation: pulse 1.5s infinite;"></div>
1435
+ <div style="margin-left: 10px; flex: 1;">
1436
+ <div style="height: 12px; background: #e5e7eb; border-radius: 4px; width: 60%; animation: pulse 1.5s infinite;"></div>
1437
+ <div style="height: 8px; background: #e5e7eb; border-radius: 4px; width: 40%; margin-top: 5px; animation: pulse 1.5s infinite;"></div>
1438
+ </div>
1439
+ </div>
1440
+ `).join("")}
1441
+ </div>
1442
+ <style>@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }</style>
1443
+ `,
1444
+ [_Zum.SKELETON_TYPES.CHAT_DETAIL_PAGE]: () => `
1445
+ <div style="max-width: 800px; margin: 0 auto; padding: 20px;">
1446
+ ${Array(5).fill(0).map((_, i) => `
1447
+ <div style="display: flex; ${i % 2 === 0 ? "justify-content: flex-end;" : "justify-content: flex-start;"} margin-bottom: 15px;">
1448
+ <div style="height: 40px; background: #e5e7eb; border-radius: 16px; width: 60%; animation: pulse 1.5s infinite;"></div>
1449
+ </div>
1450
+ `).join("")}
1451
+ </div>
1452
+ <style>@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }</style>
1453
+ `,
1454
+ [_Zum.SKELETON_TYPES.SERVICE_PAGE]: () => `
1455
+ <div style="max-width: 800px; margin: 0 auto; padding: 20px;">
1456
+ <div style="height: 200px; background: #e5e7eb; border-radius: 8px; animation: pulse 1.5s infinite;"></div>
1457
+ <div style="display: flex; align-items: center; margin-top: 15px;">
1458
+ <div style="width: 80px; height: 80px; background: #e5e7eb; border-radius: 8px; animation: pulse 1.5s infinite;"></div>
1459
+ <div style="margin-left: 15px; flex: 1;">
1460
+ <div style="height: 16px; background: #e5e7eb; border-radius: 4px; width: 40%; animation: pulse 1.5s infinite;"></div>
1461
+ <div style="height: 12px; background: #e5e7eb; border-radius: 4px; width: 90%; margin-top: 8px; animation: pulse 1.5s infinite;"></div>
1462
+ </div>
1463
+ </div>
1464
+ </div>
1465
+ <style>@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }</style>
1466
+ `,
1467
+ [_Zum.SKELETON_TYPES.DASHBOARD_PAGE]: () => `
1468
+ <div style="max-width: 1200px; margin: 0 auto; padding: 20px;">
1469
+ <div style="height: 24px; background: #e5e7eb; border-radius: 4px; width: 30%; margin-bottom: 20px; animation: pulse 1.5s infinite;"></div>
1470
+ <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; margin-bottom: 20px;">
1471
+ ${Array(4).fill(0).map(() => `
1472
+ <div style="background: white; padding: 15px; border-radius: 8px;">
1473
+ <div style="height: 12px; background: #e5e7eb; border-radius: 4px; width: 50%; animation: pulse 1.5s infinite;"></div>
1474
+ <div style="height: 24px; background: #e5e7eb; border-radius: 4px; width: 40%; margin-top: 10px; animation: pulse 1.5s infinite;"></div>
1475
+ </div>
1476
+ `).join("")}
1477
+ </div>
1478
+ <div style="height: 200px; background: #e5e7eb; border-radius: 8px; animation: pulse 1.5s infinite;"></div>
1479
+ </div>
1480
+ <style>@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }</style>
1481
+ `,
1482
+ [_Zum.SKELETON_TYPES.SETTINGS_PAGE]: () => `
1483
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
1484
+ <div style="height: 24px; background: #e5e7eb; border-radius: 4px; width: 40%; margin-bottom: 20px; animation: pulse 1.5s infinite;"></div>
1485
+ ${Array(3).fill(0).map(() => `
1486
+ <div style="background: white; padding: 15px; border-radius: 8px; margin-bottom: 10px;">
1487
+ <div style="display: flex; justify-content: space-between;">
1488
+ <div style="height: 12px; background: #e5e7eb; border-radius: 4px; width: 40%; animation: pulse 1.5s infinite;"></div>
1489
+ <div style="width: 48px; height: 24px; background: #e5e7eb; border-radius: 12px; animation: pulse 1.5s infinite;"></div>
1490
+ </div>
1491
+ </div>
1492
+ `).join("")}
1493
+ </div>
1494
+ <style>@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }</style>
1495
+ `,
1496
+ [_Zum.SKELETON_TYPES.SEARCH_PAGE]: () => `
1497
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
1498
+ <div style="height: 40px; background: #e5e7eb; border-radius: 20px; margin-bottom: 20px; animation: pulse 1.5s infinite;"></div>
1499
+ ${Array(4).fill(0).map(() => `
1500
+ <div style="display: flex; align-items: center; padding: 10px; border-bottom: 1px solid #f0f0f0;">
1501
+ <div style="width: 60px; height: 60px; background: #e5e7eb; border-radius: 8px; animation: pulse 1.5s infinite;"></div>
1502
+ <div style="margin-left: 10px; flex: 1;">
1503
+ <div style="height: 12px; background: #e5e7eb; border-radius: 4px; width: 80%; animation: pulse 1.5s infinite;"></div>
1504
+ </div>
1505
+ </div>
1506
+ `).join("")}
1507
+ </div>
1508
+ <style>@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }</style>
1509
+ `,
1510
+ [_Zum.SKELETON_TYPES.PRODUCT_GRID]: () => `
1511
+ <div style="max-width: 1200px; margin: 0 auto; padding: 20px;">
1512
+ <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 15px;">
1513
+ ${Array(count).fill(0).map(() => `
1514
+ <div style="background: white; border-radius: 8px; overflow: hidden;">
1515
+ <div style="height: 120px; background: #e5e7eb; animation: pulse 1.5s infinite;"></div>
1516
+ <div style="padding: 10px;">
1517
+ <div style="height: 10px; background: #e5e7eb; border-radius: 4px; width: 80%; animation: pulse 1.5s infinite;"></div>
1518
+ <div style="height: 10px; background: #e5e7eb; border-radius: 4px; width: 50%; margin-top: 5px; animation: pulse 1.5s infinite;"></div>
1519
+ </div>
1520
+ </div>
1521
+ `).join("")}
1522
+ </div>
1523
+ </div>
1524
+ <style>@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }</style>
1525
+ `,
1526
+ [_Zum.SKELETON_TYPES.NOTIFICATIONS_PAGE]: () => `
1527
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
1528
+ ${Array(count).fill(0).map(() => `
1529
+ <div style="display: flex; align-items: flex-start; padding: 15px; border-bottom: 1px solid #f0f0f0;">
1530
+ <div style="width: 40px; height: 40px; border-radius: 50%; background: #e5e7eb; animation: pulse 1.5s infinite;"></div>
1531
+ <div style="margin-left: 10px; flex: 1;">
1532
+ <div style="height: 12px; background: #e5e7eb; border-radius: 4px; width: 90%; animation: pulse 1.5s infinite;"></div>
1533
+ <div style="height: 8px; background: #e5e7eb; border-radius: 4px; width: 60%; margin-top: 5px; animation: pulse 1.5s infinite;"></div>
1534
+ </div>
1535
+ </div>
1536
+ `).join("")}
1537
+ </div>
1538
+ <style>@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }</style>
1539
+ `,
1540
+ [_Zum.SKELETON_TYPES.FORM_PAGE]: () => `
1541
+ <div style="max-width: 500px; margin: 0 auto; padding: 20px;">
1542
+ ${Array(5).fill(0).map(() => `
1543
+ <div style="margin-bottom: 20px;">
1544
+ <div style="height: 10px; background: #e5e7eb; border-radius: 4px; width: 30%; margin-bottom: 8px; animation: pulse 1.5s infinite;"></div>
1545
+ <div style="height: 48px; background: #e5e7eb; border-radius: 8px; animation: pulse 1.5s infinite;"></div>
1546
+ </div>
1547
+ `).join("")}
1548
+ <div style="height: 120px; background: #e5e7eb; border-radius: 8px; animation: pulse 1.5s infinite;"></div>
1549
+ </div>
1550
+ <style>@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }</style>
1551
+ `
1552
+ };
1553
+ return (templates[type] || templates[_Zum.SKELETON_TYPES.DEFAULT])(count);
1554
+ }
1555
+ // ═══ SPINNERS ═══
1556
+ static createSpinner(text = "Loading...", el) {
1557
+ const s = _Zum.create("div", {
1558
+ html: `<div class="spinner-container"><div class="spinner-circle"></div><div class="spinner-text">${text}</div></div>`,
1559
+ css: `.spinner-container{display:flex;flex-direction:column;justify-content:center;align-items:center;padding:20px;color:#555;gap:8px}.spinner-circle{width:40px;height:40px;border:4px solid #e0e0e0;border-top:4px solid #007bff;border-radius:50%;animation:spin 1s linear infinite}.spinner-text{font-size:14px;color:#666}@keyframes spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}`,
1560
+ useShadow: false
1561
+ });
1562
+ _Zum.mount(s, el);
1563
+ return s;
1564
+ }
1565
+ static createBorderSpinner(text = "Loading...", el) {
1566
+ if (el && el.style) el.style.position = el.style.position || "relative";
1567
+ const s = _Zum.create("div", {
1568
+ html: `<div class="border-spinner-overlay"><div class="border-spinner-circle"></div><div class="border-spinner-text">${text}</div></div>`,
1569
+ css: `.border-spinner-overlay{position:absolute;top:0;left:0;width:100%;height:100%;display:flex;flex-direction:column;justify-content:center;align-items:center;background:rgba(255,255,255,.7);z-index:1000;pointer-events:none;padding:10px}.border-spinner-circle{position:absolute;top:0;left:0;width:calc(100% - 4px);height:calc(100% - 4px);border:2px solid rgba(0,123,255,.2);border-top:2px solid #007bff;border-radius:4px;box-sizing:border-box;animation:border-spin 1.5s linear infinite}.border-spinner-text{margin-top:50px;font-size:14px;color:#007bff;z-index:1001;background:#fff;padding:2px 5px;border-radius:3px}@keyframes border-spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}`,
1570
+ useShadow: false
1571
+ });
1572
+ _Zum.mount(s, el);
1573
+ return s;
1574
+ }
1575
+ static createRingSpinner(text = "Loading...", el) {
1576
+ if (el && el.style) el.style.position = el.style.position || "relative";
1577
+ const s = _Zum.create("div", {
1578
+ html: `<div class="ring-spinner-overlay"><div class="ring-spinner-circle"></div><div class="ring-spinner-text">${text}</div></div>`,
1579
+ css: `.ring-spinner-overlay{position:absolute;top:0;left:0;width:100%;height:100%;display:flex;flex-direction:column;justify-content:center;align-items:center;background:rgba(255,255,255,.7);z-index:1000;gap:10px}.ring-spinner-circle{width:50px;height:50px;border:6px solid #e0e0e0;border-top:6px solid #007bff;border-radius:50%;animation:spin 1.2s cubic-bezier(.5,0,.5,1) infinite}.ring-spinner-text{font-size:16px;color:#007bff;font-weight:700}@keyframes spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}`,
1580
+ useShadow: false
1581
+ });
1582
+ _Zum.mount(s, el);
1583
+ return s;
1584
+ }
1585
+ static createScalingSpinner(text = "Loading...", el) {
1586
+ if (el && el.style) el.style.position = el.style.position || "relative";
1587
+ const s = _Zum.create("div", {
1588
+ html: `<div class="scaling-spinner-overlay"><div class="scaling-spinner-container"><div class="scaling-spinner-circle"></div></div><div class="scaling-spinner-text">${text}</div></div>`,
1589
+ css: `.scaling-spinner-overlay{position:absolute;top:0;left:0;width:100%;height:100%;display:flex;flex-direction:column;justify-content:center;align-items:center;background:rgba(255,255,255,.7);z-index:1000;gap:10px}.scaling-spinner-container{width:30%;padding-bottom:30%;position:relative;max-width:80px;max-height:80px}.scaling-spinner-circle{position:absolute;top:0;left:0;width:100%;height:100%;border:4px solid #e0e0e0;border-top:4px solid #007bff;border-radius:50%;box-sizing:border-box;animation:spin 1.2s cubic-bezier(.5,0,.5,1) infinite}.scaling-spinner-text{font-size:16px;color:#007bff;font-weight:700}@keyframes spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}`,
1590
+ useShadow: false
1591
+ });
1592
+ _Zum.mount(s, el);
1593
+ return s;
1594
+ }
1595
+ static destroySpinner(spinner) {
1596
+ _Zum.destroy(spinner);
1597
+ }
1598
+ // ═══ QUERYING & SHADOW DOM ═══
1599
+ static getShadowRoot(el) {
1600
+ return el.shadowRoot || el.__shadowRoot || null;
1601
+ }
1602
+ static isShadowHost(el) {
1603
+ return !!(el.shadowRoot || el.__isShadowHost || el.__hostElement);
1604
+ }
1605
+ static getAllShadowHosts() {
1606
+ if (!hasDOM()) return [];
1607
+ return Array.from(document.querySelectorAll("*")).filter((el) => _Zum.isShadowHost(el));
1608
+ }
1609
+ static queryFromRoot(root, selector) {
1610
+ if (!root) return null;
1611
+ if (root instanceof ShadowRoot || root === document) return root.querySelector(selector);
1612
+ const sr = _Zum.getShadowRoot(root);
1613
+ return sr ? sr.querySelector(selector) : root.querySelector(selector);
1614
+ }
1615
+ static queryAllFromRoot(root, selector) {
1616
+ if (!root) return [];
1617
+ if (root instanceof ShadowRoot || root === document) return root.querySelectorAll(selector);
1618
+ const sr = _Zum.getShadowRoot(root);
1619
+ return sr ? sr.querySelectorAll(selector) : root.querySelectorAll(selector);
1620
+ }
1621
+ static querySelector(el, selector) {
1622
+ const root = _Zum.getShadowRoot(el);
1623
+ return root ? root.querySelector(selector) : el.querySelector(selector);
1624
+ }
1625
+ static querySelectorAll(el, selector) {
1626
+ const root = _Zum.getShadowRoot(el);
1627
+ return root ? root.querySelectorAll(selector) : el.querySelectorAll(selector);
1628
+ }
1629
+ static find(selector) {
1630
+ if (!hasDOM()) return null;
1631
+ let result = null;
1632
+ function traverse(node) {
1633
+ if (result) return;
1634
+ if (node.nodeType === Node.ELEMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
1635
+ if (node.nodeType === Node.ELEMENT_NODE && node.matches(selector)) {
1636
+ result = node;
1637
+ return;
1638
+ }
1639
+ if (node.shadowRoot) traverse(node.shadowRoot);
1640
+ node.childNodes.forEach(traverse);
1641
+ }
1642
+ }
1643
+ traverse(document.body);
1644
+ return result;
1645
+ }
1646
+ static findAll(selector) {
1647
+ if (!hasDOM()) return [];
1648
+ const results = [];
1649
+ function traverse(node) {
1650
+ if (node.nodeType === Node.ELEMENT_NODE && node.matches(selector)) results.push(node);
1651
+ if (node.nodeType === Node.ELEMENT_NODE && node.shadowRoot) traverse(node.shadowRoot);
1652
+ node.childNodes.forEach(traverse);
1653
+ }
1654
+ traverse(document.body);
1655
+ return results;
1656
+ }
1657
+ static elementExists(el, sel) {
1658
+ return !!_Zum.querySelector(el, sel);
1659
+ }
1660
+ static getComputedStyle(el, sel) {
1661
+ const e = _Zum.querySelector(el, sel);
1662
+ return e ? window.getComputedStyle(e) : null;
1663
+ }
1664
+ // ═══ DOM MANIPULATION & EVENTS ═══
1665
+ static mount(el, parent) {
1666
+ if (!el || !parent) return null;
1667
+ const p = parent instanceof HTMLElement ? parent : document.querySelector(parent);
1668
+ if (!p) return null;
1669
+ const n = el instanceof HTMLElement ? el : typeof el === "string" ? document.querySelector(el) : null;
1670
+ if (!n) return null;
1671
+ p.appendChild(n);
1672
+ setTimeout(() => _Zum._applyContrastToElement(n), 50);
1673
+ return n;
1674
+ }
1675
+ static unmount(el, parent) {
1676
+ if (!el) return null;
1677
+ const p = parent ? parent instanceof HTMLElement ? parent : document.querySelector(parent) : el.parentNode;
1678
+ if (!p || !p.contains(el)) return null;
1679
+ p.removeChild(el);
1680
+ return el;
1681
+ }
1682
+ static append(el, child) {
1683
+ if (!el || !child) return null;
1684
+ const root = _Zum.getShadowRoot(el) || el;
1685
+ root.appendChild(child);
1686
+ setTimeout(() => _Zum._applyContrastToElement(child), 50);
1687
+ return child;
1688
+ }
1689
+ static addChildren(el, children) {
1690
+ if (!el || !(children == null ? void 0 : children.length)) return;
1691
+ const root = _Zum.getShadowRoot(el) || el;
1692
+ children.forEach((child) => {
1693
+ root.appendChild(child);
1694
+ setTimeout(() => _Zum._applyContrastToElement(child), 50);
1695
+ });
1696
+ }
1697
+ static replaceChild(el, oldSel, newChild) {
1698
+ if (!el || !newChild) return null;
1699
+ const old = _Zum.querySelector(el, oldSel);
1700
+ if (!old) return null;
1701
+ old.parentNode.replaceChild(newChild, old);
1702
+ setTimeout(() => _Zum._applyContrastToElement(newChild), 50);
1703
+ return newChild;
1704
+ }
1705
+ static clone(el, deep = true) {
1706
+ if (!el) return null;
1707
+ let target = el;
1708
+ if (el.style && el.style.display === "contents" && el.children.length > 0) {
1709
+ for (let c of el.children) {
1710
+ if (c.__ZumComponent) {
1711
+ target = c;
1712
+ break;
1713
+ }
1714
+ if (c.__shadowRoot || c.__isShadowHost) {
1715
+ target = c;
1716
+ break;
1717
+ }
1718
+ }
1719
+ }
1720
+ const root = _Zum.getShadowRoot(target) || target;
1721
+ return root.cloneNode(deep);
1722
+ }
1723
+ static show(el) {
1724
+ if (el) (_Zum.getShadowRoot(el) || el).style.display = "";
1725
+ }
1726
+ static hide(el) {
1727
+ if (el) (_Zum.getShadowRoot(el) || el).style.display = "none";
1728
+ }
1729
+ static addEventListener(el, sel, evt, handler) {
1730
+ const e = _Zum.querySelector(el, sel);
1731
+ if (e) {
1732
+ e.addEventListener(evt, handler);
1733
+ (e.__events || (e.__events = [])).push({ event: evt, handler });
1734
+ }
1735
+ }
1736
+ static removeEventListener(el, sel, evt, handler = null) {
1737
+ const e = _Zum.querySelector(el, sel);
1738
+ if (!(e == null ? void 0 : e.__events)) return;
1739
+ e.__events = e.__events.filter((ev) => {
1740
+ if (ev.event === evt && (!handler || ev.handler === handler)) {
1741
+ e.removeEventListener(ev.event, ev.handler);
1742
+ return false;
1743
+ }
1744
+ return true;
1745
+ });
1746
+ }
1747
+ static clearEventListeners(el, sel) {
1748
+ const e = _Zum.querySelector(el, sel);
1749
+ if (e == null ? void 0 : e.__events) {
1750
+ e.__events.forEach(({ event, handler }) => e.removeEventListener(event, handler));
1751
+ e.__events = [];
1752
+ }
1753
+ }
1754
+ static on(el, sel, evt, handler) {
1755
+ _Zum.addEventListener(el, sel, evt, handler);
1756
+ }
1757
+ static updateContent(el, sel, html) {
1758
+ const e = _Zum.querySelector(el, sel);
1759
+ if (e) e.innerHTML = html;
1760
+ setTimeout(() => _Zum._applyContrastToElement(e), 50);
1761
+ }
1762
+ static updateText(el, sel, text) {
1763
+ const e = _Zum.querySelector(el, sel);
1764
+ if (e) e.textContent = text;
1765
+ setTimeout(() => _Zum._applyContrastToElement(e), 50);
1766
+ }
1767
+ static updateStyles(el, sel, styles) {
1768
+ const e = _Zum.querySelector(el, sel);
1769
+ if (e) Object.assign(e.style, styles);
1770
+ }
1771
+ static updateAttributes(el, sel, attrs) {
1772
+ const e = _Zum.querySelector(el, sel);
1773
+ if (e) Object.entries(attrs).forEach(([k, v]) => e.setAttribute(k, v));
1774
+ }
1775
+ static bulkUpdateContent(el, updates) {
1776
+ const root = _Zum.getShadowRoot(el);
1777
+ if (!root) return;
1778
+ updates.forEach((u) => {
1779
+ const e = _Zum.queryFromRoot(root, u.selector);
1780
+ if (!e) return;
1781
+ if (u.properties) Object.assign(e, u.properties);
1782
+ if (u.attributes) Object.entries(u.attributes).forEach(([k, v]) => e.setAttribute(k, v));
1783
+ if (u.styles) Object.assign(e.style, u.styles);
1784
+ if (u.html) e.innerHTML = u.html;
1785
+ if (u.text) e.textContent = u.text;
1786
+ });
1787
+ }
1788
+ static addElement(el, parentSel, tag, options = {}) {
1789
+ const root = _Zum.getShadowRoot(el);
1790
+ if (!root) return null;
1791
+ const parent = parentSel ? _Zum.queryFromRoot(root, parentSel) : root;
1792
+ if (!parent) return null;
1793
+ const newEl = document.createElement(tag);
1794
+ if (options.text) newEl.textContent = options.text;
1795
+ if (options.html) newEl.innerHTML = options.html;
1796
+ if (options.className) newEl.className = options.className;
1797
+ if (options.style) Object.assign(newEl.style, options.style);
1798
+ if (options.attributes) Object.entries(options.attributes).forEach(([k, v]) => newEl.setAttribute(k, v));
1799
+ parent.appendChild(newEl);
1800
+ setTimeout(() => _Zum._applyContrastToElement(newEl), 50);
1801
+ return newEl;
1802
+ }
1803
+ static removeElement(el, sel) {
1804
+ const e = _Zum.querySelector(el, sel);
1805
+ if (e == null ? void 0 : e.parentNode) e.parentNode.removeChild(e);
1806
+ }
1807
+ static toggleClass(el, sel, cls, force) {
1808
+ const e = _Zum.querySelector(el, sel);
1809
+ if (e) e.classList.toggle(cls, force);
1810
+ }
1811
+ static data(el, sel, key, value) {
1812
+ const e = _Zum.querySelector(el, sel);
1813
+ if (!e) return null;
1814
+ if (value === void 0) return e.dataset[key] || null;
1815
+ e.dataset[key] = value;
1816
+ return null;
1817
+ }
1818
+ static text(el, sel, text) {
1819
+ const e = _Zum.querySelector(el, sel);
1820
+ if (e) e.textContent = text;
1821
+ setTimeout(() => _Zum._applyContrastToElement(e), 50);
1822
+ }
1823
+ static html(el, sel, html) {
1824
+ const e = _Zum.querySelector(el, sel);
1825
+ if (e) e.innerHTML = html;
1826
+ setTimeout(() => _Zum._applyContrastToElement(e), 50);
1827
+ }
1828
+ static css(el, sel, styles) {
1829
+ const e = _Zum.querySelector(el, sel);
1830
+ if (e) Object.assign(e.style, styles);
1831
+ }
1832
+ static attr(el, sel, attrs) {
1833
+ const e = _Zum.querySelector(el, sel);
1834
+ if (e) Object.entries(attrs).forEach(([k, v]) => e.setAttribute(k, v));
1835
+ }
1836
+ static destroyWidget(el) {
1837
+ var _a, _b;
1838
+ if ((_a = el.__swiper) == null ? void 0 : _a.destroy) el.__swiper.destroy();
1839
+ if ((_b = el.__chart) == null ? void 0 : _b.destroy) el.__chart.destroy();
1840
+ el.__quill = el.__swiper = el.__chart = null;
1841
+ }
1842
+ // ═══ STATE ═══
1843
+ static getState(el) {
1844
+ let target = el;
1845
+ if (el.style && el.style.display === "contents" && el.children.length > 0) {
1846
+ for (let c of el.children) {
1847
+ if (c.__state) {
1848
+ target = c;
1849
+ break;
1850
+ }
1851
+ if (c.__shadowRoot) {
1852
+ for (let sc of c.__shadowRoot.children) {
1853
+ if (sc.__state) {
1854
+ target = sc;
1855
+ break;
1856
+ }
1857
+ }
1858
+ if (target !== el) break;
1859
+ }
1860
+ }
1861
+ }
1862
+ if (!(target == null ? void 0 : target.__state)) {
1863
+ zwarn("No state found on element");
1864
+ return null;
1865
+ }
1866
+ return target.__state;
1867
+ }
1868
+ static setState(el, newState, options = {}) {
1869
+ if (!(el == null ? void 0 : el.__state)) return;
1870
+ const { deep = false } = options;
1871
+ if (!deep) {
1872
+ Object.assign(el.__state, newState);
1873
+ return;
1874
+ }
1875
+ const merge = (t, s) => {
1876
+ Object.keys(s).forEach((k) => {
1877
+ const sv = s[k];
1878
+ if (sv && typeof sv === "object" && !Array.isArray(sv)) {
1879
+ if (!t[k] || typeof t[k] !== "object") t[k] = {};
1880
+ merge(t[k], sv);
1881
+ } else t[k] = sv;
1882
+ });
1883
+ };
1884
+ const snapshot = JSON.parse(JSON.stringify({ ...el.__state }));
1885
+ merge(snapshot, newState);
1886
+ Object.assign(el.__state, snapshot);
1887
+ }
1888
+ static watchState(el, property, callback) {
1889
+ let target = el;
1890
+ if (el.style && el.style.display === "contents" && el.children.length > 0) {
1891
+ for (let c of el.children) {
1892
+ if (c.__state) {
1893
+ target = c;
1894
+ break;
1895
+ }
1896
+ if (c.__shadowRoot) {
1897
+ for (let sc of c.__shadowRoot.children) {
1898
+ if (sc.__state) {
1899
+ target = sc;
1900
+ break;
1901
+ }
1902
+ }
1903
+ if (target !== el) break;
1904
+ }
1905
+ }
1906
+ }
1907
+ if (!(target == null ? void 0 : target.__state)) {
1908
+ zwarn("No state found on element");
1909
+ return;
1910
+ }
1911
+ if (!target.__stateWatchers) target.__stateWatchers = {};
1912
+ if (!target.__stateWatchers[property]) target.__stateWatchers[property] = [];
1913
+ target.__stateWatchers[property].push(callback);
1914
+ }
1915
+ static async fetch(key, options = {}) {
1916
+ const {
1917
+ url = null,
1918
+ method = "GET",
1919
+ headers = {},
1920
+ body = null,
1921
+ cacheFirst = true,
1922
+ localChanges = true,
1923
+ diff = true,
1924
+ diffIdKey = "id",
1925
+ autoRefresh = 0,
1926
+ onDiff = null,
1927
+ onSuccess = null,
1928
+ onError = null,
1929
+ _customFetch = null,
1930
+ pagination = false,
1931
+ pageSize = 10,
1932
+ initialPage = 1,
1933
+ pageParam = "page",
1934
+ sizeParam = "limit",
1935
+ dataPath = null
1936
+ } = options;
1937
+ if (!_Zum._fetchCache) {
1938
+ _Zum._fetchCache = /* @__PURE__ */ new Map();
1939
+ _Zum._loadFetchCache();
1940
+ }
1941
+ if (!_Zum._fetchCache.has(key)) {
1942
+ _Zum._fetchCache.set(key, {
1943
+ serverData: null,
1944
+ localChanges: {},
1945
+ lastFetch: null,
1946
+ subscribers: [],
1947
+ previousData: null,
1948
+ pages: /* @__PURE__ */ new Map(),
1949
+ paginationMeta: null
1950
+ });
1951
+ }
1952
+ const cache = _Zum._fetchCache.get(key);
1953
+ const extractData = (response) => {
1954
+ if (dataPath) return dataPath.split(".").reduce((obj, k) => obj == null ? void 0 : obj[k], response);
1955
+ if (Array.isArray(response)) return response;
1956
+ return response.data || response.items || response.posts || response.results || [response];
1957
+ };
1958
+ const extractPagination = (response) => {
1959
+ if (response.pagination) return response.pagination;
1960
+ if (response.meta) return response.meta;
1961
+ return {
1962
+ page: response.page || 1,
1963
+ totalPages: response.totalPages || response.total_pages || 1,
1964
+ total: response.total || response.totalItems || 0,
1965
+ pageSize: response.pageSize || response.per_page || pageSize
1966
+ };
1967
+ };
1968
+ const buildUrl = (page) => {
1969
+ if (!url) return null;
1970
+ let pageUrl = url.replace(`{${pageParam}}`, page).replace(`{${sizeParam}}`, pageSize);
1971
+ if (!url.includes("{")) {
1972
+ const sep = url.includes("?") ? "&" : "?";
1973
+ pageUrl = `${url}${sep}${pageParam}=${page}&${sizeParam}=${pageSize}`;
1974
+ }
1975
+ return pageUrl;
1976
+ };
1977
+ const fetchPage = async (page) => {
1978
+ if (pagination && cache.pages.has(page)) {
1979
+ cache.paginationMeta.currentPage = page;
1980
+ return cache.pages.get(page);
1981
+ }
1982
+ let serverData;
1983
+ if (_customFetch) serverData = await _customFetch(page);
1984
+ else if (url) {
1985
+ const pu = buildUrl(page);
1986
+ const fo = { method, headers: { "Content-Type": "application/json", ...headers } };
1987
+ if (body) fo.body = JSON.stringify(body);
1988
+ const r = await fetch(pu, fo);
1989
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
1990
+ serverData = await r.json();
1991
+ } else throw new Error("No url or _customFetch");
1992
+ const da = extractData(serverData), pm = extractPagination(serverData);
1993
+ if (pagination) {
1994
+ cache.pages.set(page, da);
1995
+ cache.paginationMeta = { ...pm, currentPage: page, pageSize, hasNext: page < pm.totalPages, hasPrev: page > 1 };
1996
+ }
1997
+ return da;
1998
+ };
1999
+ const state = {
2000
+ data: null,
2001
+ loading: true,
2002
+ error: null,
2003
+ lastFetch: null,
2004
+ hasLocalChanges: Object.keys(cache.localChanges).length > 0,
2005
+ diff: { summary: { added: 0, updated: 0, deleted: 0, unchanged: 0, total: 0, hasChanges: false }, added: [], updated: [], deleted: [], unchanged: [] },
2006
+ pagination: pagination ? {
2007
+ currentPage: initialPage,
2008
+ totalPages: 1,
2009
+ totalItems: 0,
2010
+ pageSize,
2011
+ hasNext: false,
2012
+ hasPrev: false,
2013
+ cachedPages: []
2014
+ } : null,
2015
+ nextPage: pagination ? async () => {
2016
+ var _a;
2017
+ if (!state.pagination.hasNext) return;
2018
+ state.loading = true;
2019
+ notify();
2020
+ try {
2021
+ const d = await fetchPage(state.pagination.currentPage + 1);
2022
+ state.data = d;
2023
+ state.pagination.currentPage++;
2024
+ state.pagination.hasPrev = true;
2025
+ state.pagination.hasNext = ((_a = cache.paginationMeta) == null ? void 0 : _a.hasNext) || false;
2026
+ state.pagination.cachedPages = Array.from(cache.pages.keys());
2027
+ state.lastFetch = Date.now();
2028
+ } catch (e) {
2029
+ state.error = e.message;
2030
+ }
2031
+ state.loading = false;
2032
+ notify();
2033
+ } : null,
2034
+ prevPage: pagination ? async () => {
2035
+ var _a;
2036
+ if (!state.pagination.hasPrev) return;
2037
+ state.loading = true;
2038
+ notify();
2039
+ try {
2040
+ const d = await fetchPage(state.pagination.currentPage - 1);
2041
+ state.data = d;
2042
+ state.pagination.currentPage--;
2043
+ state.pagination.hasNext = true;
2044
+ state.pagination.hasPrev = ((_a = cache.paginationMeta) == null ? void 0 : _a.hasPrev) || state.pagination.currentPage > 1;
2045
+ state.pagination.cachedPages = Array.from(cache.pages.keys());
2046
+ state.lastFetch = Date.now();
2047
+ } catch (e) {
2048
+ state.error = e.message;
2049
+ }
2050
+ state.loading = false;
2051
+ notify();
2052
+ } : null,
2053
+ goToPage: pagination ? async (page) => {
2054
+ var _a;
2055
+ state.loading = true;
2056
+ notify();
2057
+ try {
2058
+ const d = await fetchPage(page);
2059
+ state.data = d;
2060
+ state.pagination.currentPage = page;
2061
+ state.pagination.hasPrev = page > 1;
2062
+ state.pagination.hasNext = ((_a = cache.paginationMeta) == null ? void 0 : _a.hasNext) || false;
2063
+ state.pagination.cachedPages = Array.from(cache.pages.keys());
2064
+ state.lastFetch = Date.now();
2065
+ } catch (e) {
2066
+ state.error = e.message;
2067
+ }
2068
+ state.loading = false;
2069
+ notify();
2070
+ } : null,
2071
+ refresh: async () => {
2072
+ var _a;
2073
+ state.loading = true;
2074
+ state.error = null;
2075
+ notify();
2076
+ try {
2077
+ const cp = pagination ? ((_a = state.pagination) == null ? void 0 : _a.currentPage) || 1 : 1;
2078
+ let sd;
2079
+ if (pagination) {
2080
+ cache.pages.delete(cp);
2081
+ sd = await fetchPage(cp);
2082
+ } else {
2083
+ if (_customFetch) sd = await _customFetch();
2084
+ else if (url) {
2085
+ const r = await fetch(url, { method, headers });
2086
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
2087
+ sd = await r.json();
2088
+ }
2089
+ sd = extractData(sd);
2090
+ }
2091
+ if (diff && cache.previousData) {
2092
+ const dr = _Zum._differ.diff(cache.previousData, sd, diffIdKey);
2093
+ if (dr) {
2094
+ state.diff = { summary: dr.summary, added: dr.added, updated: dr.updated, deleted: dr.deleted, unchanged: dr.unchanged };
2095
+ state.data = dr.all;
2096
+ if (onDiff) onDiff(state.diff);
2097
+ } else state.data = sd;
2098
+ } else state.data = sd;
2099
+ cache.previousData = JSON.parse(JSON.stringify(sd));
2100
+ cache.serverData = sd;
2101
+ cache.lastFetch = Date.now();
2102
+ state.lastFetch = cache.lastFetch;
2103
+ if (localChanges && cache.localChanges && state.data) {
2104
+ state.data = state.data.map((item) => {
2105
+ const id = item[diffIdKey];
2106
+ const lc = cache.localChanges[id];
2107
+ return lc ? { ...item, ...lc, __localEdit: true } : item;
2108
+ });
2109
+ }
2110
+ state.hasLocalChanges = Object.keys(cache.localChanges).length > 0;
2111
+ state.loading = false;
2112
+ if (onSuccess) onSuccess(state.data);
2113
+ } catch (e) {
2114
+ state.error = e.message;
2115
+ state.loading = false;
2116
+ if (onError) onError(e);
2117
+ }
2118
+ notify();
2119
+ },
2120
+ updateItem: (itemId, changes) => {
2121
+ if (!cache.localChanges[itemId]) cache.localChanges[itemId] = {};
2122
+ Object.assign(cache.localChanges[itemId], changes);
2123
+ if (state.data) {
2124
+ const item = state.data.find((i) => i[diffIdKey] == itemId);
2125
+ if (item) Object.assign(item, changes);
2126
+ }
2127
+ state.hasLocalChanges = true;
2128
+ notify();
2129
+ _Zum._saveFetchCache();
2130
+ },
2131
+ revertItem: (itemId) => {
2132
+ var _a;
2133
+ delete cache.localChanges[itemId];
2134
+ const si = (_a = cache.serverData) == null ? void 0 : _a.find((i) => i[diffIdKey] == itemId);
2135
+ if (si && state.data) {
2136
+ const idx = state.data.findIndex((i) => i[diffIdKey] == itemId);
2137
+ if (idx >= 0) state.data[idx] = { ...si };
2138
+ }
2139
+ state.hasLocalChanges = Object.keys(cache.localChanges).length > 0;
2140
+ notify();
2141
+ _Zum._saveFetchCache();
2142
+ },
2143
+ syncToServer: async (syncUrl = null) => {
2144
+ const tu = syncUrl || url;
2145
+ try {
2146
+ const r = await fetch(tu, {
2147
+ method: "PATCH",
2148
+ headers: { "Content-Type": "application/json", ...headers },
2149
+ body: JSON.stringify({ changes: { ...cache.localChanges } })
2150
+ });
2151
+ if (r.ok) {
2152
+ cache.localChanges = {};
2153
+ state.hasLocalChanges = false;
2154
+ notify();
2155
+ _Zum._saveFetchCache();
2156
+ }
2157
+ } catch (e) {
2158
+ zerr("Sync failed:", e);
2159
+ }
2160
+ },
2161
+ subscribe: (cb) => {
2162
+ cache.subscribers.push(cb);
2163
+ return () => {
2164
+ cache.subscribers = cache.subscribers.filter((c) => c !== cb);
2165
+ };
2166
+ }
2167
+ };
2168
+ function notify() {
2169
+ cache.subscribers.forEach((cb) => cb(state));
2170
+ }
2171
+ if (pagination) {
2172
+ state.loading = true;
2173
+ notify();
2174
+ try {
2175
+ const d = await fetchPage(initialPage);
2176
+ state.data = d;
2177
+ state.pagination = { ...cache.paginationMeta, cachedPages: Array.from(cache.pages.keys()) };
2178
+ state.lastFetch = Date.now();
2179
+ } catch (e) {
2180
+ state.error = e.message;
2181
+ }
2182
+ state.loading = false;
2183
+ notify();
2184
+ } else {
2185
+ if (cacheFirst && cache.serverData) {
2186
+ state.data = cache.serverData.map((item) => {
2187
+ var _a;
2188
+ const lc = (_a = cache.localChanges) == null ? void 0 : _a[item[diffIdKey]];
2189
+ return lc ? { ...item, ...lc, __localEdit: true } : item;
2190
+ });
2191
+ state.loading = false;
2192
+ state.lastFetch = cache.lastFetch;
2193
+ state.hasLocalChanges = Object.keys(cache.localChanges).length > 0;
2194
+ state.diff.summary.total = state.data.length;
2195
+ }
2196
+ await state.refresh();
2197
+ }
2198
+ if (autoRefresh > 0) {
2199
+ const iv = setInterval(() => state.refresh(), autoRefresh);
2200
+ state._autoRefreshInterval = iv;
2201
+ }
2202
+ state._saveCache = () => _Zum._saveFetchCache();
2203
+ return state;
2204
+ }
2205
+ static _saveFetchCache() {
2206
+ if (!_Zum._fetchCache) return;
2207
+ const cd = {};
2208
+ _Zum._fetchCache.forEach((v, k) => {
2209
+ cd[k] = { serverData: v.serverData, localChanges: v.localChanges, lastFetch: v.lastFetch, previousData: v.previousData };
2210
+ });
2211
+ try {
2212
+ localStorage.setItem("__Zum_fetch_cache", JSON.stringify(cd));
2213
+ } catch (e) {
2214
+ }
2215
+ }
2216
+ static _loadFetchCache() {
2217
+ try {
2218
+ const c = localStorage.getItem("__Zum_fetch_cache");
2219
+ if (c) {
2220
+ const d = JSON.parse(c);
2221
+ Object.entries(d).forEach(([k, v]) => _Zum._fetchCache.set(k, v));
2222
+ }
2223
+ } catch (e) {
2224
+ }
2225
+ }
2226
+ static _initFetchCache() {
2227
+ if (!_Zum._fetchCache) {
2228
+ _Zum._fetchCache = /* @__PURE__ */ new Map();
2229
+ _Zum._loadFetchCache();
2230
+ }
2231
+ }
2232
+ static clearFetchCache() {
2233
+ localStorage.removeItem("__Zum_fetch_cache");
2234
+ if (_Zum._fetchCache) _Zum._fetchCache.clear();
2235
+ zlog("\u{1F5D1}\uFE0F Fetch cache cleared");
2236
+ }
2237
+ // ═══ SCROLL MEMORY ═══
2238
+ static rememberScroll(componentName, options = {}) {
2239
+ const { scrollBehavior = "smooth", scope = "global", saveDelay = 200, highlightTarget = true, offsetTop = 0 } = options;
2240
+ const key = `${scope}::${componentName}`;
2241
+ let scrollTimeout, lastKnownPosition = 0, lastFocusedElement = null;
2242
+ const savedData = _Zum._scrollMemory.get(key);
2243
+ if (savedData) {
2244
+ lastKnownPosition = savedData.position || 0;
2245
+ lastFocusedElement = savedData.elementId || null;
2246
+ }
2247
+ return {
2248
+ save: function(elementId = null) {
2249
+ lastKnownPosition = window.scrollY || window.pageYOffset;
2250
+ if (elementId) lastFocusedElement = elementId;
2251
+ _Zum._scrollMemory.set(key, { position: lastKnownPosition, elementId: lastFocusedElement, timestamp: Date.now() });
2252
+ },
2253
+ restore: function() {
2254
+ const data = _Zum._scrollMemory.get(key);
2255
+ if (!data) return false;
2256
+ const { position, elementId } = data;
2257
+ if (elementId) {
2258
+ const element = document.getElementById(elementId);
2259
+ if (element) {
2260
+ const rect = element.getBoundingClientRect();
2261
+ const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
2262
+ const elementTop = rect.top + scrollTop;
2263
+ const windowHeight = window.innerHeight;
2264
+ const scrollTo = elementTop - windowHeight / 2 + rect.height / 2 + offsetTop;
2265
+ window.scrollTo({ top: Math.max(0, scrollTo), behavior: scrollBehavior });
2266
+ if (highlightTarget) {
2267
+ const ot = element.style.transition, ob = element.style.boxShadow, obc = element.style.borderColor;
2268
+ element.style.transition = "box-shadow 0.3s, border-color 0.3s";
2269
+ element.style.boxShadow = "0 0 0 4px rgba(59, 130, 246, 0.5)";
2270
+ element.style.borderColor = "#3b82f6";
2271
+ setTimeout(() => {
2272
+ element.style.transition = ot;
2273
+ element.style.boxShadow = ob;
2274
+ element.style.borderColor = obc;
2275
+ }, 2e3);
2276
+ }
2277
+ return true;
2278
+ }
2279
+ }
2280
+ if (position > 0) {
2281
+ window.scrollTo({ top: position, behavior: scrollBehavior });
2282
+ return true;
2283
+ }
2284
+ return false;
2285
+ },
2286
+ startTracking: function(container = document) {
2287
+ const scrollHandler = () => {
2288
+ clearTimeout(scrollTimeout);
2289
+ scrollTimeout = setTimeout(() => this.save(), saveDelay);
2290
+ };
2291
+ window.addEventListener("scroll", scrollHandler, { passive: true });
2292
+ const clickHandler = (e) => {
2293
+ const target = e.target.closest("[id]");
2294
+ if (target && target.id) this.save(target.id);
2295
+ };
2296
+ container.addEventListener("click", clickHandler);
2297
+ const beforeUnloadHandler = () => this.save();
2298
+ window.addEventListener("beforeunload", beforeUnloadHandler);
2299
+ return () => {
2300
+ window.removeEventListener("scroll", scrollHandler);
2301
+ container.removeEventListener("click", clickHandler);
2302
+ window.removeEventListener("beforeunload", beforeUnloadHandler);
2303
+ };
2304
+ },
2305
+ clear: function() {
2306
+ _Zum._scrollMemory.delete(key);
2307
+ lastKnownPosition = 0;
2308
+ lastFocusedElement = null;
2309
+ },
2310
+ getData: function() {
2311
+ return _Zum._scrollMemory.get(key) || null;
2312
+ }
2313
+ };
2314
+ }
2315
+ static saveScrollToState(el, elementId = null) {
2316
+ const state = _Zum.getState(el);
2317
+ if (state) {
2318
+ state.__scrollPosition = window.scrollY || window.pageYOffset;
2319
+ if (elementId) state.__lastFocusedElement = elementId;
2320
+ }
2321
+ }
2322
+ static restoreScrollFromState(el, options = {}) {
2323
+ const state = _Zum.getState(el);
2324
+ if (!state) return false;
2325
+ const { highlightTarget = true, scrollBehavior = "smooth", offsetTop = 0 } = options;
2326
+ const position = state.__scrollPosition;
2327
+ const elementId = state.__lastFocusedElement;
2328
+ if (elementId) {
2329
+ const element = _Zum.querySelector(el, `#${elementId}`) || document.getElementById(elementId);
2330
+ if (element) {
2331
+ const rect = element.getBoundingClientRect();
2332
+ const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
2333
+ const elementTop = rect.top + scrollTop;
2334
+ const windowHeight = window.innerHeight;
2335
+ const scrollTo = elementTop - windowHeight / 2 + rect.height / 2 + offsetTop;
2336
+ window.scrollTo({ top: Math.max(0, scrollTo), behavior: scrollBehavior });
2337
+ if (highlightTarget) {
2338
+ element.style.transition = "box-shadow 0.3s, border-color 0.3s";
2339
+ element.style.boxShadow = "0 0 0 4px rgba(59, 130, 246, 0.5)";
2340
+ element.style.borderColor = "#3b82f6";
2341
+ setTimeout(() => {
2342
+ element.style.boxShadow = "";
2343
+ element.style.borderColor = "";
2344
+ }, 2e3);
2345
+ }
2346
+ return true;
2347
+ }
2348
+ }
2349
+ if (position > 0) {
2350
+ window.scrollTo({ top: position, behavior: scrollBehavior });
2351
+ return true;
2352
+ }
2353
+ return false;
2354
+ }
2355
+ static initTheme(themeId = "light") {
2356
+ if (!_Zum._themeStylesInjected) _Zum._injectThemeStyles();
2357
+ if (_Zum.THEMES[themeId]) {
2358
+ _Zum._currentTheme = themeId;
2359
+ _Zum.applyTheme(themeId);
2360
+ return true;
2361
+ }
2362
+ zwarn(`Theme "${themeId}" not found. Using light theme.`);
2363
+ _Zum._currentTheme = "light";
2364
+ _Zum.applyTheme("light");
2365
+ return false;
2366
+ }
2367
+ static restoreThemePreference() {
2368
+ const savedTheme = localStorage.getItem(_Zum.themeSettings.persistKey);
2369
+ if (savedTheme && _Zum.THEMES[savedTheme]) {
2370
+ _Zum.applyTheme(savedTheme, { manual: false });
2371
+ return true;
2372
+ }
2373
+ if (_Zum.themeSettings.respectSystemPreference) {
2374
+ const systemTheme = _Zum.getSystemThemePreference();
2375
+ _Zum.applyTheme(systemTheme, { manual: false });
2376
+ return true;
2377
+ }
2378
+ return false;
2379
+ }
2380
+ static getSystemThemePreference() {
2381
+ if (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) return "dark";
2382
+ return "light";
2383
+ }
2384
+ static initThemeWithSystemPreference() {
2385
+ const savedTheme = localStorage.getItem(_Zum.themeSettings.persistKey);
2386
+ const isManual = localStorage.getItem(_Zum.themeSettings.systemPreferenceKey);
2387
+ if (savedTheme && isManual && _Zum.THEMES[savedTheme]) {
2388
+ _Zum.applyTheme(savedTheme, { manual: true });
2389
+ zlog(`\u2705 Theme initialized with manual preference: ${savedTheme}`);
2390
+ return;
2391
+ }
2392
+ const systemTheme = _Zum.getSystemThemePreference();
2393
+ _Zum.applyTheme(systemTheme, { manual: false });
2394
+ const darkModeQuery = window.matchMedia("(prefers-color-scheme: dark)");
2395
+ const handleChange = (e) => {
2396
+ const manualOverride = localStorage.getItem(_Zum.themeSettings.systemPreferenceKey);
2397
+ if (!manualOverride) {
2398
+ const newTheme = e.matches ? "dark" : "light";
2399
+ document.querySelectorAll("*").forEach((el) => {
2400
+ el._zumContrastApplied = false;
2401
+ });
2402
+ _Zum.applyTheme(newTheme, { manual: false, smooth: true, duration: 400 });
2403
+ setTimeout(() => _Zum.refreshContrast(), 500);
2404
+ zlog(`\u{1F504} Auto-switched to ${newTheme} theme (system preference)`);
2405
+ }
2406
+ };
2407
+ if (darkModeQuery.addEventListener) darkModeQuery.addEventListener("change", handleChange);
2408
+ else if (darkModeQuery.addListener) darkModeQuery.addListener(handleChange);
2409
+ zlog(`\u2705 Theme initialized with system preference: ${systemTheme}`);
2410
+ }
2411
+ static isUsingSystemTheme() {
2412
+ return !localStorage.getItem(_Zum.themeSettings.systemPreferenceKey);
2413
+ }
2414
+ static resetToSystemTheme() {
2415
+ localStorage.removeItem(_Zum.themeSettings.systemPreferenceKey);
2416
+ const systemTheme = _Zum.getSystemThemePreference();
2417
+ _Zum.applyTheme(systemTheme, { manual: false });
2418
+ zlog(`\u{1F504} Reset to system theme: ${systemTheme}`);
2419
+ }
2420
+ static applyTheme(themeId, options = {}) {
2421
+ if (!hasDOM()) return false;
2422
+ const { smooth = true, duration = 400, ease = "ease-in-out", updateContrast = true, manual = true } = options;
2423
+ const theme = _Zum.THEMES[themeId];
2424
+ if (!theme) {
2425
+ zwarn(`Theme "${themeId}" not found.`);
2426
+ return false;
2427
+ }
2428
+ _Zum._currentTheme = themeId;
2429
+ if (manual) localStorage.setItem(_Zum.themeSettings.systemPreferenceKey, "true");
2430
+ else localStorage.removeItem(_Zum.themeSettings.systemPreferenceKey);
2431
+ const root = document.documentElement;
2432
+ const colors = theme.colors;
2433
+ document.querySelectorAll("style[data-Zum-themes], style[data-Zum-theme]").forEach((s) => s.remove());
2434
+ _Zum._injectThemeStyles();
2435
+ Object.entries(colors).forEach(([key, value]) => root.style.setProperty(`--Zum-${key}`, value));
2436
+ Object.entries(theme.typography).forEach(([key, value]) => root.style.setProperty(`--Zum-font-${key}`, value));
2437
+ Object.entries(theme.spacing).forEach(([key, value]) => root.style.setProperty(`--Zum-spacing-${key}`, value));
2438
+ Object.entries(theme.borderRadius).forEach(([key, value]) => root.style.setProperty(`--Zum-radius-${key}`, value));
2439
+ Object.entries(theme.shadows).forEach(([key, value]) => root.style.setProperty(`--Zum-shadow-${key}`, value));
2440
+ Object.entries(theme.transitions).forEach(([key, value]) => root.style.setProperty(`--Zum-transition-${key}`, value));
2441
+ document.body.style.backgroundColor = colors.background;
2442
+ document.body.style.color = colors.text;
2443
+ document.body.style.fontFamily = theme.typography.fontFamily;
2444
+ document.body.style.fontSize = theme.typography.fontSize;
2445
+ document.body.style.lineHeight = theme.typography.lineHeight;
2446
+ document.documentElement.style.backgroundColor = colors.background;
2447
+ const metaThemeColor = document.querySelector('meta[name="theme-color"]');
2448
+ if (metaThemeColor) metaThemeColor.content = colors.background;
2449
+ document.documentElement.setAttribute("data-theme", themeId);
2450
+ document.body.setAttribute("data-theme", themeId);
2451
+ if (_Zum.themeSettings.persist) localStorage.setItem(_Zum.themeSettings.persistKey, themeId);
2452
+ _Zum._notifyThemeObservers(themeId);
2453
+ if (updateContrast && _Zum.themeSettings.autoContrast) {
2454
+ setTimeout(() => {
2455
+ document.querySelectorAll("*").forEach((el) => {
2456
+ el._zumContrastApplied = false;
2457
+ });
2458
+ _Zum._applyContrastToAll();
2459
+ }, smooth ? duration + 50 : 50);
2460
+ }
2461
+ zlog(`\u2705 Theme applied: ${themeId} (${theme.name})`);
2462
+ return true;
2463
+ }
2464
+ static toggleTheme() {
2465
+ return _Zum.applyTheme(_Zum._currentTheme === "light" ? "dark" : "light");
2466
+ }
2467
+ static applyThemeToElement(el, themeId = null) {
2468
+ if (!el) return false;
2469
+ const theme = themeId ? _Zum.THEMES[themeId] : _Zum.getTheme();
2470
+ if (!theme) return false;
2471
+ const target = el._isShadowHost ? _Zum.getShadowRoot(el) : el;
2472
+ if (!target) return false;
2473
+ Object.entries(theme.colors).forEach(([key, value]) => target.style.setProperty(`--Zum-${key}`, value));
2474
+ target.style.backgroundColor = theme.colors.background;
2475
+ target.style.color = theme.colors.text;
2476
+ return true;
2477
+ }
2478
+ static applyThemeToCustomElement(element, themeId) {
2479
+ const theme = _Zum.getTheme(themeId);
2480
+ if (!theme || !element) return false;
2481
+ const cssProps = _Zum.getThemeCSSProperties(themeId);
2482
+ element.style.cssText += cssProps;
2483
+ element.setAttribute("data-theme", themeId);
2484
+ element.style.backgroundColor = theme.colors.background;
2485
+ element.style.color = theme.colors.text;
2486
+ return true;
2487
+ }
2488
+ static applyThemeToElementDirect(el, bgColor, textColor) {
2489
+ if (!el) return;
2490
+ if (_Zum.isShadowHost(el)) {
2491
+ const shadow = _Zum.getShadowRoot(el);
2492
+ if (!shadow) return;
2493
+ shadow.querySelectorAll("style[data-Zum-theme]").forEach((s) => s.remove());
2494
+ const styleEl = document.createElement("style");
2495
+ styleEl.setAttribute("data-Zum-theme", "true");
2496
+ styleEl.textContent = `:host { background: ${bgColor}; color: ${textColor}; }`;
2497
+ shadow.appendChild(styleEl);
2498
+ }
2499
+ }
2500
+ static getCurrentTheme() {
2501
+ return _Zum._currentTheme;
2502
+ }
2503
+ static getTheme(themeId = null) {
2504
+ return _Zum.THEMES[themeId || _Zum._currentTheme] || null;
2505
+ }
2506
+ static getThemeSafe(themeId) {
2507
+ return _Zum.THEMES[themeId] || _Zum.THEMES[_Zum.themeSettings.defaultTheme] || _Zum.THEMES.light;
2508
+ }
2509
+ static getThemeName(themeId) {
2510
+ const t = _Zum.getTheme(themeId);
2511
+ return t ? t.name : themeId;
2512
+ }
2513
+ static getThemeNames() {
2514
+ const names = {};
2515
+ Object.entries(_Zum.THEMES).forEach(([id, theme]) => {
2516
+ names[id] = theme.name || id;
2517
+ });
2518
+ return names;
2519
+ }
2520
+ static getThemeColors(themeId = null) {
2521
+ const t = _Zum.getTheme(themeId);
2522
+ return t ? t.colors : null;
2523
+ }
2524
+ static getThemeColor(colorKey, themeId = null) {
2525
+ const t = themeId ? _Zum.THEMES[themeId] : _Zum.getTheme();
2526
+ return t ? t.colors[colorKey] || null : null;
2527
+ }
2528
+ static getAvailableThemes() {
2529
+ return Object.keys(_Zum.THEMES);
2530
+ }
2531
+ static themeExists(themeId) {
2532
+ return !!_Zum.THEMES[themeId];
2533
+ }
2534
+ static getThemeSettings() {
2535
+ return { ..._Zum.themeSettings };
2536
+ }
2537
+ static updateThemeSettings(settings) {
2538
+ Object.assign(_Zum.themeSettings, settings);
2539
+ return _Zum.themeSettings;
2540
+ }
2541
+ static setDefaultTheme(themeId) {
2542
+ if (_Zum.themeExists(themeId)) {
2543
+ _Zum.themeSettings.defaultTheme = themeId;
2544
+ return true;
2545
+ }
2546
+ return false;
2547
+ }
2548
+ static resetToDefaultTheme() {
2549
+ return _Zum.applyTheme(_Zum.themeSettings.defaultTheme, { manual: false });
2550
+ }
2551
+ static setThemePersistence(enabled) {
2552
+ _Zum.themeSettings.persist = enabled;
2553
+ if (!enabled) {
2554
+ localStorage.removeItem(_Zum.themeSettings.persistKey);
2555
+ localStorage.removeItem(_Zum.themeSettings.systemPreferenceKey);
2556
+ }
2557
+ }
2558
+ static isDarkTheme() {
2559
+ return _Zum._currentTheme === "dark";
2560
+ }
2561
+ static isLightTheme() {
2562
+ return _Zum._currentTheme === "light";
2563
+ }
2564
+ static getThemeMode() {
2565
+ return _Zum.isUsingSystemTheme() ? "system" : "manual";
2566
+ }
2567
+ static addTheme(themeId, themeConfig) {
2568
+ if (_Zum.THEMES[themeId]) zwarn(`Theme "${themeId}" already exists. Overwriting.`);
2569
+ const requiredKeys = ["colors", "typography", "spacing", "borderRadius", "shadows", "transitions"];
2570
+ const missingKeys = requiredKeys.filter((key) => !themeConfig[key]);
2571
+ if (missingKeys.length > 0) {
2572
+ zerr(`Theme missing required keys: ${missingKeys.join(", ")}`);
2573
+ return false;
2574
+ }
2575
+ _Zum.THEMES[themeId] = { id: themeId, name: themeConfig.name || themeId, ...themeConfig };
2576
+ return true;
2577
+ }
2578
+ static defineTheme(themeId, theme) {
2579
+ if (!theme || !theme.colors) {
2580
+ zerr("Zum.defineTheme: theme must include a colors object.");
2581
+ return false;
2582
+ }
2583
+ const base = _Zum.THEMES.light;
2584
+ _Zum.THEMES[themeId] = {
2585
+ id: themeId,
2586
+ name: theme.name || themeId,
2587
+ colors: { ...base.colors, ...theme.colors },
2588
+ typography: { ...base.typography, ...theme.typography || {} },
2589
+ spacing: { ...base.spacing, ...theme.spacing || {} },
2590
+ borderRadius: { ...base.borderRadius, ...theme.borderRadius || {} },
2591
+ shadows: { ...base.shadows, ...theme.shadows || {} },
2592
+ transitions: { ...base.transitions, ...theme.transitions || {} }
2593
+ };
2594
+ return true;
2595
+ }
2596
+ static removeTheme(themeId) {
2597
+ if (themeId === "light" || themeId === "dark") {
2598
+ zwarn("Cannot remove default themes (light/dark)");
2599
+ return false;
2600
+ }
2601
+ if (_Zum.THEMES[themeId]) {
2602
+ delete _Zum.THEMES[themeId];
2603
+ return true;
2604
+ }
2605
+ return false;
2606
+ }
2607
+ static duplicateTheme(sourceId, newId) {
2608
+ const source = _Zum.getTheme(sourceId);
2609
+ if (!source) return false;
2610
+ return _Zum.addTheme(newId, { ...source, id: newId, name: `${source.name} (Copy)` });
2611
+ }
2612
+ static exportTheme(themeId) {
2613
+ const theme = _Zum.getTheme(themeId);
2614
+ return theme ? JSON.stringify(theme, null, 2) : null;
2615
+ }
2616
+ static importTheme(themeJson) {
2617
+ try {
2618
+ const theme = JSON.parse(themeJson);
2619
+ if (!theme.id || !theme.colors || !theme.typography) throw new Error("Invalid theme format");
2620
+ _Zum.addTheme(theme.id, theme);
2621
+ return true;
2622
+ } catch (error) {
2623
+ zerr("Failed to import theme:", error);
2624
+ return false;
2625
+ }
2626
+ }
2627
+ static observeTheme(callback) {
2628
+ if (typeof callback !== "function") return () => {
2629
+ };
2630
+ _Zum._themeObservers.push(callback);
2631
+ callback(_Zum._currentTheme);
2632
+ return () => {
2633
+ _Zum._themeObservers = _Zum._themeObservers.filter((cb) => cb !== callback);
2634
+ };
2635
+ }
2636
+ static onThemeChange(cb) {
2637
+ return _Zum.observeTheme(cb);
2638
+ }
2639
+ static _notifyThemeObservers(themeId) {
2640
+ _Zum._themeObservers.forEach((callback) => {
2641
+ try {
2642
+ callback(themeId);
2643
+ } catch (error) {
2644
+ zerr("Theme observer error:", error);
2645
+ }
2646
+ });
2647
+ }
2648
+ static getContrastRatio(color1, color2) {
2649
+ const lum1 = _Zum._calculateLuminance(color1);
2650
+ const lum2 = _Zum._calculateLuminance(color2);
2651
+ const lighter = Math.max(lum1, lum2);
2652
+ const darker = Math.min(lum1, lum2);
2653
+ return (lighter + 0.05) / (darker + 0.05);
2654
+ }
2655
+ static checkThemeAccessibility(themeId) {
2656
+ const theme = _Zum.getTheme(themeId);
2657
+ if (!theme) return null;
2658
+ const results = { theme: themeId, name: theme.name, passed: true, checks: [] };
2659
+ const textContrast = _Zum.getContrastRatio(theme.colors.text, theme.colors.background);
2660
+ results.checks.push({ name: "Text contrast", ratio: textContrast.toFixed(2), passed: textContrast >= 4.5, wcag: textContrast >= 4.5 ? "AA" : "Fail" });
2661
+ const secondaryContrast = _Zum.getContrastRatio(theme.colors.textSecondary, theme.colors.background);
2662
+ results.checks.push({ name: "Secondary text", ratio: secondaryContrast.toFixed(2), passed: secondaryContrast >= 3, wcag: secondaryContrast >= 3 ? "AA" : "Fail" });
2663
+ const buttonContrast = _Zum.getContrastRatio(theme.colors.primary, theme.colors.background);
2664
+ results.checks.push({ name: "Interactive", ratio: buttonContrast.toFixed(2), passed: buttonContrast >= 3, wcag: buttonContrast >= 3 ? "AA" : "Fail" });
2665
+ results.passed = results.checks.every((check) => check.passed);
2666
+ return results;
2667
+ }
2668
+ static getAccessibleThemes() {
2669
+ return Object.keys(_Zum.THEMES).filter((themeId) => {
2670
+ const result = _Zum.checkThemeAccessibility(themeId);
2671
+ return result && result.passed;
2672
+ });
2673
+ }
2674
+ static createThemeToggle(options = {}) {
2675
+ const { lightIcon = "\u2600\uFE0F", darkIcon = "\u{1F319}", systemIcon = "\u{1F313}", className = "theme-toggle", position = "fixed", top = "20px", right = "20px", smooth = true, duration = 400 } = options;
2676
+ const button = document.createElement("button");
2677
+ button.className = className;
2678
+ let currentMode = 0;
2679
+ const updateButton = (themeId) => {
2680
+ const isSystem = !localStorage.getItem(_Zum.themeSettings.systemPreferenceKey);
2681
+ if (isSystem) {
2682
+ button.textContent = systemIcon;
2683
+ button.title = "System theme";
2684
+ currentMode = 0;
2685
+ } else if (themeId === "dark") {
2686
+ button.textContent = darkIcon;
2687
+ button.title = "Dark theme";
2688
+ currentMode = 2;
2689
+ } else {
2690
+ button.textContent = lightIcon;
2691
+ button.title = "Light theme";
2692
+ currentMode = 1;
2693
+ }
2694
+ button.setAttribute("data-theme", themeId);
2695
+ };
2696
+ const style = document.createElement("style");
2697
+ style.textContent = `
2698
+ .${className} {
2699
+ position: ${position}; top: ${top}; right: ${right}; z-index: 9999;
2700
+ background: var(--Zum-surface); color: var(--Zum-text);
2701
+ border: 1px solid var(--Zum-border); border-radius: var(--Zum-radius-full);
2702
+ padding: var(--Zum-spacing-sm) var(--Zum-spacing-md);
2703
+ cursor: pointer; font-size: 20px; box-shadow: var(--Zum-shadow-md);
2704
+ transition: all ${duration}ms ease-in-out; width: 48px; height: 48px;
2705
+ display: flex; align-items: center; justify-content: center;
2706
+ backdrop-filter: blur(10px);
2707
+ }
2708
+ .${className}:hover { transform: scale(1.1); box-shadow: var(--Zum-shadow-lg); }
2709
+ .${className}:active { transform: scale(0.95); }
2710
+ `;
2711
+ document.head.appendChild(style);
2712
+ updateButton(_Zum._currentTheme);
2713
+ button.addEventListener("click", () => {
2714
+ if (currentMode === 0) {
2715
+ _Zum.applyTheme("light", { smooth, duration, manual: true });
2716
+ updateButton("light");
2717
+ } else if (currentMode === 1) {
2718
+ _Zum.applyTheme("dark", { smooth, duration, manual: true });
2719
+ updateButton("dark");
2720
+ } else {
2721
+ localStorage.removeItem(_Zum.themeSettings.systemPreferenceKey);
2722
+ const systemTheme = _Zum.getSystemThemePreference();
2723
+ _Zum.applyTheme(systemTheme, { smooth, duration, manual: false });
2724
+ updateButton(systemTheme);
2725
+ }
2726
+ });
2727
+ _Zum.observeTheme(updateButton);
2728
+ const darkModeMediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
2729
+ if (darkModeMediaQuery.addEventListener) {
2730
+ darkModeMediaQuery.addEventListener("change", () => {
2731
+ if (!localStorage.getItem(_Zum.themeSettings.systemPreferenceKey)) {
2732
+ const systemTheme = darkModeMediaQuery.matches ? "dark" : "light";
2733
+ _Zum.applyTheme(systemTheme, { smooth, duration, manual: false });
2734
+ updateButton(systemTheme);
2735
+ }
2736
+ });
2737
+ }
2738
+ return button;
2739
+ }
2740
+ static createThemeSelector(options = {}) {
2741
+ const { className = "theme-selector", includeSystem = true, currentTheme = _Zum._currentTheme, onChange = null } = options;
2742
+ const select = document.createElement("select");
2743
+ select.className = className;
2744
+ select.style.cssText = `padding: 8px 12px; border-radius: 6px; border: 1px solid var(--Zum-border); background: var(--Zum-surface); color: var(--Zum-text); cursor: pointer; font-size: 14px;`;
2745
+ if (includeSystem) {
2746
+ const option = document.createElement("option");
2747
+ option.value = "system";
2748
+ option.textContent = "\u{1F313} System";
2749
+ if (_Zum.isUsingSystemTheme()) option.selected = true;
2750
+ select.appendChild(option);
2751
+ }
2752
+ Object.entries(_Zum.THEMES).forEach(([id, theme]) => {
2753
+ const option = document.createElement("option");
2754
+ option.value = id;
2755
+ option.textContent = theme.name || id;
2756
+ if (id === currentTheme && !_Zum.isUsingSystemTheme()) option.selected = true;
2757
+ select.appendChild(option);
2758
+ });
2759
+ select.addEventListener("change", (e) => {
2760
+ const value = e.target.value;
2761
+ if (value === "system") {
2762
+ localStorage.removeItem(_Zum.themeSettings.systemPreferenceKey);
2763
+ const systemTheme = _Zum.getSystemThemePreference();
2764
+ _Zum.applyTheme(systemTheme, { manual: false });
2765
+ } else {
2766
+ _Zum.applyTheme(value, { manual: true });
2767
+ }
2768
+ if (onChange) onChange(value);
2769
+ });
2770
+ _Zum.observeTheme((themeId) => {
2771
+ select.value = _Zum.isUsingSystemTheme() ? "system" : themeId;
2772
+ });
2773
+ return select;
2774
+ }
2775
+ static createThemePreview(themeId) {
2776
+ const theme = _Zum.getTheme(themeId);
2777
+ if (!theme) return null;
2778
+ const preview = document.createElement("div");
2779
+ preview.className = "theme-preview";
2780
+ preview.style.cssText = `display: flex; flex-direction: column; gap: 10px; padding: 20px; background: ${theme.colors.background}; color: ${theme.colors.text}; border-radius: 8px; border: 1px solid ${theme.colors.border}; font-family: ${theme.typography.fontFamily}; max-width: 300px;`;
2781
+ preview.innerHTML = `
2782
+ <h3 style="color: ${theme.colors.primary};">${theme.name}</h3>
2783
+ <p style="color: ${theme.colors.textSecondary};">Theme preview</p>
2784
+ <div style="display: flex; gap: 8px; flex-wrap: wrap;">
2785
+ <span style="background: ${theme.colors.primary}; color: white; padding: 4px 12px; border-radius: 4px;">Primary</span>
2786
+ <span style="background: ${theme.colors.secondary}; color: white; padding: 4px 12px; border-radius: 4px;">Secondary</span>
2787
+ <span style="background: ${theme.colors.success}; color: white; padding: 4px 12px; border-radius: 4px;">Success</span>
2788
+ </div>
2789
+ <div style="display: flex; gap: 8px;">
2790
+ <button style="background: ${theme.colors.primary}; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer;">Button</button>
2791
+ <input type="text" placeholder="Input" style="background: ${theme.colors.inputBg}; color: ${theme.colors.text}; border: 1px solid ${theme.colors.inputBorder}; padding: 8px; border-radius: 4px;">
2792
+ </div>
2793
+ <div style="background: ${theme.colors.cardBg}; padding: 10px; border-radius: 4px; border: 1px solid ${theme.colors.border};">Card content</div>
2794
+ `;
2795
+ return preview;
2796
+ }
2797
+ static createColorPalette(themeId) {
2798
+ const theme = _Zum.getTheme(themeId);
2799
+ if (!theme) return null;
2800
+ const palette = document.createElement("div");
2801
+ palette.className = "theme-palette";
2802
+ palette.style.cssText = `display: grid; grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); gap: 10px; padding: 10px;`;
2803
+ Object.entries(theme.colors).forEach(([key, value]) => {
2804
+ const item = document.createElement("div");
2805
+ item.style.cssText = `display: flex; flex-direction: column; align-items: center; gap: 4px; padding: 8px; border-radius: 4px; background: ${value}; color: ${_Zum.getContrastColor(value)}; font-size: 11px; text-align: center;`;
2806
+ item.innerHTML = `<span style="font-weight: 600;">${key}</span><span style="opacity: 0.8;">${value}</span>`;
2807
+ palette.appendChild(item);
2808
+ });
2809
+ return palette;
2810
+ }
2811
+ static generateThemeCSS(themeId) {
2812
+ const theme = _Zum.getTheme(themeId);
2813
+ if (!theme) return "";
2814
+ let css = `[data-theme="${themeId}"] {
2815
+ `;
2816
+ Object.entries(theme.colors).forEach(([key, value]) => {
2817
+ css += ` --Zum-${key}: ${value};
2818
+ `;
2819
+ });
2820
+ Object.entries(theme.typography).forEach(([key, value]) => {
2821
+ css += ` --Zum-font-${key}: ${value};
2822
+ `;
2823
+ });
2824
+ Object.entries(theme.spacing).forEach(([key, value]) => {
2825
+ css += ` --Zum-spacing-${key}: ${value};
2826
+ `;
2827
+ });
2828
+ Object.entries(theme.borderRadius).forEach(([key, value]) => {
2829
+ css += ` --Zum-radius-${key}: ${value};
2830
+ `;
2831
+ });
2832
+ Object.entries(theme.shadows).forEach(([key, value]) => {
2833
+ css += ` --Zum-shadow-${key}: ${value};
2834
+ `;
2835
+ });
2836
+ Object.entries(theme.transitions).forEach(([key, value]) => {
2837
+ css += ` --Zum-transition-${key}: ${value};
2838
+ `;
2839
+ });
2840
+ css += "}\n";
2841
+ return css;
2842
+ }
2843
+ static generateAllThemeCSS() {
2844
+ let css = "";
2845
+ Object.keys(_Zum.THEMES).forEach((themeId) => {
2846
+ css += _Zum.generateThemeCSS(themeId);
2847
+ });
2848
+ return css;
2849
+ }
2850
+ static getThemeCSSProperties(themeId) {
2851
+ const theme = _Zum.getTheme(themeId);
2852
+ if (!theme) return "";
2853
+ let css = "";
2854
+ Object.entries(theme.colors).forEach(([key, value]) => {
2855
+ css += `--Zum-${key}: ${value};
2856
+ `;
2857
+ });
2858
+ return css;
2859
+ }
2860
+ static _injectThemeStyles() {
2861
+ document.querySelectorAll("style[data-Zum-themes]").forEach((s) => s.remove());
2862
+ const styleEl = document.createElement("style");
2863
+ styleEl.setAttribute("data-Zum-themes", "true");
2864
+ styleEl.textContent = `
2865
+ html { color-scheme: light dark; }
2866
+
2867
+ ${_Zum.generateAllThemeCSS()}
2868
+
2869
+ html, body { transition: background-color 300ms ease-in-out, color 300ms ease-in-out; }
2870
+ * { transition: background-color 300ms ease-in-out, color 300ms ease-in-out, border-color 300ms ease-in-out, box-shadow 300ms ease-in-out; }
2871
+ ::-webkit-scrollbar { width: 8px; height: 8px; }
2872
+ ::-webkit-scrollbar-track { background: var(--Zum-scrollbarTrack, #f1f5f9); }
2873
+ ::-webkit-scrollbar-thumb { background: var(--Zum-scrollbarThumb, #cbd5e1); border-radius: var(--Zum-radius-full, 9999px); }
2874
+ ::selection { background: var(--Zum-primary, #3b82f6); color: var(--Zum-text, #ffffff); }
2875
+ `;
2876
+ document.head.appendChild(styleEl);
2877
+ _Zum._themeStylesInjected = true;
2878
+ }
2879
+ static refreshTheme() {
2880
+ const currentTheme = _Zum._currentTheme;
2881
+ if (currentTheme) {
2882
+ _Zum.applyTheme(currentTheme);
2883
+ document.querySelectorAll(".theme-aware, [data-theme]").forEach((el) => {
2884
+ if (el !== document.documentElement && el !== document.body) el.setAttribute("data-theme", currentTheme);
2885
+ });
2886
+ window.dispatchEvent(new CustomEvent("zum-theme-refreshed", { detail: { theme: currentTheme } }));
2887
+ zlog(`\u{1F504} Theme refreshed: ${currentTheme}`);
2888
+ }
2889
+ }
2890
+ static reloadTheme() {
2891
+ return _Zum.applyTheme(_Zum._currentTheme);
2892
+ }
2893
+ static clearThemePreferences() {
2894
+ localStorage.removeItem(_Zum.themeSettings.persistKey);
2895
+ localStorage.removeItem(_Zum.themeSettings.systemPreferenceKey);
2896
+ zlog("\u{1F5D1}\uFE0F Theme preferences cleared");
2897
+ }
2898
+ static clearAllThemeData() {
2899
+ localStorage.removeItem(_Zum.themeSettings.persistKey);
2900
+ localStorage.removeItem(_Zum.themeSettings.systemPreferenceKey);
2901
+ _Zum._currentTheme = _Zum.themeSettings.defaultTheme;
2902
+ _Zum._themeObservers = [];
2903
+ document.querySelectorAll("style[data-Zum-themes]").forEach((s) => s.remove());
2904
+ document.querySelectorAll("style[data-Zum-theme]").forEach((s) => s.remove());
2905
+ document.querySelectorAll("style[data-Zum-contrast]").forEach((s) => s.remove());
2906
+ _Zum._themeStylesInjected = false;
2907
+ _Zum._contrastInitialized = false;
2908
+ document.documentElement.removeAttribute("data-theme");
2909
+ if (document.body) document.body.removeAttribute("data-theme");
2910
+ zlog("\u{1F5D1}\uFE0F All theme data cleared");
2911
+ }
2912
+ static clearAllZumData() {
2913
+ const keysToRemove = ["Zum_theme_preference", "Zum_theme_preference_manual", "ZumKey", "app-name", "__Zum_fetch_cache", "__Zum_refreshing", "__Zum_loaded", "__Zum_license_cache", "__Zum_pubkey"];
2914
+ keysToRemove.forEach((key) => {
2915
+ localStorage.removeItem(key);
2916
+ sessionStorage.removeItem(key);
2917
+ });
2918
+ zlog("\u{1F5D1}\uFE0F All Zum data cleared from localStorage");
2919
+ }
2920
+ static getZumStorageKeys() {
2921
+ const keys = [];
2922
+ for (let i = 0; i < localStorage.length; i++) {
2923
+ const key = localStorage.key(i);
2924
+ if (key && (key.includes("Zum") || key === "app-name")) keys.push(key);
2925
+ }
2926
+ return keys;
2927
+ }
2928
+ static inspectZumStorage() {
2929
+ const keys = _Zum.getZumStorageKeys();
2930
+ zlog("\u{1F4E6} Zum data in localStorage:");
2931
+ keys.forEach((key) => {
2932
+ const value = localStorage.getItem(key);
2933
+ zlog(` ${key}:`, value ? value.substring(0, 100) + (value.length > 100 ? "..." : "") : "null");
2934
+ });
2935
+ return keys;
2936
+ }
2937
+ static resetTheme() {
2938
+ localStorage.removeItem(_Zum.themeSettings.persistKey);
2939
+ localStorage.removeItem(_Zum.themeSettings.systemPreferenceKey);
2940
+ const defaultTheme = _Zum.themeSettings.defaultTheme || "light";
2941
+ _Zum.applyTheme(defaultTheme, { manual: false });
2942
+ zlog(`\u{1F504} Theme reset to: ${defaultTheme}`);
2943
+ }
2944
+ static fullReset() {
2945
+ _Zum.clearAllZumData();
2946
+ zlog("\u{1F504} Full reset complete. Reloading...");
2947
+ setTimeout(() => location.reload(), 100);
2948
+ }
2949
+ };
2950
+ __publicField(_Zum, "config", null);
2951
+ __publicField(_Zum, "configPromise", Promise.resolve(null));
2952
+ __publicField(_Zum, "_readyPromise", null);
2953
+ __publicField(_Zum, "_scrollMemory", /* @__PURE__ */ new Map());
2954
+ __publicField(_Zum, "_fetchCache", null);
2955
+ __publicField(_Zum, "_animationsInjected", false);
2956
+ __publicField(_Zum, "_contrastInitialized", false);
2957
+ __publicField(_Zum, "_contrastProcessing", /* @__PURE__ */ new WeakSet());
2958
+ __publicField(_Zum, "_contrastProcessed", /* @__PURE__ */ new WeakSet());
2959
+ __publicField(_Zum, "_debugEnabled", false);
2960
+ __publicField(_Zum, "_debugLog", []);
2961
+ __publicField(_Zum, "_debugLogLimit", 500);
2962
+ __publicField(_Zum, "_debugDedupe", /* @__PURE__ */ new Map());
2963
+ __publicField(_Zum, "_debugPerfMarks", /* @__PURE__ */ new Map());
2964
+ __publicField(_Zum, "_beforeUnloadHandlers", /* @__PURE__ */ new Set());
2965
+ __publicField(_Zum, "_beforeUnloadAttached", false);
2966
+ __publicField(_Zum, "_hasRestored", false);
2967
+ // Global flag to respect reduced motion (set to false to force animations)
2968
+ __publicField(_Zum, "respectReducedMotion", true);
2969
+ // ═══ ANIMATIONS ═══
2970
+ __publicField(_Zum, "animations", {
2971
+ fade: { keyframes: `@keyframes fade { 0% { opacity: 0; } 100% { opacity: 1; } }`, options: { duration: 800, easing: "cubic-bezier(0.25, 0.1, 0.25, 1)" } },
2972
+ slideUp: { keyframes: `@keyframes slideUp { 0% { opacity: 0; transform: translateY(40px); } 100% { opacity: 1; transform: translateY(0); } }`, options: { duration: 800, easing: "cubic-bezier(0.25, 0.1, 0.25, 1)" } },
2973
+ slideDown: { keyframes: `@keyframes slideDown { 0% { opacity: 0; transform: translateY(-40px); } 100% { opacity: 1; transform: translateY(0); } }`, options: { duration: 800, easing: "cubic-bezier(0.25, 0.1, 0.25, 1)" } },
2974
+ slideLeft: { keyframes: `@keyframes slideLeft { 0% { opacity: 0; transform: translateX(40px); } 100% { opacity: 1; transform: translateX(0); } }`, options: { duration: 800, easing: "cubic-bezier(0.25, 0.1, 0.25, 1)" } },
2975
+ slideRight: { keyframes: `@keyframes slideRight { 0% { opacity: 0; transform: translateX(-40px); } 100% { opacity: 1; transform: translateX(0); } }`, options: { duration: 800, easing: "cubic-bezier(0.25, 0.1, 0.25, 1)" } },
2976
+ scale: { keyframes: `@keyframes scale { 0% { opacity: 0; transform: scale(0.9); } 100% { opacity: 1; transform: scale(1); } }`, options: { duration: 800, easing: "cubic-bezier(0.25, 0.1, 0.25, 1)" } },
2977
+ bounce: { keyframes: `@keyframes bounce { 0% { opacity: 0; transform: scale(0.3); } 100% { opacity: 1; transform: scale(1); } }`, options: { duration: 1e3, easing: "cubic-bezier(0.25, 0.1, 0.25, 1)" } },
2978
+ blurIn: { keyframes: `@keyframes blurIn { 0% { opacity: 0; filter: blur(20px); } 100% { opacity: 1; filter: blur(0); } }`, options: { duration: 1e3, easing: "cubic-bezier(0.25, 0.1, 0.25, 1)" } },
2979
+ rotateIn: { keyframes: `@keyframes rotateIn { 0% { opacity: 0; transform: rotate(-8deg); } 100% { opacity: 1; transform: rotate(0); } }`, options: { duration: 1e3, easing: "cubic-bezier(0.25, 0.1, 0.25, 1)" } },
2980
+ flipIn: { keyframes: `@keyframes flipIn { 0% { opacity: 0; transform: perspective(400px) rotateX(-90deg); } 100% { opacity: 1; transform: perspective(400px) rotateX(0); } }`, options: { duration: 700, easing: "ease-out" } },
2981
+ shake: { keyframes: `@keyframes shake { 0%, 100% { transform: translateX(0); } 20% { transform: translateX(-8px); } 40% { transform: translateX(8px); } 60% { transform: translateX(-6px); } 80% { transform: translateX(6px); } }`, options: { duration: 500, easing: "ease-in-out" } },
2982
+ pulse: { keyframes: `@keyframes pulse { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.05); } }`, options: { duration: 1e3, easing: "ease-in-out" } },
2983
+ reveal: { keyframes: `@keyframes reveal { 0% { clip-path: inset(0 100% 0 0); } 100% { clip-path: inset(0 0 0 0); } }`, options: { duration: 800, easing: "cubic-bezier(.2,.8,.2,1)" } }
2984
+ });
2985
+ // ═══ SKELETONS ═══
2986
+ __publicField(_Zum, "SKELETON_TYPES", {
2987
+ DEFAULT: "default",
2988
+ FEED_PAGE: "feed-page",
2989
+ PROFILE_PAGE: "profile-page",
2990
+ CHAT_PAGE: "chat-page",
2991
+ CHAT_DETAIL_PAGE: "chat-detail-page",
2992
+ SERVICE_PAGE: "service-page",
2993
+ DASHBOARD_PAGE: "dashboard-page",
2994
+ SETTINGS_PAGE: "settings-page",
2995
+ SEARCH_PAGE: "search-page",
2996
+ PRODUCT_GRID: "product-grid",
2997
+ NOTIFICATIONS_PAGE: "notifications-page",
2998
+ FORM_PAGE: "form-page"
2999
+ });
3000
+ __publicField(_Zum, "DEFAULT_SKELETON_OPTIONS", {
3001
+ count: 6,
3002
+ customClass: "",
3003
+ colors: { base: "#f5f5f5", highlight: "#e8e8e8" },
3004
+ animationDuration: 1.5
3005
+ });
3006
+ __publicField(_Zum, "REMOVE_SKELETON_OPTIONS", {
3007
+ animate: true,
3008
+ animationType: "fade",
3009
+ duration: 300,
3010
+ delay: 0,
3011
+ callback: null,
3012
+ removeStyles: true,
3013
+ selector: ".skeleton"
3014
+ });
3015
+ // ═══ FETCH ═══
3016
+ __publicField(_Zum, "_differ", {
3017
+ diff(oldData, newData, idKey = "id") {
3018
+ if (!oldData || !newData) return null;
3019
+ const oldMap = new Map(oldData.map((item) => [item[idKey], item]));
3020
+ const newMap = new Map(newData.map((item) => [item[idKey], item]));
3021
+ const result = {
3022
+ added: [],
3023
+ updated: [],
3024
+ deleted: [],
3025
+ unchanged: [],
3026
+ all: [],
3027
+ summary: { added: 0, updated: 0, deleted: 0, unchanged: 0, total: 0, hasChanges: false }
3028
+ };
3029
+ newMap.forEach((newItem, id) => {
3030
+ const oldItem = oldMap.get(id);
3031
+ if (!oldItem) result.added.push({ id, item: { ...newItem, __change: "added" } });
3032
+ else if (JSON.stringify(oldItem) !== JSON.stringify(newItem)) {
3033
+ const changes = {};
3034
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(oldItem), ...Object.keys(newItem)]);
3035
+ allKeys.forEach((key) => {
3036
+ if (key === "__change") return;
3037
+ if (JSON.stringify(oldItem[key]) !== JSON.stringify(newItem[key]))
3038
+ changes[key] = { from: oldItem[key], to: newItem[key] };
3039
+ });
3040
+ result.updated.push({ id, item: { ...newItem, __change: "updated" }, changes });
3041
+ } else {
3042
+ result.unchanged.push({ id, item: { ...newItem, __change: "unchanged" } });
3043
+ }
3044
+ });
3045
+ oldMap.forEach((oldItem, id) => {
3046
+ if (!newMap.has(id)) result.deleted.push({ id, item: { ...oldItem, __change: "deleted" } });
3047
+ });
3048
+ result.all = [
3049
+ ...result.added.map((a) => a.item),
3050
+ ...result.updated.map((u) => u.item),
3051
+ ...result.unchanged.map((u) => u.item),
3052
+ ...result.deleted.map((d) => d.item)
3053
+ ];
3054
+ result.summary = {
3055
+ added: result.added.length,
3056
+ updated: result.updated.length,
3057
+ deleted: result.deleted.length,
3058
+ unchanged: result.unchanged.length,
3059
+ total: result.all.length,
3060
+ hasChanges: result.added.length > 0 || result.updated.length > 0 || result.deleted.length > 0
3061
+ };
3062
+ return result;
3063
+ }
3064
+ });
3065
+ // ═══ THEME SYSTEM ═══
3066
+ __publicField(_Zum, "themeSettings", {
3067
+ defaultTheme: "light",
3068
+ persist: true,
3069
+ persistKey: "Zum_theme_preference",
3070
+ systemPreferenceKey: "Zum_theme_preference_manual",
3071
+ respectSystemPreference: true,
3072
+ smoothTransitions: true,
3073
+ transitionDuration: 400,
3074
+ transitionEasing: "ease-in-out",
3075
+ autoContrast: true,
3076
+ contrastThreshold: 0.5
3077
+ });
3078
+ __publicField(_Zum, "THEMES", {
3079
+ light: {
3080
+ id: "light",
3081
+ name: "Light",
3082
+ colors: {
3083
+ primary: "#3b82f6",
3084
+ secondary: "#8b5cf6",
3085
+ success: "#22c55e",
3086
+ danger: "#ef4444",
3087
+ warning: "#f59e0b",
3088
+ info: "#06b6d4",
3089
+ background: "#ffffff",
3090
+ surface: "#f8fafc",
3091
+ surface2: "#f1f5f9",
3092
+ text: "#0f172a",
3093
+ textSecondary: "#475569",
3094
+ textMuted: "#94a3b8",
3095
+ border: "#e2e8f0",
3096
+ borderLight: "#f1f5f9",
3097
+ shadow: "rgba(0,0,0,0.05)",
3098
+ shadowHover: "rgba(0,0,0,0.1)",
3099
+ gradient: "linear-gradient(135deg, #3b82f6, #8b5cf6)",
3100
+ cardBg: "#ffffff",
3101
+ inputBg: "#ffffff",
3102
+ inputBorder: "#e2e8f0",
3103
+ inputFocus: "#3b82f6",
3104
+ navbarBg: "#ffffff",
3105
+ sidebarBg: "#f8fafc",
3106
+ footerBg: "#f1f5f9",
3107
+ modalBg: "rgba(0,0,0,0.5)",
3108
+ tooltipBg: "#0f172a",
3109
+ tooltipText: "#ffffff",
3110
+ skeletonBase: "#f1f5f9",
3111
+ skeletonHighlight: "#e2e8f0",
3112
+ scrollbarTrack: "#f1f5f9",
3113
+ scrollbarThumb: "#cbd5e1"
3114
+ },
3115
+ typography: { fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', fontFamilyMono: "ui-monospace, monospace", fontSize: "16px", lineHeight: "1.6" },
3116
+ spacing: { xs: "4px", sm: "8px", md: "16px", lg: "24px", xl: "32px", "2xl": "48px" },
3117
+ borderRadius: { sm: "4px", md: "8px", lg: "12px", xl: "16px", full: "9999px" },
3118
+ shadows: { sm: "0 1px 2px rgba(0,0,0,0.05)", md: "0 4px 6px rgba(0,0,0,0.07)", lg: "0 10px 15px rgba(0,0,0,0.1)", xl: "0 20px 25px rgba(0,0,0,0.15)" },
3119
+ transitions: { fast: "150ms ease-in-out", normal: "300ms ease-in-out", slow: "500ms ease-in-out" }
3120
+ },
3121
+ dark: {
3122
+ id: "dark",
3123
+ name: "Dark",
3124
+ colors: {
3125
+ primary: "#60a5fa",
3126
+ secondary: "#a78bfa",
3127
+ success: "#4ade80",
3128
+ danger: "#f87171",
3129
+ warning: "#fbbf24",
3130
+ info: "#22d3ee",
3131
+ background: "#0f172a",
3132
+ surface: "#1e293b",
3133
+ surface2: "#334155",
3134
+ text: "#f1f5f9",
3135
+ textSecondary: "#94a3b8",
3136
+ textMuted: "#64748b",
3137
+ border: "#334155",
3138
+ borderLight: "#1e293b",
3139
+ shadow: "rgba(0,0,0,0.3)",
3140
+ shadowHover: "rgba(0,0,0,0.4)",
3141
+ gradient: "linear-gradient(135deg, #60a5fa, #a78bfa)",
3142
+ cardBg: "#1e293b",
3143
+ inputBg: "#1e293b",
3144
+ inputBorder: "#334155",
3145
+ inputFocus: "#60a5fa",
3146
+ navbarBg: "#0f172a",
3147
+ sidebarBg: "#1e293b",
3148
+ footerBg: "#0f172a",
3149
+ modalBg: "rgba(0,0,0,0.7)",
3150
+ tooltipBg: "#334155",
3151
+ tooltipText: "#f1f5f9",
3152
+ skeletonBase: "#1e293b",
3153
+ skeletonHighlight: "#334155",
3154
+ scrollbarTrack: "#1e293b",
3155
+ scrollbarThumb: "#475569"
3156
+ },
3157
+ typography: { fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', fontFamilyMono: "ui-monospace, monospace", fontSize: "16px", lineHeight: "1.6" },
3158
+ spacing: { xs: "4px", sm: "8px", md: "16px", lg: "24px", xl: "32px", "2xl": "48px" },
3159
+ borderRadius: { sm: "4px", md: "8px", lg: "12px", xl: "16px", full: "9999px" },
3160
+ shadows: { sm: "0 1px 2px rgba(0,0,0,0.3)", md: "0 4px 6px rgba(0,0,0,0.4)", lg: "0 10px 15px rgba(0,0,0,0.5)", xl: "0 20px 25px rgba(0,0,0,0.6)" },
3161
+ transitions: { fast: "150ms ease-in-out", normal: "300ms ease-in-out", slow: "500ms ease-in-out" }
3162
+ },
3163
+ sepia: {
3164
+ id: "sepia",
3165
+ name: "Sepia",
3166
+ colors: {
3167
+ primary: "#8b7d6b",
3168
+ secondary: "#a8907a",
3169
+ success: "#6b8b6b",
3170
+ danger: "#8b6b6b",
3171
+ warning: "#8b7d4b",
3172
+ info: "#6b7d8b",
3173
+ background: "#f5ece0",
3174
+ surface: "#ede4d8",
3175
+ surface2: "#e5dcd0",
3176
+ text: "#3d3529",
3177
+ textSecondary: "#6b6357",
3178
+ textMuted: "#8b8377",
3179
+ border: "#d4c8b8",
3180
+ borderLight: "#e5dcd0",
3181
+ shadow: "rgba(61,53,41,0.08)",
3182
+ shadowHover: "rgba(61,53,41,0.15)",
3183
+ gradient: "linear-gradient(135deg, #8b7d6b, #a8907a)",
3184
+ cardBg: "#ede4d8",
3185
+ inputBg: "#f5ece0",
3186
+ inputBorder: "#d4c8b8",
3187
+ inputFocus: "#8b7d6b",
3188
+ navbarBg: "#ede4d8",
3189
+ sidebarBg: "#e5dcd0",
3190
+ footerBg: "#e5dcd0",
3191
+ modalBg: "rgba(61,53,41,0.6)",
3192
+ tooltipBg: "#3d3529",
3193
+ tooltipText: "#f5ece0",
3194
+ skeletonBase: "#e5dcd0",
3195
+ skeletonHighlight: "#d4c8b8",
3196
+ scrollbarTrack: "#ede4d8",
3197
+ scrollbarThumb: "#c4b8a8"
3198
+ },
3199
+ typography: { fontFamily: 'Georgia, "Times New Roman", serif', fontFamilyMono: "ui-monospace, monospace", fontSize: "17px", lineHeight: "1.7" },
3200
+ spacing: { xs: "4px", sm: "8px", md: "16px", lg: "24px", xl: "32px", "2xl": "48px" },
3201
+ borderRadius: { sm: "3px", md: "6px", lg: "10px", xl: "14px", full: "9999px" },
3202
+ shadows: { sm: "0 1px 2px rgba(61,53,41,0.05)", md: "0 4px 6px rgba(61,53,41,0.07)", lg: "0 10px 15px rgba(61,53,41,0.1)", xl: "0 20px 25px rgba(61,53,41,0.12)" },
3203
+ transitions: { fast: "150ms ease-in-out", normal: "300ms ease-in-out", slow: "500ms ease-in-out" }
3204
+ }
3205
+ });
3206
+ __publicField(_Zum, "_currentTheme", "light");
3207
+ __publicField(_Zum, "_themeObservers", []);
3208
+ __publicField(_Zum, "_themeStylesInjected", false);
3209
+ // ═══ DEBUG ═══
3210
+ __publicField(_Zum, "debug", {
3211
+ enable() {
3212
+ _Zum._debugEnabled = true;
3213
+ return true;
3214
+ },
3215
+ disable() {
3216
+ _Zum._debugEnabled = false;
3217
+ },
3218
+ isEnabled() {
3219
+ return _Zum._debugEnabled;
3220
+ },
3221
+ log(...args) {
3222
+ if (!_Zum._debugEnabled) return;
3223
+ let key;
3224
+ try {
3225
+ key = JSON.stringify(args);
3226
+ } catch (_) {
3227
+ key = String(args);
3228
+ }
3229
+ const now = Date.now();
3230
+ const last = _Zum._debugDedupe.get(key);
3231
+ if (last && now - last < 250) return;
3232
+ _Zum._debugDedupe.set(key, now);
3233
+ console.log("\u{1F41B}", ...args);
3234
+ _Zum._debugLog.push({ ts: now, args });
3235
+ if (_Zum._debugLog.length > _Zum._debugLogLimit) _Zum._debugLog.shift();
3236
+ },
3237
+ getLog() {
3238
+ return _Zum._debugLog.slice();
3239
+ },
3240
+ clearLog() {
3241
+ _Zum._debugLog.length = 0;
3242
+ _Zum._debugDedupe.clear();
3243
+ }
3244
+ });
3245
+ // ═══════════════════════════════════════════════════════
3246
+ // BUILT-IN NAVIGATION & OVERLAYS (ZumActivity)
3247
+ // ═══════════════════════════════════════════════════════
3248
+ __publicField(_Zum, "Activity", {
3249
+ _pages: /* @__PURE__ */ new Map(),
3250
+ _layers: [],
3251
+ _activeLayer: null,
3252
+ _container: null,
3253
+ _cacheTTL: 1e3 * 60 * 60,
3254
+ _started: false,
3255
+ _cleanupInterval: null,
3256
+ _activeOverlays: { sidebar: null, optionMenu: null, toolPick: null, dialog: null },
3257
+ _sweepCache() {
3258
+ if (typeof sessionStorage === "undefined") return;
3259
+ const now = Date.now();
3260
+ for (let i = sessionStorage.length - 1; i >= 0; i--) {
3261
+ const key = sessionStorage.key(i);
3262
+ if (key && key.startsWith("zum-activity-cache:")) {
3263
+ }
3264
+ }
3265
+ },
3266
+ start() {
3267
+ if (this._started || !hasDOM()) return;
3268
+ this._started = true;
3269
+ this._container = document.getElementById("zum-activity-root");
3270
+ if (!this._container) {
3271
+ this._container = document.createElement("div");
3272
+ this._container.id = "zum-activity-root";
3273
+ this._container.style.cssText = "position: relative; width: 100%; height: 100%; overflow: hidden;";
3274
+ document.body.appendChild(this._container);
3275
+ }
3276
+ this._injectBaseStyles();
3277
+ this._cleanupInterval = setInterval(() => this._sweepCache(), 6e4);
3278
+ window.addEventListener("hashchange", () => this._handleHashChange());
3279
+ this._handleHashChange();
3280
+ },
3281
+ stop() {
3282
+ if (!this._started) return;
3283
+ this._started = false;
3284
+ clearInterval(this._cleanupInterval);
3285
+ window.removeEventListener("hashchange", this._handleHashChange);
3286
+ },
3287
+ addLazyPage(path, factory) {
3288
+ this._pages.set(path, { factory, cache: true });
3289
+ },
3290
+ addPage(path, factory) {
3291
+ this._pages.set(path, { factory, cache: false });
3292
+ },
3293
+ navigateTo(path) {
3294
+ if (window.location.hash === `#${path}`) return;
3295
+ window.location.hash = path;
3296
+ },
3297
+ goBack() {
3298
+ window.history.back();
3299
+ },
3300
+ getCurrentPath() {
3301
+ const raw = window.location.hash.replace(/^#/, "") || "/";
3302
+ return raw.length > 1 && raw.startsWith("/") ? raw : raw.startsWith("/") ? raw : "/" + raw;
3303
+ },
3304
+ findTrigger(selector) {
3305
+ if (!selector) return null;
3306
+ return typeof selector === "string" ? document.querySelector(selector) : selector;
3307
+ },
3308
+ _handleHashChange() {
3309
+ if (this._pages.size === 0) return;
3310
+ const path = this.getCurrentPath();
3311
+ const match = this._matchRoute(path);
3312
+ if (!match) {
3313
+ zerr(`ZumActivity: No route found for "${path}"`);
3314
+ return;
3315
+ }
3316
+ const { page, params } = match;
3317
+ if (this._closeTopOverlay()) return;
3318
+ this._renderPage(path, page, params);
3319
+ },
3320
+ _matchRoute(path) {
3321
+ for (const [pattern, config] of this._pages.entries()) {
3322
+ const normalizedPattern = pattern.length > 1 && !pattern.startsWith("/") ? "/" + pattern : pattern;
3323
+ const regex = new RegExp(`^${normalizedPattern.replace(/:[a-zA-Z0-9_]+/g, "([^/]+)")}$`);
3324
+ const match = path.match(regex);
3325
+ if (match) {
3326
+ const params = {};
3327
+ const keys = (pattern.match(/:[a-zA-Z0-9_]+/g) || []).map((k) => k.slice(1));
3328
+ keys.forEach((key, i) => params[key] = decodeURIComponent(match[i + 1]));
3329
+ return { page: config, params };
3330
+ }
3331
+ }
3332
+ return null;
3333
+ },
3334
+ async _renderPage(path, page, params) {
3335
+ const cacheKey = `zum-activity-cache:${path}`;
3336
+ let layer = this._layers.find((l) => l.path === path);
3337
+ if (!layer) {
3338
+ layer = document.createElement("div");
3339
+ layer.className = "activity-page-layer";
3340
+ layer.path = path;
3341
+ layer.style.cssText = "position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow-y: auto; background: var(--Zum-background); z-index: 1; display: none; transition: transform 0.3s ease;";
3342
+ this._container.appendChild(layer);
3343
+ this._layers.push(layer);
3344
+ }
3345
+ if (this._activeLayer) this._activeLayer.style.display = "none";
3346
+ layer.style.display = "block";
3347
+ this._activeLayer = layer;
3348
+ if (!layer.innerHTML.trim()) {
3349
+ let result = sessionStorage.getItem(cacheKey);
3350
+ if (!result || !page.cache) {
3351
+ try {
3352
+ result = await page.factory(params);
3353
+ } catch (e) {
3354
+ zerr("Page factory error:", e);
3355
+ result = `<div class="activity-error">Failed to load page.</div>`;
3356
+ }
3357
+ if (page.cache) {
3358
+ try {
3359
+ const cacheVal = result instanceof HTMLElement ? result.outerHTML : String(result);
3360
+ sessionStorage.setItem(cacheKey, cacheVal);
3361
+ } catch (_) {
3362
+ }
3363
+ }
3364
+ }
3365
+ const inner = document.createElement("div");
3366
+ inner.className = "activity-page-inner";
3367
+ if (result instanceof HTMLElement) inner.appendChild(result);
3368
+ else inner.innerHTML = String(result);
3369
+ layer.appendChild(inner);
3370
+ }
3371
+ },
3372
+ _closeTopOverlay() {
3373
+ for (const [key, el] of Object.entries(this._activeOverlays)) {
3374
+ if (el) {
3375
+ this._closeOverlay(key);
3376
+ return true;
3377
+ }
3378
+ }
3379
+ return false;
3380
+ },
3381
+ _closeOverlay(key) {
3382
+ const el = this._activeOverlays[key];
3383
+ if (el) {
3384
+ el.remove();
3385
+ this._activeOverlays[key] = null;
3386
+ document.body.style.overflow = "";
3387
+ }
3388
+ },
3389
+ _injectBaseStyles() {
3390
+ if (document.getElementById("activity-base-styles")) return;
3391
+ const style = document.createElement("style");
3392
+ style.id = "activity-base-styles";
3393
+ style.textContent = `
3394
+ .activity-page-layer { transition: opacity 0.2s ease, transform 0.2s ease; }
3395
+ .activity-page-inner { max-width: 500px; margin: 0 auto; padding: 16px; width: 100%; box-sizing: border-box; }
3396
+ @media (min-width: 768px) { .activity-page-inner { max-width: 100%; padding: 32px; } }
3397
+ .activity-overlay-backdrop { position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1000; opacity: 0; transition: opacity 0.2s; }
3398
+ .activity-overlay-backdrop.open { opacity: 1; }
3399
+ .activity-sidebar { position: fixed; top: 0; bottom: 0; left: 0; width: 280px; background: var(--Zum-surface, #fff); z-index: 1001; transform: translateX(-100%); transition: transform 0.3s cubic-bezier(0.25, 0.1, 0.25, 1); box-shadow: 4px 0 24px rgba(0,0,0,0.1); display: flex; flex-direction: column; }
3400
+ .activity-sidebar.open { transform: translateX(0); }
3401
+ .activity-dialog-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.6); z-index: 2000; display: flex; align-items: center; justify-content: center; opacity: 0; transition: opacity 0.2s; }
3402
+ .activity-dialog-overlay.open { opacity: 1; }
3403
+ .activity-dialog { background: var(--Zum-surface, #fff); border-radius: 12px; padding: 24px; max-width: 400px; width: 90%; transform: scale(0.95); transition: transform 0.2s; }
3404
+ .activity-dialog-overlay.open .activity-dialog { transform: scale(1); }
3405
+ .activity-option-menu, .activity-tool-pick { position: fixed; background: var(--Zum-surface, #fff); border: 1px solid var(--Zum-border, #ddd); border-radius: 8px; padding: 8px 0; box-shadow: 0 4px 12px rgba(0,0,0,0.15); z-index: 1001; min-width: 160px; opacity: 0; transform: translateY(-8px); transition: all 0.2s; }
3406
+ .activity-option-menu.open, .activity-tool-pick.open { opacity: 1; transform: translateY(0); }
3407
+ .activity-menu-item { padding: 10px 16px; cursor: pointer; font-size: 14px; transition: background 0.15s; }
3408
+ .activity-menu-item:hover { background: var(--Zum-surface-hover, #f1f5f9); }
3409
+ `;
3410
+ document.head.appendChild(style);
3411
+ },
3412
+ openSideBar(triggerSelector, config) {
3413
+ this._closeOverlay("sidebar");
3414
+ const trigger = this.findTrigger(triggerSelector);
3415
+ const backdrop = document.createElement("div");
3416
+ backdrop.className = "activity-overlay-backdrop";
3417
+ const sidebar = document.createElement("div");
3418
+ sidebar.className = "activity-sidebar";
3419
+ sidebar.innerHTML = `
3420
+ <div style="padding: 16px; border-bottom: 1px solid var(--Zum-border); font-weight: bold; font-size: 18px;">${config.title || "Menu"}</div>
3421
+ <div class="activity-sidebar-nav" style="flex: 1; overflow-y: auto; padding: 16px;">
3422
+ ${(config.items || []).map((item) => `<div class="activity-sidebar-item activity-menu-item" data-path="${item.path}">${item.icon || ""} ${item.label}</div>`).join("")}
3423
+ </div>
3424
+ `;
3425
+ document.body.appendChild(backdrop);
3426
+ document.body.appendChild(sidebar);
3427
+ this._activeOverlays.sidebar = { backdrop, sidebar };
3428
+ requestAnimationFrame(() => {
3429
+ backdrop.classList.add("open");
3430
+ sidebar.classList.add("open");
3431
+ });
3432
+ const close = () => this._closeOverlay("sidebar");
3433
+ backdrop.onclick = close;
3434
+ sidebar.querySelectorAll(".activity-sidebar-item").forEach((item) => {
3435
+ item.onclick = () => {
3436
+ const path = item.getAttribute("data-path");
3437
+ close();
3438
+ if (path) this.navigateTo(path);
3439
+ };
3440
+ });
3441
+ },
3442
+ showDialog(config) {
3443
+ this._closeOverlay("dialog");
3444
+ const overlay = document.createElement("div");
3445
+ overlay.className = "activity-dialog-overlay";
3446
+ overlay.innerHTML = `
3447
+ <div class="activity-dialog">
3448
+ <h3 style="margin: 0 0 12px; font-size: 18px;">${config.title || ""}</h3>
3449
+ <p style="margin: 0 0 24px; color: var(--Zum-textSecondary); font-size: 14px;">${config.message || ""}</p>
3450
+ <div style="display: flex; gap: 12px; justify-content: flex-end;">
3451
+ ${(config.buttons || [{ label: "Close", action: "close" }]).map((btn) => `
3452
+ <button class="activity-dialog-btn" data-action="${btn.action}" style="padding: 8px 16px; border-radius: 6px; border: 1px solid var(--Zum-border); background: ${btn.type === "destructive" ? "#ef4444" : "transparent"}; color: ${btn.type === "destructive" ? "#fff" : "inherit"}; cursor: pointer;">
3453
+ ${btn.label}
3454
+ </button>
3455
+ `).join("")}
3456
+ </div>
3457
+ </div>
3458
+ `;
3459
+ document.body.appendChild(overlay);
3460
+ this._activeOverlays.dialog = overlay;
3461
+ requestAnimationFrame(() => overlay.classList.add("open"));
3462
+ overlay.querySelectorAll(".activity-dialog-btn").forEach((btn) => {
3463
+ btn.onclick = () => {
3464
+ const action = btn.getAttribute("data-action");
3465
+ this._closeOverlay("dialog");
3466
+ if (config.onAction) config.onAction(action);
3467
+ };
3468
+ });
3469
+ },
3470
+ showOptionMenu(triggerSelector, config) {
3471
+ this._closeOverlay("optionMenu");
3472
+ const trigger = this.findTrigger(triggerSelector);
3473
+ if (!trigger) return;
3474
+ const menu = document.createElement("div");
3475
+ menu.className = "activity-option-menu";
3476
+ menu.innerHTML = (config.items || []).map((item) => `<div class="activity-menu-item" data-action="${item.action}">${item.label}</div>`).join("");
3477
+ document.body.appendChild(menu);
3478
+ this._activeOverlays.optionMenu = menu;
3479
+ const rect = trigger.getBoundingClientRect();
3480
+ menu.style.top = `${rect.bottom + 8}px`;
3481
+ menu.style.left = `${rect.left}px`;
3482
+ requestAnimationFrame(() => menu.classList.add("open"));
3483
+ menu.querySelectorAll(".activity-menu-item").forEach((el) => {
3484
+ el.onclick = () => {
3485
+ const action = el.getAttribute("data-action");
3486
+ this._closeOverlay("optionMenu");
3487
+ if (config.onAction) config.onAction(action);
3488
+ };
3489
+ });
3490
+ const close = (e) => {
3491
+ if (!menu.contains(e.target) && e.target !== trigger) {
3492
+ this._closeOverlay("optionMenu");
3493
+ document.removeEventListener("click", close);
3494
+ }
3495
+ };
3496
+ setTimeout(() => document.addEventListener("click", close), 0);
3497
+ },
3498
+ showToolPick(triggerSelector, config) {
3499
+ this._closeOverlay("toolPick");
3500
+ const trigger = this.findTrigger(triggerSelector);
3501
+ if (!trigger) return;
3502
+ const picker = document.createElement("div");
3503
+ picker.className = "activity-tool-pick";
3504
+ picker.innerHTML = (config.items || []).map((item) => `<div class="activity-menu-item" data-action="${item.action}">${item.icon || ""} ${item.label}</div>`).join("");
3505
+ document.body.appendChild(picker);
3506
+ this._activeOverlays.toolPick = picker;
3507
+ const rect = trigger.getBoundingClientRect();
3508
+ picker.style.top = `${rect.bottom + 8}px`;
3509
+ picker.style.left = `${rect.right - 160}px`;
3510
+ requestAnimationFrame(() => picker.classList.add("open"));
3511
+ picker.querySelectorAll(".activity-menu-item").forEach((el) => {
3512
+ el.onclick = () => {
3513
+ const action = el.getAttribute("data-action");
3514
+ this._closeOverlay("toolPick");
3515
+ if (config.onAction) config.onAction(action);
3516
+ };
3517
+ });
3518
+ const close = (e) => {
3519
+ if (!picker.contains(e.target) && e.target !== trigger) {
3520
+ this._closeOverlay("toolPick");
3521
+ document.removeEventListener("click", close);
3522
+ }
3523
+ };
3524
+ setTimeout(() => document.addEventListener("click", close), 0);
3525
+ }
3526
+ });
3527
+ var Zum = _Zum;
3528
+ if (hasDOM()) {
3529
+ window.Zum = Zum;
3530
+ window.ZumActivity = Zum.Activity;
3531
+ (function ensureColorScheme() {
3532
+ if (!document.querySelector('meta[name="color-scheme"]')) {
3533
+ const m = document.createElement("meta");
3534
+ m.name = "color-scheme";
3535
+ m.content = "light dark";
3536
+ document.head.appendChild(m);
3537
+ }
3538
+ if (!document.querySelector('meta[name="theme-color"]')) {
3539
+ const l = document.createElement("meta");
3540
+ l.name = "theme-color";
3541
+ l.content = "#ffffff";
3542
+ l.setAttribute("media", "(prefers-color-scheme: light)");
3543
+ document.head.appendChild(l);
3544
+ const d = document.createElement("meta");
3545
+ d.name = "theme-color";
3546
+ d.content = "#0f172a";
3547
+ d.setAttribute("media", "(prefers-color-scheme: dark)");
3548
+ document.head.appendChild(d);
3549
+ }
3550
+ })();
3551
+ if (!window.__ACTIVITY_NO_AUTOSTART__) {
3552
+ queueMicrotask(() => {
3553
+ if (!Zum.Activity._started) {
3554
+ Zum.Activity.start();
3555
+ if (!window.location.hash) {
3556
+ Zum.Activity.navigateTo("/");
3557
+ }
3558
+ }
3559
+ });
3560
+ }
3561
+ try {
3562
+ const autoSwitchEnabled = !window.__ZUM_NO_SYSTEM_THEME__ && Zum.themeSettings.respectSystemPreference !== false;
3563
+ const savedTheme = localStorage.getItem(Zum.themeSettings.persistKey);
3564
+ const savedIsManual = !!localStorage.getItem(Zum.themeSettings.systemPreferenceKey);
3565
+ const systemPrefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
3566
+ let chosenTheme;
3567
+ if (savedTheme && savedIsManual && Zum.THEMES[savedTheme]) {
3568
+ chosenTheme = savedTheme;
3569
+ } else if (autoSwitchEnabled && systemPrefersDark) {
3570
+ chosenTheme = "dark";
3571
+ } else if (autoSwitchEnabled && !systemPrefersDark) {
3572
+ chosenTheme = "light";
3573
+ } else {
3574
+ chosenTheme = Zum.themeSettings.defaultTheme || "light";
3575
+ }
3576
+ Zum._currentTheme = chosenTheme;
3577
+ Zum._injectThemeStyles();
3578
+ Zum.applyTheme(chosenTheme, { manual: savedIsManual && savedTheme === chosenTheme });
3579
+ if (window.matchMedia && autoSwitchEnabled) {
3580
+ const darkQuery = window.matchMedia("(prefers-color-scheme: dark)");
3581
+ const onSystemChange = (e) => {
3582
+ if (localStorage.getItem(Zum.themeSettings.systemPreferenceKey)) return;
3583
+ const newTheme = e.matches ? "dark" : "light";
3584
+ document.querySelectorAll("*").forEach((el) => {
3585
+ el._zumContrastApplied = false;
3586
+ });
3587
+ Zum.applyTheme(newTheme, { manual: false, smooth: true, duration: 400 });
3588
+ setTimeout(() => Zum.refreshContrast(), 500);
3589
+ zlog(`\u{1F504} Auto-switched to ${newTheme} (system preference)`);
3590
+ };
3591
+ if (darkQuery.addEventListener) {
3592
+ darkQuery.addEventListener("change", onSystemChange);
3593
+ } else if (darkQuery.addListener) {
3594
+ darkQuery.addListener(onSystemChange);
3595
+ }
3596
+ }
3597
+ Zum._initAutoContrast();
3598
+ } catch (error) {
3599
+ zwarn("Theme initialization error:", error);
3600
+ Zum._currentTheme = Zum.themeSettings.defaultTheme || "light";
3601
+ Zum.applyTheme(Zum._currentTheme, { manual: false });
3602
+ }
3603
+ if (!document.getElementById("app-global-styles")) {
3604
+ const style = document.createElement("style");
3605
+ style.id = "app-global-styles";
3606
+ style.textContent = `
3607
+ * { margin: 0; padding: 0; box-sizing: border-box; }
3608
+ html, body { width: 100%; min-height: 100%; }
3609
+ body { font-family: Arial, sans-serif; overflow-x: hidden; }
3610
+ `;
3611
+ document.head.appendChild(style);
3612
+ }
3613
+ }
3614
+ var ZumActivity = Zum.Activity;
3615
+ var Zum_default = Zum;