@apigo.cc/state 1.0.18 → 1.0.21

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/README.md CHANGED
@@ -20,15 +20,11 @@
20
20
 
21
21
  指令语法:`$attribute="code"`。作用域默认为全局,组件内优先访问 `node.state`。
22
22
 
23
- ### 结构化映射 (AI 强制规范)
24
- | 指令 | 触发逻辑 | DOM 行为 | 运行约束 |
25
- | :--- | :--- | :--- | :--- |
26
- | **`$if`** | `Boolean(result)` | `true`: 挂载节点; `false`: 移除节点。 | **必须** 作用于 `<template>`。 |
27
- | **`$each`** | `Iterable` | 基于 `key` 属性执行节点复用。无 `key` 时按索引重建。支持 `as`, `index` 定义局部变量。 | **必须** 作用于 `<template>`。 |
28
-
29
- **结构化指令铁律**:
30
- 1. **标签约束**:严禁在非 `<template>` 标签上使用 `$if` 或 `$each`。
31
- 2. **互斥约束**:严禁在同一个 `<template>` 上同时使用 `$if` 和 `$each`。若需组合,必须嵌套(如:`$if` 模版包裹 `$each` 模版)。
23
+ ### 结构化映射
24
+ | 指令 | 触发逻辑 | DOM 行为 |
25
+ | :--- | :--- | :--- |
26
+ | **`$if`** | `Boolean(result)` | `true`: 挂载节点; `false`: 移除节点。建议配合 `<template>`。 |
27
+ | **`$each`** | `Iterable` | 基于 `key` 属性执行节点复用。无 `key` 时按索引重建。支持 `as`, `index` 定义局部变量。 |
32
28
 
33
29
  ### 数据双向绑定 (`$bind`)
34
30
  AI 必须根据不同的元素类型执行以下逻辑:
@@ -41,11 +37,11 @@ AI 必须根据不同的元素类型执行以下逻辑:
41
37
  - **`[contenteditable]`**: 监听 `input`,同步 `innerHTML`。
42
38
  - **`input[type=file]`**: 同步 `files` 对象。
43
39
 
44
- ### 属性与 Property 绑定
40
+ ### 属性操作映射
45
41
  - **`$text`**: 映射至 `textContent`。
46
42
  - **`$html`**: 映射至 `innerHTML`。
47
43
  - **`$class`**: **严格要求使用模板字符串**。范式:`class="static-name ${condition ? 'dynamic-name' : ''}"`。严禁覆盖原有类名。
48
- - **`$.path.to.prop`**: 直接映射至 DOM 对象或组件的 Property。初始化 Property 绑定必须带 `.` 前缀。
44
+ - **`.path.to.prop`**: 直接映射至 DOM 对象原生属性。例如:`.style.color="'red'"` 映射为 `el.style.color = 'red'`。
49
45
  - **`$src`**: 增强逻辑。若值以 `.svg` 结尾,异步 Fetch 并替换为内联 `<svg>` 节点。
50
46
  - **`$$attr`**: 二级求值。`eval(eval(expr))` 逻辑,用于动态生成指令代码。
51
47
 
@@ -53,11 +49,11 @@ AI 必须根据不同的元素类型执行以下逻辑:
53
49
 
54
50
  ## 3. 生命周期与事件逻辑
55
51
 
56
- - **`$on[event]`**: 映射为 `addEventListener`。注入 `event`, `thisNode`, `State`, `LocalStorage`, `Hash`。
52
+ - **`$on[event]`**: 映射为 `addEventListener`。注入 `event`, `thisNode`, `this`。
57
53
  - **生命周期**:
58
- - **`$onload`**: 节点进入 DOM 且指令解析完成后触发。
59
- - **`$onunload`**: 节点从 DOM 移除前触发。
60
- - **`$onupdate`**: 绑定的数据变更且渲染任务完成后执行。
54
+ - **`$onload`**: `DOMNodeInserted` 且指令解析完成后触发。
55
+ - **`$onunload`**: `DOMNodeRemoved` 前触发,必须用于清理定时器或外部监听。
56
+ - **`$onupdate`**: 属性 setter 触发且渲染微任务完成后执行。
61
57
 
62
58
  ---
63
59
 
package/dist/state.js CHANGED
@@ -1,8 +1,72 @@
1
1
  (function(global, factory) {
2
- typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.ApigoState = {}));
2
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.ApigoState = global.ApigoState || {}));
3
3
  })(this, function(exports2) {
4
4
  "use strict";
5
- var _a;
5
+ var _a, _b;
6
+ const Util = {
7
+ clone: (obj) => JSON.parse(JSON.stringify(obj)),
8
+ base64: (str) => btoa(String.fromCharCode(...new TextEncoder().encode(str))),
9
+ unbase64: (str) => new TextDecoder().decode(Uint8Array.from(atob(str), (c) => c.charCodeAt(0))),
10
+ urlbase64: (str) => Util.base64(str).replace(/[+/=]/g, (m) => ({ "+": "-", "/": "", "=": "" })[m]),
11
+ unurlbase64: (str) => Util.unbase64(str.replace(/[-_.]/g, (m) => ({ "-": "+", "_": "/", ".": "=" })[m]).padEnd(Math.ceil(str.length / 4) * 4, "=")),
12
+ safeJson: (str) => {
13
+ try {
14
+ return JSON.parse(str);
15
+ } catch {
16
+ return null;
17
+ }
18
+ },
19
+ updateDefaults: (obj, defaults) => {
20
+ for (const k in defaults) if (obj[k] === void 0) obj[k] = defaults[k];
21
+ },
22
+ copyFunction: (toObj, fromObj, ...funcNames) => {
23
+ funcNames.forEach((name) => toObj[name] = fromObj[name].bind(fromObj));
24
+ },
25
+ getFunctionBody: (fn) => {
26
+ const code = fn.toString();
27
+ return code.slice(code.indexOf("{") + 1, code.lastIndexOf("}")).trim();
28
+ },
29
+ makeDom: (html) => {
30
+ if (html.includes(">\n")) html = html.replace(/>\s+</g, "><").trim();
31
+ const node = document.createElement("div");
32
+ node.innerHTML = html;
33
+ return node.children[0];
34
+ },
35
+ newAvg: () => {
36
+ let total = 0, count = 0, avg = 0;
37
+ return {
38
+ add: (v) => {
39
+ total += v;
40
+ count++;
41
+ return avg = total / count;
42
+ },
43
+ get: () => avg,
44
+ clear: () => {
45
+ total = 0, count = 0, avg = 0;
46
+ }
47
+ };
48
+ },
49
+ newTimeCount: () => {
50
+ let startTime = 0, total = 0, count = 0;
51
+ return {
52
+ start: () => startTime = (/* @__PURE__ */ new Date()).getTime(),
53
+ end: () => {
54
+ const endTime = (/* @__PURE__ */ new Date()).getTime();
55
+ const left = endTime - startTime;
56
+ startTime = endTime;
57
+ total += left;
58
+ count++;
59
+ return left;
60
+ },
61
+ avg: () => total / count
62
+ };
63
+ }
64
+ };
65
+ const $ = (a, b) => b ? a.querySelector(b) : document.querySelector(a);
66
+ const $$ = (a, b) => b ? a.querySelectorAll(b) : document.querySelectorAll(a);
67
+ globalThis.Util = Util;
68
+ globalThis.$ = $;
69
+ globalThis.$$ = $$;
6
70
  let __activeBinding = null;
7
71
  let __noWriteBack = null;
8
72
  const _setActiveBinding = (val) => __activeBinding = val;
@@ -70,14 +134,67 @@
70
134
  }
71
135
  });
72
136
  }
73
- const $ = (a, b) => b ? a.querySelector(b) : document.querySelector(a);
74
- const $$ = (a, b) => b ? a.querySelectorAll(b) : document.querySelectorAll(a);
137
+ globalThis.NewState = NewState;
138
+ let _hashParams = new URLSearchParams(typeof globalThis !== "undefined" ? ((_b = (_a = globalThis.location) == null ? void 0 : _a.hash) == null ? void 0 : _b.substring(1)) || "" : "");
139
+ const Hash = NewState({}, (k) => Util.safeJson(_hashParams.get(k)), (k, v) => {
140
+ const oldStr = _hashParams.get(k);
141
+ const newStr = v === void 0 ? void 0 : JSON.stringify(v);
142
+ if (oldStr === newStr || oldStr === null && newStr === void 0) return;
143
+ v === void 0 ? _hashParams.delete(k) : _hashParams.set(k, newStr);
144
+ globalThis.location.hash = "#" + _hashParams.toString();
145
+ });
146
+ if (typeof globalThis !== "undefined") {
147
+ globalThis.addEventListener("hashchange", () => {
148
+ var _a2;
149
+ const newParams = new URLSearchParams(((_a2 = globalThis.location.hash) == null ? void 0 : _a2.substring(1)) || "");
150
+ const keys = /* @__PURE__ */ new Set([..._hashParams.keys(), ...newParams.keys()]);
151
+ _hashParams = newParams;
152
+ keys.forEach((k) => Hash[k] = Hash[k]);
153
+ });
154
+ }
155
+ const LocalStorage = NewState({}, (k) => Util.safeJson(localStorage.getItem(k)), (k, v) => {
156
+ const oldStr = localStorage.getItem(k);
157
+ const newStr = v === void 0 ? void 0 : JSON.stringify(v);
158
+ if (oldStr === newStr || oldStr === null && newStr === void 0) return;
159
+ v === void 0 ? localStorage.removeItem(k) : localStorage.setItem(k, newStr);
160
+ });
161
+ const State = NewState({
162
+ exitBlocks: 0
163
+ });
164
+ globalThis.Hash = Hash;
165
+ globalThis.LocalStorage = LocalStorage;
166
+ globalThis.State = State;
167
+ let _disableRunCodeError = false;
168
+ const setDisableRunCodeError = (value) => {
169
+ _disableRunCodeError = value;
170
+ };
171
+ const _fnCache = /* @__PURE__ */ new Map();
172
+ function _runCode(code, vars, thisObj, extendVars) {
173
+ const allVars = { ...extendVars || {}, ...vars || {} };
174
+ const argKeys = Object.keys(allVars);
175
+ const argValues = Object.values(allVars);
176
+ const cacheKey = code + argKeys.join(",");
177
+ try {
178
+ let fn = _fnCache.get(cacheKey);
179
+ if (!fn) {
180
+ fn = new Function("Hash", "LocalStorage", "State", ...argKeys, code);
181
+ _fnCache.set(cacheKey, fn);
182
+ }
183
+ return fn.apply(thisObj, [globalThis.Hash, globalThis.LocalStorage, globalThis.State, ...argValues]);
184
+ } catch (e) {
185
+ if (!_disableRunCodeError) console.error(e, extendVars, [code, extendVars, vars, thisObj]);
186
+ return null;
187
+ }
188
+ }
189
+ function _returnCode(code, vars, thisObj, extendVars) {
190
+ if (code.includes("${")) return _runCode("return `" + code + "`", vars, thisObj, extendVars);
191
+ else return _runCode("return " + code, vars, thisObj, extendVars);
192
+ }
75
193
  const _components = /* @__PURE__ */ new Map();
76
194
  const _pendingTemplates = [];
77
195
  const Component = {
78
196
  getTemplate: (name) => document.querySelector(`template[component="${name.toUpperCase()}"]`),
79
197
  register: (name, setupFunc, templateNode = null, ...globalNodes) => {
80
- console.log("Component.register:", name.toUpperCase());
81
198
  _components.set(name.toUpperCase(), setupFunc);
82
199
  if (document.readyState !== "loading") Component._addTemplate(name, templateNode, globalNodes);
83
200
  else _pendingTemplates.push([name, templateNode, globalNodes]);
@@ -154,32 +271,6 @@
154
271
  }
155
272
  if (componentFunc) componentFunc(node);
156
273
  }
157
- let _disableRunCodeError = false;
158
- function setDisableRunCodeError(value) {
159
- _disableRunCodeError = value;
160
- }
161
- const _fnCache = /* @__PURE__ */ new Map();
162
- function _runCode(code, vars, thisObj, extendVars) {
163
- const allVars = { ...extendVars || {}, ...vars || {} };
164
- const argKeys = Object.keys(allVars);
165
- const argValues = Object.values(allVars);
166
- const cacheKey = code + argKeys.join(",");
167
- try {
168
- let fn = _fnCache.get(cacheKey);
169
- if (!fn) {
170
- fn = new Function("Hash", "LocalStorage", "State", ...argKeys, code);
171
- _fnCache.set(cacheKey, fn);
172
- }
173
- return fn.apply(thisObj, [globalThis.Hash, globalThis.LocalStorage, globalThis.State, ...argValues]);
174
- } catch (e) {
175
- if (!_disableRunCodeError) console.error(e, extendVars, [code, extendVars, vars, thisObj]);
176
- return null;
177
- }
178
- }
179
- function _returnCode(code, vars, thisObj, extendVars) {
180
- if (code.includes("${")) return _runCode("return `" + code + "`", vars, thisObj, extendVars);
181
- else return _runCode("return " + code, vars, thisObj, extendVars);
182
- }
183
274
  let _translator = (text, args) => {
184
275
  if (!text || typeof text !== "string") return text;
185
276
  return text.replace(/\{(.+?)\}/g, (match, key) => args.hasOwnProperty(key) ? args[key] : match);
@@ -294,6 +385,7 @@
294
385
  if (existingNodes) {
295
386
  node._keyedNodes.delete(keyVal);
296
387
  existingNodes.forEach((child) => {
388
+ node.parentNode.insertBefore(child, node);
297
389
  child._ref[indexName] = k;
298
390
  child._ref[asName] = item;
299
391
  _scanTree(child);
@@ -354,12 +446,12 @@
354
446
  }
355
447
  }
356
448
  }
357
- const _initBinding = (binding) => {
449
+ function _initBinding(binding) {
358
450
  if (!binding.node._bindings) binding.node._bindings = [];
359
451
  binding.node._bindings.push({ attr: binding.attr, prop: binding.prop, tpl: binding.tpl, exp: binding.exp });
360
452
  _updateBinding(binding);
361
- };
362
- const _parseNode = (node, scanObj) => {
453
+ }
454
+ function _parseNode(node, scanObj) {
363
455
  if (node._bindings) {
364
456
  node._states = /* @__PURE__ */ new Set();
365
457
  node._bindings.forEach((b) => _updateBinding({ node, ...b }));
@@ -372,7 +464,7 @@
372
464
  if (attr.name.startsWith("$.")) {
373
465
  const realAttrName = attr.name.slice(2);
374
466
  let tpl = _translate(attr.value);
375
- if (tpl.includes("this.")) tpl = tpl.replace(/\bthis\./g, "this.parent.");
467
+ if (scanObj.thisObj && tpl.includes("this.")) tpl = tpl.replace(/\bthis\./g, "this.parent.");
376
468
  const result = _returnCode(tpl, { thisNode: node }, { parent: scanObj.thisObj || node }, node._ref || {});
377
469
  let o = node;
378
470
  const prop = realAttrName.split(".");
@@ -398,7 +490,7 @@
398
490
  } else {
399
491
  attrs = Array.from(node.attributes).filter((a) => (a.name.startsWith("$") || a.name.startsWith("st-")) && !["$if", "$each", "st-if", "st-each"].includes(a.name) || a.name.includes("."));
400
492
  }
401
- if (node._thisObj && scanObj.thisObj) node._thisObj.parent = scanObj.thisObj;
493
+ if (node._thisObj && scanObj.thisObj && node._thisObj !== scanObj.thisObj) node._thisObj.parent = scanObj.thisObj;
402
494
  if (!node._thisObj) node._thisObj = scanObj.thisObj || null;
403
495
  if (!node._ref) node._ref = scanObj.extendVars || {};
404
496
  node._states = /* @__PURE__ */ new Set();
@@ -418,7 +510,8 @@
418
510
  node.addEventListener(eventName, (e) => _runCode(tpl, { event: e, thisNode: node, ...e.detail || {} }, scanObj.thisObj || node, node._ref || {}));
419
511
  } else {
420
512
  if (realAttrName === "bind") {
421
- node.addEventListener(["textarea", "text", "password"].includes(node.type || "text") || node.isContentEditable ? "input" : "change", (e) => {
513
+ const isTextInput = ["INPUT", "TEXTAREA"].includes(node.tagName) && ["textarea", "text", "password", "email", "number", "search", "url", "tel"].includes(node.type || "text") || node.isContentEditable;
514
+ node.addEventListener(isTextInput ? "input" : "change", (e) => {
422
515
  let newVal = node.isContentEditable ? e.target.innerHTML : node.type === "checkbox" ? e.target.checked : e.target.files || e.target.value || e.detail;
423
516
  _setNoWriteBack(node);
424
517
  setDisableRunCodeError(true);
@@ -440,7 +533,7 @@
440
533
  if (node._hasOnLoad || node._componentInitialized) Promise.resolve().then(() => node.dispatchEvent(new Event("load", { bubbles: false })));
441
534
  if (node._hasOnUpdate) node.dispatchEvent(new Event("update", { bubbles: false }));
442
535
  if (node._thisObj) scanObj.thisObj = node._thisObj;
443
- };
536
+ }
444
537
  const _scanTree = (node, scanObj = {}) => {
445
538
  if (node.nodeType === 3) {
446
539
  if (node._stTranslated) return;
@@ -469,6 +562,7 @@
469
562
  node.parentNode.insertBefore(template, node);
470
563
  template.content.appendChild(node);
471
564
  template._ref = node._ref;
565
+ _scanTree(template, scanObj);
472
566
  return;
473
567
  }
474
568
  if (node.tagName === "TEMPLATE" && (node.hasAttribute("$if") || node.hasAttribute("st-if")) && (node.hasAttribute("$each") || node.hasAttribute("st-each"))) {
@@ -528,118 +622,14 @@
528
622
  });
529
623
  node.childNodes && node.childNodes.forEach((child) => _unbindTree(child));
530
624
  };
531
- const _unsafeRefreshState = _scanTree;
532
- const Util = {
533
- clone: window.structuredClone || ((obj) => JSON.parse(JSON.stringify(obj))),
534
- base64: (str) => btoa(String.fromCharCode(...new TextEncoder().encode(str))),
535
- unbase64: (str) => new TextDecoder().decode(Uint8Array.from(atob(str), (c) => c.charCodeAt(0))),
536
- urlbase64: (str) => Util.base64(str).replace(/[+/=]/g, (m) => ({ "+": "-", "/": "", "=": "" })[m]),
537
- unurlbase64: (str) => Util.unbase64(str.replace(/[-_.]/g, (m) => ({ "-": "+", "_": "/", ".": "=" })[m]).padEnd(Math.ceil(str.length / 4) * 4, "=")),
538
- safeJson: (str) => {
539
- try {
540
- return JSON.parse(str);
541
- } catch {
542
- return null;
543
- }
544
- },
545
- updateDefaults: (obj, defaults) => {
546
- for (const k in defaults) if (obj[k] === void 0) obj[k] = defaults[k];
547
- },
548
- copyFunction: (toObj, fromObj, ...funcNames) => {
549
- funcNames.forEach((name) => toObj[name] = fromObj[name].bind(fromObj));
550
- },
551
- getFunctionBody: (fn) => {
552
- const code = fn.toString();
553
- return code.slice(code.indexOf("{") + 1, code.lastIndexOf("}")).trim();
554
- },
555
- makeDom: (html) => {
556
- if (html.includes(">\n")) html = html.replace(/>\s+</g, "><").trim();
557
- const node = document.createElement("div");
558
- node.innerHTML = html;
559
- return node.children[0];
560
- },
561
- newAvg: () => {
562
- let total = 0, count = 0, avg = 0;
563
- return {
564
- add: (v) => {
565
- total += v;
566
- count++;
567
- return avg = total / count;
568
- },
569
- get: () => avg,
570
- clear: () => {
571
- total = 0, count = 0, avg = 0;
572
- }
573
- };
574
- },
575
- newTimeCount: () => {
576
- let startTime = 0, total = 0, count = 0;
577
- return {
578
- start: () => startTime = (/* @__PURE__ */ new Date()).getTime(),
579
- end: () => {
580
- const endTime = (/* @__PURE__ */ new Date()).getTime();
581
- const left = endTime - startTime;
582
- startTime = endTime;
583
- total += left;
584
- count++;
585
- return left;
586
- },
587
- avg: () => total / count
588
- };
589
- }
590
- };
591
- globalThis.Util = Util;
592
- let _hashParams = new URLSearchParams(((_a = window.location.hash) == null ? void 0 : _a.substring(1)) || "");
593
- const Hash = NewState({}, (k) => Util.safeJson(_hashParams.get(k)), (k, v) => {
594
- const oldStr = _hashParams.get(k);
595
- const newStr = v === void 0 ? void 0 : JSON.stringify(v);
596
- if (oldStr === newStr || oldStr === null && newStr === void 0) return;
597
- v === void 0 ? _hashParams.delete(k) : _hashParams.set(k, newStr);
598
- window.location.hash = "#" + _hashParams.toString();
599
- });
600
- if (typeof window !== "undefined") {
601
- window.addEventListener("hashchange", () => {
602
- var _a2;
603
- const newParams = new URLSearchParams(((_a2 = window.location.hash) == null ? void 0 : _a2.substring(1)) || "");
604
- const keys = /* @__PURE__ */ new Set([..._hashParams.keys(), ...newParams.keys()]);
605
- _hashParams = newParams;
606
- keys.forEach((k) => Hash[k] = Hash[k]);
607
- });
608
- }
609
- const LocalStorage = NewState({}, (k) => Util.safeJson(localStorage.getItem(k)), (k, v) => {
610
- const oldStr = localStorage.getItem(k);
611
- const newStr = v === void 0 ? void 0 : JSON.stringify(v);
612
- if (oldStr === newStr || oldStr === null && newStr === void 0) return;
613
- v === void 0 ? localStorage.removeItem(k) : localStorage.setItem(k, newStr);
614
- });
615
- const State = NewState({
616
- exitBlocks: 0
617
- });
618
- globalThis.Hash = Hash;
619
- globalThis.LocalStorage = LocalStorage;
620
- globalThis.State = State;
621
- const ApigoState = {
622
- NewState,
623
- Component,
624
- $,
625
- $$,
626
- RefreshState: _unsafeRefreshState,
627
- SetTranslator,
628
- _scanTree,
629
- _unbindTree,
630
- Util,
631
- Hash,
632
- LocalStorage,
633
- State
634
- };
635
- globalThis.$ = $;
636
- globalThis.$$ = $$;
637
- if (typeof window !== "undefined") {
638
- window.ApigoState = ApigoState;
639
- }
625
+ globalThis.Component = Component;
626
+ globalThis.SetTranslator = SetTranslator;
627
+ globalThis.__unsafeRefreshState = _scanTree;
640
628
  if (typeof document !== "undefined") {
641
629
  const init = () => {
642
- Component._initPending();
630
+ if (globalThis.Component && globalThis.Component._initPending) {
631
+ globalThis.Component._initPending();
632
+ }
643
633
  const htmlNode = document.documentElement;
644
634
  if (!htmlNode.hasAttribute("$data-bs-theme") && !htmlNode.hasAttribute("data-bs-theme")) {
645
635
  htmlNode.setAttribute("$data-bs-theme", "LocalStorage.darkMode?'dark':'light'");
@@ -657,17 +647,16 @@
657
647
  if (document.readyState !== "loading") init();
658
648
  else document.addEventListener("DOMContentLoaded", init, true);
659
649
  }
650
+ const __unsafeRefreshState = _scanTree;
660
651
  exports2.$ = $;
661
652
  exports2.$$ = $$;
662
653
  exports2.Component = Component;
663
654
  exports2.Hash = Hash;
664
655
  exports2.LocalStorage = LocalStorage;
665
656
  exports2.NewState = NewState;
666
- exports2.RefreshState = _unsafeRefreshState;
667
657
  exports2.SetTranslator = SetTranslator;
668
658
  exports2.State = State;
669
659
  exports2.Util = Util;
670
- exports2._scanTree = _scanTree;
671
- exports2._unbindTree = _unbindTree;
660
+ exports2.__unsafeRefreshState = __unsafeRefreshState;
672
661
  Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
673
662
  });
package/dist/state.min.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ApigoState={})}(this,function(e){"use strict";var t;let n=null,a=null;const s=e=>n=e,r=e=>a=e,o=new Set;function i(e={},t=null,s=null){const r={},i=new Map,l=new Map,d=(e,t)=>(l.has(e)||l.set(e,new Set),t?l.get(e).add(t):l.get(e).clear(),()=>l.get(e).delete(t)),c=(e,t)=>{l.has(e)&&l.set(e,new Set),l.get(e).delete(t)},h=t||(e=>r[e]),u=s||((e,t)=>r[e]=t);return Object.assign(r,e),new Proxy(r,{get:(e,t)=>"__watch"===t?d:"__unwatch"===t?c:"__isProxy"===t||(n&&(i.has(t)||i.set(t,new Set),i.get(t).add(n),n.node._states||(n.node._states=new Set),n.node._states.add(i)),h(t)),set(e,t,n){if(h(t)!==n&&u(t,n),l.has(t)&&l.get(t).forEach(a=>{const s=a(n);void 0!==s&&(n=s,e[t]=n)}),l.has(null)&&l.get(null).forEach(e=>e(n)),i.has(t)){const e=i.get(t);for(const t of e)t.node.isConnected?a!==t.node&&o.forEach(e=>e(t)):e.delete(t)}return!0}})}const l=(e,t)=>t?e.querySelector(t):document.querySelector(e),d=(e,t)=>t?e.querySelectorAll(t):document.querySelectorAll(e),c=new Map,h=[],u={getTemplate:e=>document.querySelector(`template[component="${e.toUpperCase()}"]`),register:(e,t,n=null,...a)=>{console.log("Component.register:",e.toUpperCase()),c.set(e.toUpperCase(),t),"loading"!==document.readyState?u._addTemplate(e,n,a):h.push([e,n,a])},exists:e=>c.has(e.toUpperCase()),getSetupFunction:e=>c.get(e.toUpperCase()),_addTemplate:(e,t,n)=>{if(t){const n=document.createElement("TEMPLATE");n.setAttribute("component",e.toUpperCase()),n.content.appendChild(t),document.body.appendChild(n)}n&&n.forEach(e=>document.body.appendChild(e))},_initPending:()=>{h.forEach(([e,t,n])=>u._addTemplate(e,t,n)),h.length=0}};function f(e,t,n,a={}){e.attributes&&Array.from(e.attributes).forEach(e=>{"class"!==e.name&&("style"===e.name?t.hasAttribute("style")?t.setAttribute("style",`${e.value}; ${t.getAttribute("style")}`):t.setAttribute("style",e.value):t.hasAttribute(e.name)||t.setAttribute(e.name,e.value))}),t.classList.add(...e.classList);const s="TEMPLATE"===t.tagName?t.content:t,r="TEMPLATE"===e.tagName?e.content.childNodes:e.childNodes;Array.from(r).forEach(e=>s.appendChild(e)),e.tagName&&u.exists(e.tagName)&&b(e.tagName,t,n,a)}function b(e,t,n,a={}){if(a[e])return;a[e]=!0,n.thisObj&&Array.from(t.attributes).forEach(e=>{(e.name.startsWith("$")||e.name.startsWith("st-"))&&e.value.includes("this.")&&(e.value=e.value.replace(/\bthis\./g,"this.parent."))});const s=u.getSetupFunction(e),r={};Array.from(t.childNodes).forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&e.hasAttribute("slot")&&(r[e.getAttribute("slot")]=e,e.removeAttribute("slot"))}),t.innerHTML="",t.state=i(t.state||{});const o=u.getTemplate(e);if(o){const e=o.content.cloneNode(!0);if(e.childNodes.length){const s=e.children[0];s&&f(s,t,n,a),d(t,"[slot-id]").forEach(e=>{const t=e.getAttribute("slot-id");r[t]&&(e.removeAttribute("slot-id"),e.innerHTML="",f(r[t],e,n,a))})}}s&&s(t)}let m=!1;function p(e){m=e}const g=new Map;function _(e,t,n,a){const s={...a||{},...t||{}},r=Object.keys(s),o=Object.values(s),i=e+r.join(",");try{let t=g.get(i);return t||(t=new Function("Hash","LocalStorage","State",...r,e),g.set(i,t)),t.apply(n,[globalThis.Hash,globalThis.LocalStorage,globalThis.State,...o])}catch(s){return m||console.error(s,a,[e,a,t,n]),null}}function y(e,t,n,a){return e.includes("${")?_("return `"+e+"`",t,n,a):_("return "+e,t,n,a)}let A=(e,t)=>e&&"string"==typeof e?e.replace(/\{(.+?)\}/g,(e,n)=>t.hasOwnProperty(n)?t[n]:e):e;const v=e=>A=e,E=e=>e&&"string"==typeof e&&e.includes("{#")?e.replace(/\{#(.+?)#\}/g,(e,t)=>{const n=t.split("||").map(e=>e.trim()),a={};if(n.length>1){const e=n[0].match(/\{(.+?)\}/g);e&&e.forEach((e,t)=>a[e.substring(1,e.length-1)]=n[t+1]||"")}return A(n[0],a)}):e;if("undefined"!=typeof document)try{document.createElement("div").setAttribute("$t","1")}catch(e){const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(e,n){return e.startsWith("$")?t.call(this,"st-"+e.substring(1),n):t.call(this,e,n)}}var N;function T(e){e._renderedNodes&&e._renderedNodes.forEach(e=>e.forEach(e=>{e.remove(),e._renderedNodes&&T(e)}))}function O(e){const t=e.node;if(!t.isConnected&&"TEMPLATE"!==t.tagName)return;s(e);let n=e.exp?e.tpl?y(e.tpl,{thisNode:t},t._thisObj||t,t._ref||null):null:e.tpl;if(2===e.exp&&"string"==typeof n)try{n=y(n,{thisNode:t},t._thisObj||t,t._ref||null)}catch(e){}if(s(null),e.prop){const a=e.prop;let s=t;for(let e=0;e<a.length-1&&(!a[e]||(null==s[a[e]]&&(s[a[e]]={}),s=s[a[e]],"object"==typeof s));e++);if("object"==typeof s&&null!==s){const e=a[a.length-1];if(e){"object"!=typeof n||null==n||Array.isArray(n)||null!=s[e]||(s[e]={});const t=s[e];"object"==typeof t&&null!=t&&t.__watch?Object.assign(t,n):s[e]!==n&&(s[e]=n)}else"object"!=typeof n||null==n||Array.isArray(n)||Object.assign(s,n)}}else if(e.attr){const a=e.attr;if("if"===a)n?t._renderedNodes&&0!==t._renderedNodes.length||(t._children.forEach(e=>{t.parentNode.insertBefore(e,t),e._ref={...t._ref},e._thisObj=t._thisObj}),t._renderedNodes=[t._children]):(T(t),t._renderedNodes=[]);else if("each"===a)if(n&&"object"==typeof n){const e=t.getAttribute("as")||"item",a=t.getAttribute("index")||"index",s=t.getAttribute("key");let r,o;if(n instanceof Map)r=Array.from(n.keys()),o=e=>n.get(e);else if("function"==typeof n[Symbol.iterator]){const e=Array.isArray(n)?n:Array.from(n);r=new Array(e.length);for(let t=0;t<e.length;t++)r[t]=t;o=t=>e[t]}else r=Object.keys(n),o=e=>n[e];t._keyedNodes||(t._keyedNodes=new Map);const i=new Map,l=[];r.forEach((n,r)=>{const d=o(n),c=s?d&&"object"==typeof d?d[s]:d:n,h=null==c||i.has(c)?`st_key_${r}`:c;let u=t._keyedNodes.get(h);u?(t._keyedNodes.delete(h),u.forEach(t=>{t._ref[a]=n,t._ref[e]=d,w(t)})):(u=[],t._children.forEach(s=>{const r=s.cloneNode(!0);r._ref={...t._ref,[a]:n,[e]:d},r._thisObj=t._thisObj,t.parentNode.insertBefore(r,t),u.push(r)})),i.set(h,u),l.push(u)}),t._keyedNodes.forEach(e=>e.forEach(e=>{T(e),e.remove()})),t._keyedNodes=i,t._renderedNodes=l}else T(t),t._renderedNodes=[];else if("bind"===a){if(["INPUT","SELECT","TEXTAREA"].includes(t.tagName)&&!t.hasAttribute("autocomplete")&&t.setAttribute("autocomplete","off"),"checkbox"===t.type){"on"===t.value||n||(_(`${e.tpl} = []`,{thisNode:t},t._thisObj||t,t._ref||{}),n=[]),t._checkboxMultiMode=n instanceof Array;const a=n instanceof Array?n.includes(t.value):!!n;t.checked!==a&&(t.checked=a)}else"radio"===t.type?t.checked!==(t.value===String(n??""))&&(t.checked=t.value===String(n??"")):"value"in t&&"file"!==t.type?Promise.resolve().then(()=>{t.value!==String(n??"")&&(t.value=n)}):t.isContentEditable&&t.innerHTML!==String(n??"")&&(t.innerHTML=n);t.dispatchEvent(new CustomEvent("bind",{bubbles:!1,detail:n}))}else["checked","disabled","readonly"].includes(a)&&(n=!!n),"boolean"==typeof n?n?t.setAttribute(a,""):t.removeAttribute(a):void 0!==n&&("string"!=typeof n&&(n=JSON.stringify(n)),"text"===a?t.textContent=n??"":"html"===a?t.innerHTML=n??"":"IMG"===t.tagName&&"src"===a&&n.includes(".svg")?t.setAttribute("_src",n??""):t.setAttribute(a,n??""))}}N=e=>O(e),o.add(N);const S=e=>{e.node._bindings||(e.node._bindings=[]),e.node._bindings.push({attr:e.attr,prop:e.prop,tpl:e.tpl,exp:e.exp}),O(e)},w=(e,t={})=>{if(3===e.nodeType){if(e._stTranslated)return;const t=E(e.textContent);return t!==e.textContent&&(e.textContent=t),void(e._stTranslated=!0)}if(1!==e.nodeType)return;if(e._stTranslated||(Array.from(e.attributes).forEach(e=>{if(!e.name.startsWith("$")&&!e.name.startsWith("st-")&&!e.name.startsWith(".")){const t=E(e.value);t!==e.value&&(e.value=t)}}),e._stTranslated=!0),"TEMPLATE"!==e.tagName&&(e.hasAttribute("$if")||e.hasAttribute("$each")||e.hasAttribute("st-if")||e.hasAttribute("st-each"))){const t=document.createElement("TEMPLATE");return Array.from(e.attributes).filter(t=>["$if","$each","st-if","st-each"].includes(t.name)||(e.hasAttribute("$each")||e.hasAttribute("st-each"))&&["as","index"].includes(t.name)).forEach(n=>{t.setAttribute(n.name,n.value),e.removeAttribute(n.name)}),e.parentNode.insertBefore(t,e),t.content.appendChild(e),void(t._ref=e._ref)}if("TEMPLATE"===e.tagName&&(e.hasAttribute("$if")||e.hasAttribute("st-if"))&&(e.hasAttribute("$each")||e.hasAttribute("st-each"))){const t=document.createElement("TEMPLATE"),n=Array.from(e.attributes).filter(e=>["$if","$each","st-if","st-each"].includes(e.name)),a=n[n.length-1];t.setAttribute(a.name,a.value),e.removeAttribute(a.name),"$each"!==a.name&&"st-each"!==a.name||Array.from(e.attributes).filter(e=>["as","index"].includes(e.name)).forEach(n=>{t.setAttribute(n.name,n.value),e.removeAttribute(n.name)}),Array.from(e.content.childNodes).forEach(e=>t.content.appendChild(e)),e.content.appendChild(t),t._ref=e._ref}if("IMG"===e.tagName&&(e.hasAttribute("src")||e.hasAttribute("_src")||e.hasAttribute("$src"))){const t=e;Promise.resolve().then(()=>{const e=t.getAttribute("_src")||t.getAttribute("src");e&&fetch(e,{cache:"force-cache"}).then(e=>e.text()).then(e=>{const n=(new DOMParser).parseFromString(e,"image/svg+xml").querySelector("svg");n&&(Array.from(t.attributes).forEach(e=>n.setAttribute(e.name,e.value)),t.replaceWith(n))})})}if(void 0!==e._thisObj)t.thisObj=e._thisObj||null;else{let n=e;for(;n&&void 0===n._thisObj;)n=n.parentNode;t.thisObj=n?n._thisObj:null}if(void 0===e._ref){let t=e;for(;t&&void 0===t._ref;)t=t.parentNode;e._ref=t?{...t._ref}:{}}t.extendVars&&Object.assign(e._ref,t.extendVars),((e,t)=>{if(e._bindings)return e._states=new Set,e._bindings.forEach(t=>O({node:e,...t})),void(e._hasOnUpdate&&e.dispatchEvent(new Event("update",{bubbles:!1})));u.exists(e.tagName)&&!e._componentInitialized&&(Array.from(e.attributes).forEach(n=>{var a;if(n.name.startsWith("$.")){const s=n.name.slice(2);let r=E(n.value);r.includes("this.")&&(r=r.replace(/\bthis\./g,"this.parent."));const o=y(r,{thisNode:e},{parent:t.thisObj||e},e._ref||{});let i=e;const l=s.split(".");for(let e=0;e<l.length-1;e++)l[e]&&(i=i[a=l[e]]??(i[a]={}));i[l[l.length-1]]=o,e.removeAttribute(n.name)}}),b(e.tagName,e,t),d(e,"[slot-id]").forEach(e=>e.removeAttribute("slot-id")),e._componentInitialized=!0,e._thisObj||(e._thisObj=e)),"TEMPLATE"===e.tagName&&(e._children=[...e.content.childNodes],e._renderedNodes||(e._renderedNodes=[]));let n=[];"TEMPLATE"===e.tagName?["$if","$each","st-if","st-each"].forEach(t=>e.hasAttribute(t)&&n.push(e.getAttributeNode(t))):n=Array.from(e.attributes).filter(e=>(e.name.startsWith("$")||e.name.startsWith("st-"))&&!["$if","$each","st-if","st-each"].includes(e.name)||e.name.includes(".")),e._thisObj&&t.thisObj&&(e._thisObj.parent=t.thisObj),e._thisObj||(e._thisObj=t.thisObj||null),e._ref||(e._ref=t.extendVars||{}),e._states=new Set,n.forEach(n=>{let a=0;n.name.startsWith("$$")||n.name.startsWith("st-st-")?a=2:(n.name.startsWith("$")||n.name.startsWith("st-"))&&(a=1);const s=2===a?n.name.startsWith("$$")?n.name.slice(2):n.name.slice(6):1===a?n.name.startsWith("$")?n.name.slice(1):n.name.slice(3):n.name;let o=n.value;if(e.removeAttribute(n.name),s.startsWith("."))S({node:e,prop:s.split("."),tpl:o,exp:a});else if(s.startsWith("on")){const n=s.slice(2);"update"===n&&(e._hasOnUpdate=!0),"load"!==n||["BODY","IMG","IFRAME"].includes(e.tagName)||(e._hasOnLoad=!0),"unload"!==n||["BODY","IMG","IFRAME"].includes(e.tagName)||(e._hasOnUnload=!0),e.addEventListener(n,n=>_(o,{event:n,thisNode:e,...n.detail||{}},t.thisObj||e,e._ref||{}))}else"bind"===s?e.addEventListener(["textarea","text","password"].includes(e.type||"text")||e.isContentEditable?"input":"change",n=>{let a=e.isContentEditable?n.target.innerHTML:"checkbox"===e.type?n.target.checked:n.target.files||n.target.value||n.detail;r(e),p(!0),"checkbox"===e.type&&e._checkboxMultiMode?_(`!!checked ? (!${o}.includes(val) && ${o}.push(val)) : (index = ${o}.indexOf(val), index > -1 && ${o}.splice(index, 1))`,{val:e.value,checked:a,thisNode:e},t.thisObj||e,e._ref||{}):_(`${o} = val`,{val:a,thisNode:e},t.thisObj||e,e._ref||{}),p(!1),r(null)}):"text"!==s||o||(o=e.textContent,e.textContent=""),o&&(o=E(o),S({node:e,attr:s,tpl:o,exp:a}))}),(e._hasOnLoad||e._componentInitialized)&&Promise.resolve().then(()=>e.dispatchEvent(new Event("load",{bubbles:!1}))),e._hasOnUpdate&&e.dispatchEvent(new Event("update",{bubbles:!1})),e._thisObj&&(t.thisObj=e._thisObj)})(e,{...t});[...e.childNodes||[]].forEach(n=>w(n,{thisObj:t.thisObj,extendVars:{...e._ref}}))},j=e=>{1===e.nodeType&&(e._hasOnUnload&&e.dispatchEvent(new Event("unload",{bubbles:!1})),e._states&&e._states.forEach(t=>{for(const[n,a]of t)for(const t of a)t.node===e&&a.delete(t)}),e.childNodes&&e.childNodes.forEach(e=>j(e)))},x=w,$={clone:window.structuredClone||(e=>JSON.parse(JSON.stringify(e))),base64:e=>btoa(String.fromCharCode(...(new TextEncoder).encode(e))),unbase64:e=>(new TextDecoder).decode(Uint8Array.from(atob(e),e=>e.charCodeAt(0))),urlbase64:e=>$.base64(e).replace(/[+/=]/g,e=>({"+":"-","/":"","=":""}[e])),unurlbase64:e=>$.unbase64(e.replace(/[-_.]/g,e=>({"-":"+",_:"/",".":"="}[e])).padEnd(4*Math.ceil(e.length/4),"=")),safeJson:e=>{try{return JSON.parse(e)}catch{return null}},updateDefaults:(e,t)=>{for(const n in t)void 0===e[n]&&(e[n]=t[n])},copyFunction:(e,t,...n)=>{n.forEach(n=>e[n]=t[n].bind(t))},getFunctionBody:e=>{const t=e.toString();return t.slice(t.indexOf("{")+1,t.lastIndexOf("}")).trim()},makeDom:e=>{e.includes(">\n")&&(e=e.replace(/>\s+</g,"><").trim());const t=document.createElement("div");return t.innerHTML=e,t.children[0]},newAvg:()=>{let e=0,t=0,n=0;return{add:a=>(e+=a,t++,n=e/t),get:()=>n,clear:()=>{e=0,t=0,n=0}}},newTimeCount:()=>{let e=0,t=0,n=0;return{start:()=>e=(new Date).getTime(),end:()=>{const a=(new Date).getTime(),s=a-e;return e=a,t+=s,n++,s},avg:()=>t/n}}};globalThis.Util=$;let M=new URLSearchParams((null==(t=window.location.hash)?void 0:t.substring(1))||"");const L=i({},e=>$.safeJson(M.get(e)),(e,t)=>{const n=M.get(e),a=void 0===t?void 0:JSON.stringify(t);n===a||null===n&&void 0===a||(void 0===t?M.delete(e):M.set(e,a),window.location.hash="#"+M.toString())});"undefined"!=typeof window&&window.addEventListener("hashchange",()=>{var e;const t=new URLSearchParams((null==(e=window.location.hash)?void 0:e.substring(1))||""),n=new Set([...M.keys(),...t.keys()]);M=t,n.forEach(e=>L[e]=L[e])});const C=i({},e=>$.safeJson(localStorage.getItem(e)),(e,t)=>{const n=localStorage.getItem(e),a=void 0===t?void 0:JSON.stringify(t);n===a||null===n&&void 0===a||(void 0===t?localStorage.removeItem(e):localStorage.setItem(e,a))}),k=i({exitBlocks:0});globalThis.Hash=L,globalThis.LocalStorage=C,globalThis.State=k;const P={NewState:i,Component:u,$:l,$$:d,RefreshState:x,SetTranslator:v,_scanTree:w,_unbindTree:j,Util:$,Hash:L,LocalStorage:C,State:k};if(globalThis.$=l,globalThis.$$=d,"undefined"!=typeof window&&(window.ApigoState=P),"undefined"!=typeof document){const e=()=>{u._initPending();const e=document.documentElement;e.hasAttribute("$data-bs-theme")||e.hasAttribute("data-bs-theme")||e.setAttribute("$data-bs-theme","LocalStorage.darkMode?'dark':'light'"),new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e.isConnected&&w(e)}),e.removedNodes.forEach(e=>j(e))})}).observe(document.documentElement,{childList:!0,subtree:!0}),w(document.documentElement)};"loading"!==document.readyState?e():document.addEventListener("DOMContentLoaded",e,!0)}e.$=l,e.$$=d,e.Component=u,e.Hash=L,e.LocalStorage=C,e.NewState=i,e.RefreshState=x,e.SetTranslator=v,e.State=k,e.Util=$,e._scanTree=w,e._unbindTree=j,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ApigoState=e.ApigoState||{})}(this,function(e){"use strict";var t,n;const s={clone:e=>JSON.parse(JSON.stringify(e)),base64:e=>btoa(String.fromCharCode(...(new TextEncoder).encode(e))),unbase64:e=>(new TextDecoder).decode(Uint8Array.from(atob(e),e=>e.charCodeAt(0))),urlbase64:e=>s.base64(e).replace(/[+/=]/g,e=>({"+":"-","/":"","=":""}[e])),unurlbase64:e=>s.unbase64(e.replace(/[-_.]/g,e=>({"-":"+",_:"/",".":"="}[e])).padEnd(4*Math.ceil(e.length/4),"=")),safeJson:e=>{try{return JSON.parse(e)}catch{return null}},updateDefaults:(e,t)=>{for(const n in t)void 0===e[n]&&(e[n]=t[n])},copyFunction:(e,t,...n)=>{n.forEach(n=>e[n]=t[n].bind(t))},getFunctionBody:e=>{const t=e.toString();return t.slice(t.indexOf("{")+1,t.lastIndexOf("}")).trim()},makeDom:e=>{e.includes(">\n")&&(e=e.replace(/>\s+</g,"><").trim());const t=document.createElement("div");return t.innerHTML=e,t.children[0]},newAvg:()=>{let e=0,t=0,n=0;return{add:s=>(e+=s,t++,n=e/t),get:()=>n,clear:()=>{e=0,t=0,n=0}}},newTimeCount:()=>{let e=0,t=0,n=0;return{start:()=>e=(new Date).getTime(),end:()=>{const s=(new Date).getTime(),a=s-e;return e=s,t+=a,n++,a},avg:()=>t/n}}},a=(e,t)=>t?e.querySelector(t):document.querySelector(e),r=(e,t)=>t?e.querySelectorAll(t):document.querySelectorAll(e);globalThis.Util=s,globalThis.$=a,globalThis.$$=r;let o=null,i=null;const l=e=>o=e,c=e=>i=e,d=new Set;function h(e={},t=null,n=null){const s={},a=new Map,r=new Map,l=(e,t)=>(r.has(e)||r.set(e,new Set),t?r.get(e).add(t):r.get(e).clear(),()=>r.get(e).delete(t)),c=(e,t)=>{r.has(e)&&r.set(e,new Set),r.get(e).delete(t)},h=t||(e=>s[e]),u=n||((e,t)=>s[e]=t);return Object.assign(s,e),new Proxy(s,{get:(e,t)=>"__watch"===t?l:"__unwatch"===t?c:"__isProxy"===t||(o&&(a.has(t)||a.set(t,new Set),a.get(t).add(o),o.node._states||(o.node._states=new Set),o.node._states.add(a)),h(t)),set(e,t,n){if(h(t)!==n&&u(t,n),r.has(t)&&r.get(t).forEach(s=>{const a=s(n);void 0!==a&&(n=a,e[t]=n)}),r.has(null)&&r.get(null).forEach(e=>e(n)),a.has(t)){const e=a.get(t);for(const t of e)t.node.isConnected?i!==t.node&&d.forEach(e=>e(t)):e.delete(t)}return!0}})}globalThis.NewState=h;let u=new URLSearchParams("undefined"!=typeof globalThis&&(null==(n=null==(t=globalThis.location)?void 0:t.hash)?void 0:n.substring(1))||"");const f=h({},e=>s.safeJson(u.get(e)),(e,t)=>{const n=u.get(e),s=void 0===t?void 0:JSON.stringify(t);n===s||null===n&&void 0===s||(void 0===t?u.delete(e):u.set(e,s),globalThis.location.hash="#"+u.toString())});"undefined"!=typeof globalThis&&globalThis.addEventListener("hashchange",()=>{var e;const t=new URLSearchParams((null==(e=globalThis.location.hash)?void 0:e.substring(1))||""),n=new Set([...u.keys(),...t.keys()]);u=t,n.forEach(e=>f[e]=f[e])});const b=h({},e=>s.safeJson(localStorage.getItem(e)),(e,t)=>{const n=localStorage.getItem(e),s=void 0===t?void 0:JSON.stringify(t);n===s||null===n&&void 0===s||(void 0===t?localStorage.removeItem(e):localStorage.setItem(e,s))}),m=h({exitBlocks:0});globalThis.Hash=f,globalThis.LocalStorage=b,globalThis.State=m;let p=!1;const g=e=>{p=e},_=new Map;function y(e,t,n,s){const a={...s||{},...t||{}},r=Object.keys(a),o=Object.values(a),i=e+r.join(",");try{let t=_.get(i);return t||(t=new Function("Hash","LocalStorage","State",...r,e),_.set(i,t)),t.apply(n,[globalThis.Hash,globalThis.LocalStorage,globalThis.State,...o])}catch(a){return p||console.error(a,s,[e,s,t,n]),null}}function A(e,t,n,s){return e.includes("${")?y("return `"+e+"`",t,n,s):y("return "+e,t,n,s)}const E=new Map,v=[],T={getTemplate:e=>document.querySelector(`template[component="${e.toUpperCase()}"]`),register:(e,t,n=null,...s)=>{E.set(e.toUpperCase(),t),"loading"!==document.readyState?T._addTemplate(e,n,s):v.push([e,n,s])},exists:e=>E.has(e.toUpperCase()),getSetupFunction:e=>E.get(e.toUpperCase()),_addTemplate:(e,t,n)=>{if(t){const n=document.createElement("TEMPLATE");n.setAttribute("component",e.toUpperCase()),n.content.appendChild(t),document.body.appendChild(n)}n&&n.forEach(e=>document.body.appendChild(e))},_initPending:()=>{v.forEach(([e,t,n])=>T._addTemplate(e,t,n)),v.length=0}};function N(e,t,n,s={}){e.attributes&&Array.from(e.attributes).forEach(e=>{"class"!==e.name&&("style"===e.name?t.hasAttribute("style")?t.setAttribute("style",`${e.value}; ${t.getAttribute("style")}`):t.setAttribute("style",e.value):t.hasAttribute(e.name)||t.setAttribute(e.name,e.value))}),t.classList.add(...e.classList);const a="TEMPLATE"===t.tagName?t.content:t,r="TEMPLATE"===e.tagName?e.content.childNodes:e.childNodes;Array.from(r).forEach(e=>a.appendChild(e)),e.tagName&&T.exists(e.tagName)&&O(e.tagName,t,n,s)}function O(e,t,n,s={}){if(s[e])return;s[e]=!0,n.thisObj&&Array.from(t.attributes).forEach(e=>{(e.name.startsWith("$")||e.name.startsWith("st-"))&&e.value.includes("this.")&&(e.value=e.value.replace(/\bthis\./g,"this.parent."))});const a=T.getSetupFunction(e),o={};Array.from(t.childNodes).forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&e.hasAttribute("slot")&&(o[e.getAttribute("slot")]=e,e.removeAttribute("slot"))}),t.innerHTML="",t.state=h(t.state||{});const i=T.getTemplate(e);if(i){const e=i.content.cloneNode(!0);if(e.childNodes.length){const a=e.children[0];a&&N(a,t,n,s),r(t,"[slot-id]").forEach(e=>{const t=e.getAttribute("slot-id");o[t]&&(e.removeAttribute("slot-id"),e.innerHTML="",N(o[t],e,n,s))})}}a&&a(t)}let S=(e,t)=>e&&"string"==typeof e?e.replace(/\{(.+?)\}/g,(e,n)=>t.hasOwnProperty(n)?t[n]:e):e;const j=e=>S=e,x=e=>e&&"string"==typeof e&&e.includes("{#")?e.replace(/\{#(.+?)#\}/g,(e,t)=>{const n=t.split("||").map(e=>e.trim()),s={};if(n.length>1){const e=n[0].match(/\{(.+?)\}/g);e&&e.forEach((e,t)=>s[e.substring(1,e.length-1)]=n[t+1]||"")}return S(n[0],s)}):e;if("undefined"!=typeof document)try{document.createElement("div").setAttribute("$t","1")}catch(e){const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(e,n){return e.startsWith("$")?t.call(this,"st-"+e.substring(1),n):t.call(this,e,n)}}var $;function M(e){e._renderedNodes&&e._renderedNodes.forEach(e=>e.forEach(e=>{e.remove(),e._renderedNodes&&M(e)}))}function w(e){const t=e.node;if(!t.isConnected&&"TEMPLATE"!==t.tagName)return;l(e);let n=e.exp?e.tpl?A(e.tpl,{thisNode:t},t._thisObj||t,t._ref||null):null:e.tpl;if(2===e.exp&&"string"==typeof n)try{n=A(n,{thisNode:t},t._thisObj||t,t._ref||null)}catch(e){}if(l(null),e.prop){const s=e.prop;let a=t;for(let e=0;e<s.length-1&&(!s[e]||(null==a[s[e]]&&(a[s[e]]={}),a=a[s[e]],"object"==typeof a));e++);if("object"==typeof a&&null!==a){const e=s[s.length-1];if(e){"object"!=typeof n||null==n||Array.isArray(n)||null!=a[e]||(a[e]={});const t=a[e];"object"==typeof t&&null!=t&&t.__watch?Object.assign(t,n):a[e]!==n&&(a[e]=n)}else"object"!=typeof n||null==n||Array.isArray(n)||Object.assign(a,n)}}else if(e.attr){const s=e.attr;if("if"===s)n?t._renderedNodes&&0!==t._renderedNodes.length||(t._children.forEach(e=>{t.parentNode.insertBefore(e,t),e._ref={...t._ref},e._thisObj=t._thisObj}),t._renderedNodes=[t._children]):(M(t),t._renderedNodes=[]);else if("each"===s)if(n&&"object"==typeof n){const e=t.getAttribute("as")||"item",s=t.getAttribute("index")||"index",a=t.getAttribute("key");let r,o;if(n instanceof Map)r=Array.from(n.keys()),o=e=>n.get(e);else if("function"==typeof n[Symbol.iterator]){const e=Array.isArray(n)?n:Array.from(n);r=new Array(e.length);for(let t=0;t<e.length;t++)r[t]=t;o=t=>e[t]}else r=Object.keys(n),o=e=>n[e];t._keyedNodes||(t._keyedNodes=new Map);const i=new Map,l=[];r.forEach((n,r)=>{const c=o(n),d=a?c&&"object"==typeof c?c[a]:c:n,h=null==d||i.has(d)?`st_key_${r}`:d;let u=t._keyedNodes.get(h);u?(t._keyedNodes.delete(h),u.forEach(a=>{t.parentNode.insertBefore(a,t),a._ref[s]=n,a._ref[e]=c,L(a)})):(u=[],t._children.forEach(a=>{const r=a.cloneNode(!0);r._ref={...t._ref,[s]:n,[e]:c},r._thisObj=t._thisObj,t.parentNode.insertBefore(r,t),u.push(r)})),i.set(h,u),l.push(u)}),t._keyedNodes.forEach(e=>e.forEach(e=>{M(e),e.remove()})),t._keyedNodes=i,t._renderedNodes=l}else M(t),t._renderedNodes=[];else if("bind"===s){if(["INPUT","SELECT","TEXTAREA"].includes(t.tagName)&&!t.hasAttribute("autocomplete")&&t.setAttribute("autocomplete","off"),"checkbox"===t.type){"on"===t.value||n||(y(`${e.tpl} = []`,{thisNode:t},t._thisObj||t,t._ref||{}),n=[]),t._checkboxMultiMode=n instanceof Array;const s=n instanceof Array?n.includes(t.value):!!n;t.checked!==s&&(t.checked=s)}else"radio"===t.type?t.checked!==(t.value===String(n??""))&&(t.checked=t.value===String(n??"")):"value"in t&&"file"!==t.type?Promise.resolve().then(()=>{t.value!==String(n??"")&&(t.value=n)}):t.isContentEditable&&t.innerHTML!==String(n??"")&&(t.innerHTML=n);t.dispatchEvent(new CustomEvent("bind",{bubbles:!1,detail:n}))}else["checked","disabled","readonly"].includes(s)&&(n=!!n),"boolean"==typeof n?n?t.setAttribute(s,""):t.removeAttribute(s):void 0!==n&&("string"!=typeof n&&(n=JSON.stringify(n)),"text"===s?t.textContent=n??"":"html"===s?t.innerHTML=n??"":"IMG"===t.tagName&&"src"===s&&n.includes(".svg")?t.setAttribute("_src",n??""):t.setAttribute(s,n??""))}}function C(e){e.node._bindings||(e.node._bindings=[]),e.node._bindings.push({attr:e.attr,prop:e.prop,tpl:e.tpl,exp:e.exp}),w(e)}$=e=>w(e),d.add($);const L=(e,t={})=>{if(3===e.nodeType){if(e._stTranslated)return;const t=x(e.textContent);return t!==e.textContent&&(e.textContent=t),void(e._stTranslated=!0)}if(1!==e.nodeType)return;if(e._stTranslated||(Array.from(e.attributes).forEach(e=>{if(!e.name.startsWith("$")&&!e.name.startsWith("st-")&&!e.name.startsWith(".")){const t=x(e.value);t!==e.value&&(e.value=t)}}),e._stTranslated=!0),"TEMPLATE"!==e.tagName&&(e.hasAttribute("$if")||e.hasAttribute("$each")||e.hasAttribute("st-if")||e.hasAttribute("st-each"))){const n=document.createElement("TEMPLATE");return Array.from(e.attributes).filter(t=>["$if","$each","st-if","st-each"].includes(t.name)||(e.hasAttribute("$each")||e.hasAttribute("st-each"))&&["as","index"].includes(t.name)).forEach(t=>{n.setAttribute(t.name,t.value),e.removeAttribute(t.name)}),e.parentNode.insertBefore(n,e),n.content.appendChild(e),n._ref=e._ref,void L(n,t)}if("TEMPLATE"===e.tagName&&(e.hasAttribute("$if")||e.hasAttribute("st-if"))&&(e.hasAttribute("$each")||e.hasAttribute("st-each"))){const t=document.createElement("TEMPLATE"),n=Array.from(e.attributes).filter(e=>["$if","$each","st-if","st-each"].includes(e.name)),s=n[n.length-1];t.setAttribute(s.name,s.value),e.removeAttribute(s.name),"$each"!==s.name&&"st-each"!==s.name||Array.from(e.attributes).filter(e=>["as","index"].includes(e.name)).forEach(n=>{t.setAttribute(n.name,n.value),e.removeAttribute(n.name)}),Array.from(e.content.childNodes).forEach(e=>t.content.appendChild(e)),e.content.appendChild(t),t._ref=e._ref}if("IMG"===e.tagName&&(e.hasAttribute("src")||e.hasAttribute("_src")||e.hasAttribute("$src"))){const t=e;Promise.resolve().then(()=>{const e=t.getAttribute("_src")||t.getAttribute("src");e&&fetch(e,{cache:"force-cache"}).then(e=>e.text()).then(e=>{const n=(new DOMParser).parseFromString(e,"image/svg+xml").querySelector("svg");n&&(Array.from(t.attributes).forEach(e=>n.setAttribute(e.name,e.value)),t.replaceWith(n))})})}if(void 0!==e._thisObj)t.thisObj=e._thisObj||null;else{let n=e;for(;n&&void 0===n._thisObj;)n=n.parentNode;t.thisObj=n?n._thisObj:null}if(void 0===e._ref){let t=e;for(;t&&void 0===t._ref;)t=t.parentNode;e._ref=t?{...t._ref}:{}}t.extendVars&&Object.assign(e._ref,t.extendVars),function(e,t){if(e._bindings)return e._states=new Set,e._bindings.forEach(t=>w({node:e,...t})),void(e._hasOnUpdate&&e.dispatchEvent(new Event("update",{bubbles:!1})));T.exists(e.tagName)&&!e._componentInitialized&&(Array.from(e.attributes).forEach(n=>{var s;if(n.name.startsWith("$.")){const a=n.name.slice(2);let r=x(n.value);t.thisObj&&r.includes("this.")&&(r=r.replace(/\bthis\./g,"this.parent."));const o=A(r,{thisNode:e},{parent:t.thisObj||e},e._ref||{});let i=e;const l=a.split(".");for(let e=0;e<l.length-1;e++)l[e]&&(i=i[s=l[e]]??(i[s]={}));i[l[l.length-1]]=o,e.removeAttribute(n.name)}}),O(e.tagName,e,t),r(e,"[slot-id]").forEach(e=>e.removeAttribute("slot-id")),e._componentInitialized=!0,e._thisObj||(e._thisObj=e)),"TEMPLATE"===e.tagName&&(e._children=[...e.content.childNodes],e._renderedNodes||(e._renderedNodes=[]));let n=[];"TEMPLATE"===e.tagName?["$if","$each","st-if","st-each"].forEach(t=>e.hasAttribute(t)&&n.push(e.getAttributeNode(t))):n=Array.from(e.attributes).filter(e=>(e.name.startsWith("$")||e.name.startsWith("st-"))&&!["$if","$each","st-if","st-each"].includes(e.name)||e.name.includes(".")),e._thisObj&&t.thisObj&&e._thisObj!==t.thisObj&&(e._thisObj.parent=t.thisObj),e._thisObj||(e._thisObj=t.thisObj||null),e._ref||(e._ref=t.extendVars||{}),e._states=new Set,n.forEach(n=>{let s=0;n.name.startsWith("$$")||n.name.startsWith("st-st-")?s=2:(n.name.startsWith("$")||n.name.startsWith("st-"))&&(s=1);const a=2===s?n.name.startsWith("$$")?n.name.slice(2):n.name.slice(6):1===s?n.name.startsWith("$")?n.name.slice(1):n.name.slice(3):n.name;let r=n.value;if(e.removeAttribute(n.name),a.startsWith("."))C({node:e,prop:a.split("."),tpl:r,exp:s});else if(a.startsWith("on")){const n=a.slice(2);"update"===n&&(e._hasOnUpdate=!0),"load"!==n||["BODY","IMG","IFRAME"].includes(e.tagName)||(e._hasOnLoad=!0),"unload"!==n||["BODY","IMG","IFRAME"].includes(e.tagName)||(e._hasOnUnload=!0),e.addEventListener(n,n=>y(r,{event:n,thisNode:e,...n.detail||{}},t.thisObj||e,e._ref||{}))}else{if("bind"===a){const n=["INPUT","TEXTAREA"].includes(e.tagName)&&["textarea","text","password","email","number","search","url","tel"].includes(e.type||"text")||e.isContentEditable;e.addEventListener(n?"input":"change",n=>{let s=e.isContentEditable?n.target.innerHTML:"checkbox"===e.type?n.target.checked:n.target.files||n.target.value||n.detail;c(e),g(!0),"checkbox"===e.type&&e._checkboxMultiMode?y(`!!checked ? (!${r}.includes(val) && ${r}.push(val)) : (index = ${r}.indexOf(val), index > -1 && ${r}.splice(index, 1))`,{val:e.value,checked:s,thisNode:e},t.thisObj||e,e._ref||{}):y(`${r} = val`,{val:s,thisNode:e},t.thisObj||e,e._ref||{}),g(!1),c(null)})}else"text"!==a||r||(r=e.textContent,e.textContent="");r&&(r=x(r),C({node:e,attr:a,tpl:r,exp:s}))}}),(e._hasOnLoad||e._componentInitialized)&&Promise.resolve().then(()=>e.dispatchEvent(new Event("load",{bubbles:!1}))),e._hasOnUpdate&&e.dispatchEvent(new Event("update",{bubbles:!1})),e._thisObj&&(t.thisObj=e._thisObj)}(e,{...t});[...e.childNodes||[]].forEach(n=>L(n,{thisObj:t.thisObj,extendVars:{...e._ref}}))},k=e=>{1===e.nodeType&&(e._hasOnUnload&&e.dispatchEvent(new Event("unload",{bubbles:!1})),e._states&&e._states.forEach(t=>{for(const[n,s]of t)for(const t of s)t.node===e&&s.delete(t)}),e.childNodes&&e.childNodes.forEach(e=>k(e)))};if(globalThis.Component=T,globalThis.SetTranslator=j,globalThis.__unsafeRefreshState=L,"undefined"!=typeof document){const e=()=>{globalThis.Component&&globalThis.Component._initPending&&globalThis.Component._initPending();const e=document.documentElement;e.hasAttribute("$data-bs-theme")||e.hasAttribute("data-bs-theme")||e.setAttribute("$data-bs-theme","LocalStorage.darkMode?'dark':'light'"),new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e.isConnected&&L(e)}),e.removedNodes.forEach(e=>k(e))})}).observe(document.documentElement,{childList:!0,subtree:!0}),L(document.documentElement)};"loading"!==document.readyState?e():document.addEventListener("DOMContentLoaded",e,!0)}const P=L;e.$=a,e.$$=r,e.Component=T,e.Hash=f,e.LocalStorage=b,e.NewState=h,e.SetTranslator=j,e.State=m,e.Util=s,e.__unsafeRefreshState=P,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "@apigo.cc/state",
3
- "version": "1.0.18",
3
+ "version": "1.0.21",
4
4
  "type": "module",
5
5
  "main": "dist/state.js",
6
+ "module": "dist/state.js",
6
7
  "files": [
7
8
  "dist"
8
9
  ],