@apigo.cc/state 1.0.11 → 1.0.16

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/state.js CHANGED
@@ -1,681 +1,673 @@
1
- var _a;
2
- let _activeBinding = null;
3
- let _noWriteBack = null;
4
- const setActiveBinding = (val) => _activeBinding = val;
5
- const setNoWriteBack = (val) => _noWriteBack = val;
6
- const _notifiers = /* @__PURE__ */ new Set();
7
- const onNotifyUpdate = (fn) => _notifiers.add(fn);
8
- function NewState(defaults = {}, getter = null, setter = null) {
9
- const _defaults = {};
10
- const _stateMappings = /* @__PURE__ */ new Map();
11
- const _watchers = /* @__PURE__ */ new Map();
12
- const _watchFunc = (k, cb) => {
13
- if (!_watchers.has(k)) _watchers.set(k, /* @__PURE__ */ new Set());
14
- !cb ? _watchers.get(k).clear() : _watchers.get(k).add(cb);
15
- return () => _watchers.get(k).delete(cb);
16
- };
17
- const _unwatchFunc = (k, cb) => {
18
- if (_watchers.has(k)) _watchers.get(k).delete(cb);
19
- };
20
- const __getter = getter || ((k) => _defaults[k]);
21
- const __setter = setter || ((k, v) => _defaults[k] = v);
22
- Object.assign(_defaults, defaults);
23
- return new Proxy(_defaults, {
24
- get(target, key) {
25
- if (key === "__watch") return _watchFunc;
26
- if (key === "__unwatch") return _unwatchFunc;
27
- if (key === "__isProxy") return true;
28
- if (_activeBinding) {
29
- if (!_stateMappings.has(key)) _stateMappings.set(key, /* @__PURE__ */ new Set());
30
- _stateMappings.get(key).add(_activeBinding);
31
- if (!_activeBinding.node._states) _activeBinding.node._states = /* @__PURE__ */ new Set();
32
- _activeBinding.node._states.add(_stateMappings);
33
- }
34
- return __getter(key);
35
- },
36
- set(target, key, value) {
37
- if (__getter(key) !== value) {
38
- __setter(key, value);
39
- }
40
- if (_watchers.has(key)) {
41
- _watchers.get(key).forEach((cb) => {
42
- const r = cb(value);
43
- if (r !== void 0) {
44
- value = r;
45
- target[key] = value;
46
- }
47
- });
48
- }
49
- if (_watchers.has(null)) {
50
- _watchers.get(null).forEach((cb) => cb(value));
51
- }
52
- if (_stateMappings.has(key)) {
53
- const bindings = _stateMappings.get(key);
54
- for (const binding of bindings) {
55
- if (!binding.node.isConnected) {
56
- bindings.delete(binding);
57
- continue;
58
- }
59
- if (_noWriteBack !== binding.node) {
60
- _notifiers.forEach((fn) => fn(binding));
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 = {}));
3
+ })(this, function(exports2) {
4
+ "use strict";
5
+ var _a;
6
+ let __activeBinding = null;
7
+ let __noWriteBack = null;
8
+ const _setActiveBinding = (val) => __activeBinding = val;
9
+ const _setNoWriteBack = (val) => __noWriteBack = val;
10
+ const _notifiers = /* @__PURE__ */ new Set();
11
+ const _onNotifyUpdate = (fn) => _notifiers.add(fn);
12
+ function NewState(defaults = {}, getter = null, setter = null) {
13
+ const _defaults = {};
14
+ const _stateMappings = /* @__PURE__ */ new Map();
15
+ const _watchers = /* @__PURE__ */ new Map();
16
+ const _watchFunc = (k, cb) => {
17
+ if (!_watchers.has(k)) _watchers.set(k, /* @__PURE__ */ new Set());
18
+ !cb ? _watchers.get(k).clear() : _watchers.get(k).add(cb);
19
+ return () => _watchers.get(k).delete(cb);
20
+ };
21
+ const _unwatchFunc = (k, cb) => {
22
+ if (_watchers.has(k)) _watchers.set(k, /* @__PURE__ */ new Set());
23
+ _watchers.get(k).delete(cb);
24
+ };
25
+ const __getter = getter || ((k) => _defaults[k]);
26
+ const __setter = setter || ((k, v) => _defaults[k] = v);
27
+ Object.assign(_defaults, defaults);
28
+ return new Proxy(_defaults, {
29
+ get(target, key) {
30
+ if (key === "__watch") return _watchFunc;
31
+ if (key === "__unwatch") return _unwatchFunc;
32
+ if (key === "__isProxy") return true;
33
+ if (__activeBinding) {
34
+ if (!_stateMappings.has(key)) _stateMappings.set(key, /* @__PURE__ */ new Set());
35
+ _stateMappings.get(key).add(__activeBinding);
36
+ if (!__activeBinding.node._states) __activeBinding.node._states = /* @__PURE__ */ new Set();
37
+ __activeBinding.node._states.add(_stateMappings);
38
+ }
39
+ return __getter(key);
40
+ },
41
+ set(target, key, value) {
42
+ if (__getter(key) !== value) {
43
+ __setter(key, value);
44
+ }
45
+ if (_watchers.has(key)) {
46
+ _watchers.get(key).forEach((cb) => {
47
+ const r = cb(value);
48
+ if (r !== void 0) {
49
+ value = r;
50
+ target[key] = value;
51
+ }
52
+ });
53
+ }
54
+ if (_watchers.has(null)) {
55
+ _watchers.get(null).forEach((cb) => cb(value));
56
+ }
57
+ if (_stateMappings.has(key)) {
58
+ const bindings = _stateMappings.get(key);
59
+ for (const binding of bindings) {
60
+ if (!binding.node.isConnected) {
61
+ bindings.delete(binding);
62
+ continue;
63
+ }
64
+ if (__noWriteBack !== binding.node) {
65
+ _notifiers.forEach((fn) => fn(binding));
66
+ }
61
67
  }
62
68
  }
63
- }
64
- return true;
65
- }
66
- });
67
- }
68
- const $ = (a, b) => b ? a.querySelector(b) : document.querySelector(a);
69
- const $$ = (a, b) => b ? a.querySelectorAll(b) : document.querySelectorAll(a);
70
- const _components = /* @__PURE__ */ new Map();
71
- const _pendingTemplates = [];
72
- const Component = {
73
- getTemplate: (name) => document.querySelector(`template[component="${name.toUpperCase()}"]`),
74
- register: (name, setupFunc, templateNode = null, ...globalNodes) => {
75
- _components.set(name.toUpperCase(), setupFunc);
76
- if (document.readyState !== "loading") Component._addTemplate(name, templateNode, globalNodes);
77
- else _pendingTemplates.push([name, templateNode, globalNodes]);
78
- },
79
- exists: (name) => _components.has(name.toUpperCase()),
80
- getSetupFunction: (name) => _components.get(name.toUpperCase()),
81
- _addTemplate: (name, templateNode, globalNodes) => {
82
- if (templateNode) {
83
- const template = document.createElement("TEMPLATE");
84
- template.setAttribute("component", name.toUpperCase());
85
- template.content.appendChild(templateNode);
86
- document.body.appendChild(template);
87
- }
88
- if (globalNodes) globalNodes.forEach((node) => document.body.appendChild(node));
89
- },
90
- _initPending: () => {
91
- _pendingTemplates.forEach(([name, templateNode, globalNodes]) => Component._addTemplate(name, templateNode, globalNodes));
92
- _pendingTemplates.length = 0;
93
- }
94
- };
95
- function _mergeNode(from, to, scanObj, exists = {}) {
96
- if (from.attributes) {
97
- Array.from(from.attributes).forEach((attr) => {
98
- if (attr.name === "class") return;
99
- if (attr.name === "style") {
100
- if (to.hasAttribute("style")) to.setAttribute("style", `${attr.value}; ${to.getAttribute("style")}`);
101
- else to.setAttribute("style", attr.value);
102
- } else if (!to.hasAttribute(attr.name)) {
103
- to.setAttribute(attr.name, attr.value);
69
+ return true;
104
70
  }
105
71
  });
106
72
  }
107
- to.classList.add(...from.classList);
108
- const fromContent = from.tagName === "TEMPLATE" ? from.content : from;
109
- const toContent = to.tagName === "TEMPLATE" ? to.content : to;
110
- Array.from(fromContent.childNodes).forEach((child) => toContent.appendChild(child));
111
- if (from.tagName && Component.exists(from.tagName)) _makeComponent(from.tagName, to, scanObj, exists);
112
- }
113
- function _makeComponent(name, node, scanObj, exists = {}) {
114
- if (exists[name]) return;
115
- exists[name] = true;
116
- if (scanObj.thisObj) {
117
- Array.from(node.attributes).forEach((attr) => {
118
- if ((attr.name.startsWith("$") || attr.name.startsWith("st-")) && attr.value.includes("this.")) {
119
- attr.value = attr.value.replace(/\bthis\./g, "this.parent.");
73
+ const $ = (a, b) => b ? a.querySelector(b) : document.querySelector(a);
74
+ const $$ = (a, b) => b ? a.querySelectorAll(b) : document.querySelectorAll(a);
75
+ const _components = /* @__PURE__ */ new Map();
76
+ const _pendingTemplates = [];
77
+ const Component = {
78
+ getTemplate: (name) => document.querySelector(`template[component="${name.toUpperCase()}"]`),
79
+ register: (name, setupFunc, templateNode = null, ...globalNodes) => {
80
+ console.log("Component.register:", name.toUpperCase());
81
+ _components.set(name.toUpperCase(), setupFunc);
82
+ if (document.readyState !== "loading") Component._addTemplate(name, templateNode, globalNodes);
83
+ else _pendingTemplates.push([name, templateNode, globalNodes]);
84
+ },
85
+ exists: (name) => _components.has(name.toUpperCase()),
86
+ getSetupFunction: (name) => _components.get(name.toUpperCase()),
87
+ _addTemplate: (name, templateNode, globalNodes) => {
88
+ if (templateNode) {
89
+ const template = document.createElement("TEMPLATE");
90
+ template.setAttribute("component", name.toUpperCase());
91
+ template.content.appendChild(templateNode);
92
+ document.body.appendChild(template);
120
93
  }
121
- });
122
- }
123
- const componentFunc = Component.getSetupFunction(name);
124
- const slots = {};
125
- Array.from(node.childNodes).forEach((child) => {
126
- if (child.nodeType === Node.ELEMENT_NODE && child.hasAttribute("slot")) {
127
- slots[child.getAttribute("slot")] = child;
128
- child.removeAttribute("slot");
94
+ if (globalNodes) globalNodes.forEach((node) => document.body.appendChild(node));
95
+ },
96
+ _initPending: () => {
97
+ _pendingTemplates.forEach(([name, templateNode, globalNodes]) => Component._addTemplate(name, templateNode, globalNodes));
98
+ _pendingTemplates.length = 0;
129
99
  }
130
- });
131
- node.innerHTML = "";
132
- node.state = NewState(node.state || {});
133
- const template = Component.getTemplate(name);
134
- if (template) {
135
- const tplnode = template.content.cloneNode(true);
136
- if (tplnode.childNodes.length) {
137
- const rootNode = Array.from(tplnode.childNodes).find((n) => n.nodeType === Node.ELEMENT_NODE);
138
- if (rootNode) _mergeNode(rootNode, node, scanObj, exists);
139
- $$(node, "[slot-id]").forEach((placeholder) => {
140
- const slotName = placeholder.getAttribute("slot-id");
141
- if (slots[slotName]) {
142
- placeholder.removeAttribute("slot-id");
143
- placeholder.innerHTML = "";
144
- _mergeNode(slots[slotName], placeholder, scanObj, exists);
100
+ };
101
+ function _mergeNode(from, to, scanObj, exists = {}) {
102
+ if (from.attributes) {
103
+ Array.from(from.attributes).forEach((attr) => {
104
+ if (attr.name === "class") return;
105
+ if (attr.name === "style") {
106
+ if (to.hasAttribute("style")) to.setAttribute("style", `${attr.value}; ${to.getAttribute("style")}`);
107
+ else to.setAttribute("style", attr.value);
108
+ } else if (!to.hasAttribute(attr.name)) {
109
+ to.setAttribute(attr.name, attr.value);
145
110
  }
146
111
  });
147
112
  }
113
+ to.classList.add(...from.classList);
114
+ const target = to.tagName === "TEMPLATE" ? to.content : to;
115
+ const sourceNodes = from.tagName === "TEMPLATE" ? from.content.childNodes : from.childNodes;
116
+ Array.from(sourceNodes).forEach((child) => target.appendChild(child));
117
+ if (from.tagName && Component.exists(from.tagName)) _makeComponent(from.tagName, to, scanObj, exists);
148
118
  }
149
- if (componentFunc) componentFunc(node);
150
- }
151
- let _disableRunCodeError = false;
152
- function setDisableRunCodeError(value) {
153
- _disableRunCodeError = value;
154
- }
155
- const _fnCache = /* @__PURE__ */ new Map();
156
- function _runCode(code, vars, thisObj, extendVars) {
157
- const allVars = { ...extendVars || {}, ...vars || {} };
158
- const argKeys = Object.keys(allVars);
159
- const argValues = Object.values(allVars);
160
- const cacheKey = code + argKeys.join(",");
161
- try {
162
- let fn = _fnCache.get(cacheKey);
163
- if (!fn) {
164
- fn = new Function("Hash", "LocalStorage", "State", ...argKeys, code);
165
- _fnCache.set(cacheKey, fn);
119
+ function _makeComponent(name, node, scanObj, exists = {}) {
120
+ if (exists[name]) return;
121
+ exists[name] = true;
122
+ if (scanObj.thisObj) {
123
+ Array.from(node.attributes).forEach((attr) => {
124
+ if ((attr.name.startsWith("$") || attr.name.startsWith("st-")) && attr.value.includes("this.")) {
125
+ attr.value = attr.value.replace(/\bthis\./g, "this.parent.");
126
+ }
127
+ });
166
128
  }
167
- return fn.apply(thisObj, [globalThis.Hash, globalThis.LocalStorage, globalThis.State, ...argValues]);
168
- } catch (e) {
169
- if (!_disableRunCodeError) console.error(e, extendVars, [code, extendVars, vars, thisObj]);
170
- return null;
129
+ const componentFunc = Component.getSetupFunction(name);
130
+ const slots = {};
131
+ Array.from(node.childNodes).forEach((child) => {
132
+ if (child.nodeType === Node.ELEMENT_NODE && child.hasAttribute("slot")) {
133
+ slots[child.getAttribute("slot")] = child;
134
+ child.removeAttribute("slot");
135
+ }
136
+ });
137
+ node.innerHTML = "";
138
+ node.state = NewState(node.state || {});
139
+ const template = Component.getTemplate(name);
140
+ if (template) {
141
+ const tplnode = template.content.cloneNode(true);
142
+ if (tplnode.childNodes.length) {
143
+ const rootNode = tplnode.children[0];
144
+ if (rootNode) _mergeNode(rootNode, node, scanObj, exists);
145
+ $$(node, "[slot-id]").forEach((placeholder) => {
146
+ const slotName = placeholder.getAttribute("slot-id");
147
+ if (slots[slotName]) {
148
+ placeholder.removeAttribute("slot-id");
149
+ placeholder.innerHTML = "";
150
+ _mergeNode(slots[slotName], placeholder, scanObj, exists);
151
+ }
152
+ });
153
+ }
154
+ }
155
+ if (componentFunc) componentFunc(node);
156
+ }
157
+ let _disableRunCodeError = false;
158
+ function setDisableRunCodeError(value) {
159
+ _disableRunCodeError = value;
171
160
  }
172
- }
173
- function _returnCode(code, vars, thisObj, extendVars) {
174
- if (code.includes("${")) return _runCode("return `" + code + "`", vars, thisObj, extendVars);
175
- else return _runCode("return " + code, vars, thisObj, extendVars);
176
- }
177
- let _translator = (text, args) => {
178
- if (!text || typeof text !== "string") return text;
179
- return text.replace(/\{(.+?)\}/g, (match, key) => args.hasOwnProperty(key) ? args[key] : match);
180
- };
181
- const SetTranslator = (fn) => _translator = fn;
182
- const _translate = (text) => {
183
- if (!text || typeof text !== "string" || !text.includes("{#")) return text;
184
- return text.replace(/\{#(.+?)#\}/g, (m, content) => {
185
- const parts = content.split("||").map((s) => s.trim());
186
- const args = {};
187
- if (parts.length > 1) {
188
- const matches = parts[0].match(/\{(.+?)\}/g);
189
- if (matches) matches.forEach((match, i) => args[match.substring(1, match.length - 1)] = parts[i + 1] || "");
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;
190
177
  }
191
- return _translator(parts[0], args);
192
- });
193
- };
194
- if (typeof document !== "undefined") {
195
- try {
196
- document.createElement("div").setAttribute("$t", "1");
197
- } catch (e) {
198
- const originalSetAttribute = Element.prototype.setAttribute;
199
- Element.prototype.setAttribute = function(name, value) {
200
- if (!name.startsWith("$")) return originalSetAttribute.call(this, name, value);
201
- return originalSetAttribute.call(this, "st-" + name.substring(1), value);
202
- };
203
178
  }
204
- }
205
- onNotifyUpdate((binding) => _updateBinding(binding));
206
- function _clearRenderedNodes(node) {
207
- if (node._renderedNodes) node._renderedNodes.forEach((nodes) => nodes.forEach((child) => {
208
- child.remove();
209
- if (child._renderedNodes) _clearRenderedNodes(child);
210
- }));
211
- }
212
- function _updateBinding(binding) {
213
- const node = binding.node;
214
- if (!node.isConnected && node.tagName !== "TEMPLATE") return;
215
- setActiveBinding(binding);
216
- if (window.__perfTrace) window.__perfTrace.evalCount++;
217
- const evalStart = window.__perfTrace ? performance.now() : 0;
218
- let result = binding.exp ? binding.tpl ? _returnCode(binding.tpl, { thisNode: node }, node._thisObj || node, node._ref || null) : null : binding.tpl;
219
- if (window.__perfTrace) window.__perfTrace.evalTotal += performance.now() - evalStart;
220
- setActiveBinding(null);
221
- if (binding.prop) {
222
- const prop = binding.prop;
223
- let o = node;
224
- for (let i = 0; i < prop.length - 1; i++) {
225
- if (!prop[i]) continue;
226
- if (o[prop[i]] == null) o[prop[i]] = {};
227
- o = o[prop[i]];
228
- if (typeof o !== "object") break;
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
+ let _translator = (text, args) => {
184
+ if (!text || typeof text !== "string") return text;
185
+ return text.replace(/\{(.+?)\}/g, (match, key) => args.hasOwnProperty(key) ? args[key] : match);
186
+ };
187
+ const SetTranslator = (fn) => _translator = fn;
188
+ const _translate = (text) => {
189
+ if (!text || typeof text !== "string" || !text.includes("{#")) return text;
190
+ return text.replace(/\{#(.+?)#\}/g, (m, content) => {
191
+ const parts = content.split("||").map((s) => s.trim());
192
+ const args = {};
193
+ if (parts.length > 1) {
194
+ const matches = parts[0].match(/\{(.+?)\}/g);
195
+ if (matches) matches.forEach((match, i) => args[match.substring(1, match.length - 1)] = parts[i + 1] || "");
196
+ }
197
+ return _translator(parts[0], args);
198
+ });
199
+ };
200
+ if (typeof document !== "undefined") {
201
+ try {
202
+ document.createElement("div").setAttribute("$t", "1");
203
+ } catch (e) {
204
+ const originalSetAttribute = Element.prototype.setAttribute;
205
+ Element.prototype.setAttribute = function(name, value) {
206
+ if (!name.startsWith("$")) return originalSetAttribute.call(this, name, value);
207
+ return originalSetAttribute.call(this, "st-" + name.substring(1), value);
208
+ };
229
209
  }
230
- if (typeof o === "object" && o !== null) {
231
- const lk = prop[prop.length - 1];
232
- if (lk) {
233
- if (typeof result === "object" && result != null && !Array.isArray(result) && o[lk] == null) o[lk] = {};
234
- const lo = o[lk];
235
- if (typeof lo === "object" && lo != null && lo.__watch) Object.assign(lo, result);
236
- else o[lk] = result;
237
- } else if (typeof result === "object" && result != null && !Array.isArray(result)) {
238
- Object.assign(o, result);
210
+ }
211
+ _onNotifyUpdate((binding) => _updateBinding(binding));
212
+ function _clearRenderedNodes(node) {
213
+ if (node._renderedNodes) node._renderedNodes.forEach((nodes) => nodes.forEach((child) => {
214
+ child.remove();
215
+ if (child._renderedNodes) _clearRenderedNodes(child);
216
+ }));
217
+ }
218
+ function _updateBinding(binding) {
219
+ const node = binding.node;
220
+ if (!node.isConnected && node.tagName !== "TEMPLATE") return;
221
+ _setActiveBinding(binding);
222
+ let result = binding.exp ? binding.tpl ? _returnCode(binding.tpl, { thisNode: node }, node._thisObj || node, node._ref || null) : null : binding.tpl;
223
+ if (binding.exp === 2 && typeof result === "string") {
224
+ try {
225
+ result = _returnCode(result, { thisNode: node }, node._thisObj || node, node._ref || null);
226
+ } catch (e) {
239
227
  }
240
228
  }
241
- } else if (binding.attr) {
242
- const attr = binding.attr;
243
- if (attr === "if") {
244
- if (result) {
245
- if (!node._renderedNodes || node._renderedNodes.length === 0) {
246
- node._children.forEach((child) => {
247
- child._stManaged = true;
248
- node.parentNode.insertBefore(child, node);
249
- child._ref = { ...node._ref };
250
- });
251
- node._renderedNodes = [node._children];
252
- } else {
253
- node._renderedNodes[0].forEach((child) => _scanTree(child, { thisObj: node._thisObj, extendVars: child._ref }));
229
+ _setActiveBinding(null);
230
+ if (binding.prop) {
231
+ const prop = binding.prop;
232
+ let o = node;
233
+ for (let i = 0; i < prop.length - 1; i++) {
234
+ if (!prop[i]) continue;
235
+ if (o[prop[i]] == null) o[prop[i]] = {};
236
+ o = o[prop[i]];
237
+ if (typeof o !== "object") break;
238
+ }
239
+ if (typeof o === "object" && o !== null) {
240
+ const lk = prop[prop.length - 1];
241
+ if (lk) {
242
+ if (typeof result === "object" && result != null && !Array.isArray(result) && o[lk] == null) o[lk] = {};
243
+ const lo = o[lk];
244
+ if (typeof lo === "object" && lo != null && lo.__watch) Object.assign(lo, result);
245
+ else {
246
+ if (o[lk] !== result) o[lk] = result;
247
+ }
248
+ } else if (typeof result === "object" && result != null && !Array.isArray(result)) {
249
+ Object.assign(o, result);
254
250
  }
255
- } else {
256
- _clearRenderedNodes(node);
257
- node._renderedNodes = [];
258
251
  }
259
- } else if (attr === "each") {
260
- if (result && typeof result === "object") {
261
- const asName = node.getAttribute("as") || "item";
262
- const indexName = node.getAttribute("index") || "index";
263
- const keyName = node.getAttribute("key");
264
- let keys, getVal;
265
- if (result instanceof Map) {
266
- keys = Array.from(result.keys());
267
- getVal = (k) => result.get(k);
268
- } else if (typeof result[Symbol.iterator] === "function") {
269
- const arr = Array.isArray(result) ? result : Array.from(result);
270
- keys = new Array(arr.length);
271
- for (let i = 0; i < arr.length; i++) keys[i] = i;
272
- getVal = (k) => arr[k];
252
+ } else if (binding.attr) {
253
+ const attr = binding.attr;
254
+ if (attr === "if") {
255
+ if (result) {
256
+ if (!node._renderedNodes || node._renderedNodes.length === 0) {
257
+ node._children.forEach((child) => {
258
+ node.parentNode.insertBefore(child, node);
259
+ child._ref = { ...node._ref };
260
+ child._thisObj = node._thisObj;
261
+ });
262
+ node._renderedNodes = [node._children];
263
+ }
273
264
  } else {
274
- keys = Object.keys(result);
275
- getVal = (k) => result[k];
265
+ _clearRenderedNodes(node);
266
+ node._renderedNodes = [];
276
267
  }
277
- if (!node._keyedNodes) node._keyedNodes = /* @__PURE__ */ new Map();
278
- const newKeyedNodes = /* @__PURE__ */ new Map();
279
- const currentRenderedNodes = [];
280
- keys.forEach((k, i) => {
281
- const item = getVal(k);
282
- const rawKey = keyName ? item && typeof item === "object" ? item[keyName] : item : k;
283
- const keyVal = rawKey === void 0 || rawKey === null || newKeyedNodes.has(rawKey) ? `st_key_fallback_${i}_${Math.random()}` : rawKey;
284
- let existingNodes = node._keyedNodes.get(keyVal);
285
- if (existingNodes) {
286
- node._keyedNodes.delete(keyVal);
287
- existingNodes.forEach((child) => {
288
- if (window.__statePerformanceTelemetry) window.__statePerformanceTelemetry.reuseCount++;
289
- let scopeChanged = false;
290
- for (let key in node._ref) {
291
- if (key === asName || key === indexName) continue;
292
- if (child._ref[key] !== node._ref[key]) {
293
- child._ref[key] = node._ref[key];
294
- scopeChanged = true;
295
- }
296
- }
297
- const indexChanged = child._ref[indexName] !== k;
298
- if (indexChanged) child._ref[indexName] = k;
299
- if (child._ref[asName] !== item || scopeChanged) {
300
- child._ref[asName] = item;
301
- if (window.__statePerformanceTelemetry) window.__statePerformanceTelemetry.scanCount++;
302
- _scanTree(child, { thisObj: node._thisObj, extendVars: child._ref });
303
- } else if (node.parentNode.lastChild !== child) {
304
- if (window.__statePerformanceTelemetry) window.__statePerformanceTelemetry.moveCount++;
305
- node.parentNode.insertBefore(child, node);
306
- }
307
- });
268
+ } else if (attr === "each") {
269
+ if (result && typeof result === "object") {
270
+ const asName = node.getAttribute("as") || "item";
271
+ const indexName = node.getAttribute("index") || "index";
272
+ const keyName = node.getAttribute("key");
273
+ let keys, getVal;
274
+ if (result instanceof Map) {
275
+ keys = Array.from(result.keys());
276
+ getVal = (k) => result.get(k);
277
+ } else if (typeof result[Symbol.iterator] === "function") {
278
+ const arr = Array.isArray(result) ? result : Array.from(result);
279
+ keys = new Array(arr.length);
280
+ for (let i = 0; i < arr.length; i++) keys[i] = i;
281
+ getVal = (k) => arr[k];
308
282
  } else {
309
- existingNodes = [];
310
- node._children.forEach((child) => {
311
- const cloned = child.cloneNode(true);
312
- cloned._stManaged = true;
313
- cloned._ref = { ...node._ref, [indexName]: k, [asName]: item };
314
- cloned._thisObj = node._thisObj;
315
- node.parentNode.insertBefore(cloned, node);
316
- existingNodes.push(cloned);
317
- });
283
+ keys = Object.keys(result);
284
+ getVal = (k) => result[k];
318
285
  }
319
- newKeyedNodes.set(keyVal, existingNodes);
320
- currentRenderedNodes.push(existingNodes);
321
- existingNodes.forEach((child) => node.parentNode.insertBefore(child, node));
322
- });
323
- node._keyedNodes.forEach((nodes) => nodes.forEach((child) => {
324
- _clearRenderedNodes(child);
325
- child.remove();
326
- }));
327
- node._keyedNodes = newKeyedNodes;
328
- node._renderedNodes = currentRenderedNodes;
286
+ if (!node._keyedNodes) node._keyedNodes = /* @__PURE__ */ new Map();
287
+ const newKeyedNodes = /* @__PURE__ */ new Map();
288
+ const currentRenderedNodes = [];
289
+ keys.forEach((k, i) => {
290
+ const item = getVal(k);
291
+ const rawKey = keyName ? item && typeof item === "object" ? item[keyName] : item : k;
292
+ const keyVal = rawKey === void 0 || rawKey === null || newKeyedNodes.has(rawKey) ? `st_key_${i}` : rawKey;
293
+ let existingNodes = node._keyedNodes.get(keyVal);
294
+ if (existingNodes) {
295
+ node._keyedNodes.delete(keyVal);
296
+ existingNodes.forEach((child) => {
297
+ child._ref[indexName] = k;
298
+ child._ref[asName] = item;
299
+ _scanTree(child);
300
+ });
301
+ } else {
302
+ existingNodes = [];
303
+ node._children.forEach((child) => {
304
+ const cloned = child.cloneNode(true);
305
+ cloned._ref = { ...node._ref, [indexName]: k, [asName]: item };
306
+ cloned._thisObj = node._thisObj;
307
+ node.parentNode.insertBefore(cloned, node);
308
+ existingNodes.push(cloned);
309
+ });
310
+ }
311
+ newKeyedNodes.set(keyVal, existingNodes);
312
+ currentRenderedNodes.push(existingNodes);
313
+ });
314
+ node._keyedNodes.forEach((nodes) => nodes.forEach((child) => {
315
+ _clearRenderedNodes(child);
316
+ child.remove();
317
+ }));
318
+ node._keyedNodes = newKeyedNodes;
319
+ node._renderedNodes = currentRenderedNodes;
320
+ } else {
321
+ _clearRenderedNodes(node);
322
+ node._renderedNodes = [];
323
+ }
324
+ } else if (attr === "bind") {
325
+ if (["INPUT", "SELECT", "TEXTAREA"].includes(node.tagName) && !node.hasAttribute("autocomplete")) node.setAttribute("autocomplete", "off");
326
+ if (node.type === "checkbox") {
327
+ if (node.value !== "on" && !result) {
328
+ _runCode(`${binding.tpl} = []`, { thisNode: node }, node._thisObj || node, node._ref || {});
329
+ result = [];
330
+ }
331
+ node._checkboxMultiMode = result instanceof Array;
332
+ const isChecked = result instanceof Array ? result.includes(node.value) : !!result;
333
+ if (node.checked !== isChecked) node.checked = isChecked;
334
+ } else if (node.type === "radio") {
335
+ if (node.checked !== (node.value === String(result ?? ""))) node.checked = node.value === String(result ?? "");
336
+ } else if ("value" in node && node.type !== "file") {
337
+ Promise.resolve().then(() => {
338
+ if (node.value !== String(result ?? "")) node.value = result;
339
+ });
340
+ } else if (node.isContentEditable) {
341
+ if (node.innerHTML !== String(result ?? "")) node.innerHTML = result;
342
+ }
343
+ node.dispatchEvent(new CustomEvent("bind", { bubbles: false, detail: result }));
329
344
  } else {
330
- _clearRenderedNodes(node);
331
- if (node._keyedNodes) node._keyedNodes.forEach((nodes) => nodes.forEach((child) => child.remove()));
332
- node._keyedNodes = /* @__PURE__ */ new Map();
333
- node._renderedNodes = [];
334
- }
335
- } else if (attr === "bind") {
336
- if (["INPUT", "SELECT", "TEXTAREA"].includes(node.tagName) && !node.hasAttribute("autocomplete")) node.setAttribute("autocomplete", "off");
337
- if (node.type === "checkbox") {
338
- if (node.value !== "on" && !result) {
339
- _runCode(`${binding.tpl} = []`, { thisNode: node }, node._thisObj || node, node._ref || {});
340
- result = [];
345
+ if (["checked", "disabled", "readonly"].includes(attr)) result = !!result;
346
+ if (typeof result === "boolean") result ? node.setAttribute(attr, "") : node.removeAttribute(attr);
347
+ else if (result !== void 0) {
348
+ if (typeof result !== "string") result = JSON.stringify(result);
349
+ if (attr === "text") node.textContent = result ?? "";
350
+ else if (attr === "html") node.innerHTML = result ?? "";
351
+ else if (node.tagName === "IMG" && attr === "src" && result.includes(".svg")) node.setAttribute("_src", result ?? "");
352
+ else node.setAttribute(attr, result ?? "");
341
353
  }
342
- node._checkboxMultiMode = result instanceof Array;
343
- const isChecked = result instanceof Array ? result.includes(node.value) : !!result;
344
- if (node.checked !== isChecked) node.checked = isChecked;
345
- } else if (node.type === "radio") {
346
- if (node.checked !== (node.value === String(result ?? ""))) node.checked = node.value === String(result ?? "");
347
- } else if ("value" in node && node.type !== "file") {
348
- setTimeout(() => {
349
- if (node.value !== String(result ?? "")) node.value = result;
350
- });
351
- } else if (node.isContentEditable) {
352
- if (node.innerHTML !== String(result ?? "")) node.innerHTML = result;
353
- }
354
- node.dispatchEvent(new CustomEvent("bind", { bubbles: false, detail: result }));
355
- } else {
356
- if (["checked", "disabled", "readonly"].includes(attr)) result = !!result;
357
- if (typeof result === "boolean") result ? node.setAttribute(attr, "") : node.removeAttribute(attr);
358
- else if (result !== void 0) {
359
- if (typeof result !== "string") result = JSON.stringify(result);
360
- if (attr === "text") node.textContent = result ?? "";
361
- else if (attr === "html") node.innerHTML = result ?? "";
362
- else if (node.tagName === "IMG" && attr === "src" && result.includes(".svg")) node.setAttribute("_src", result ?? "");
363
- else node.setAttribute(attr, result ?? "");
364
354
  }
365
355
  }
366
356
  }
367
- }
368
- const _initBinding = (binding) => {
369
- if (!binding.node._bindings) binding.node._bindings = [];
370
- binding.node._bindings.push({ attr: binding.attr, prop: binding.prop, tpl: binding.tpl, exp: binding.exp });
371
- _updateBinding(binding);
372
- };
373
- const _parseNode = (node, scanObj) => {
374
- let hasBindings = false;
375
- if (node._bindings) {
376
- node._states = /* @__PURE__ */ new Set();
377
- node._bindings.forEach((b) => _updateBinding({ node, ...b }));
378
- if (node._hasOnUpdate) node.dispatchEvent(new Event("update", { bubbles: false }));
379
- hasBindings = true;
380
- }
381
- if (Component.exists(node.tagName) && !node._componentInitialized) {
382
- Array.from(node.attributes).forEach((attr) => {
383
- var _a2;
384
- if (attr.name.startsWith("$.")) {
385
- const realAttrName = attr.name.slice(2);
386
- let tpl = _translate(attr.value);
387
- if (tpl.includes("this.")) tpl = tpl.replace(/\bthis\./g, "this.parent.");
388
- const result = _returnCode(tpl, { thisNode: node }, { parent: scanObj.thisObj || node }, node._ref || {});
389
- let o = node;
390
- const prop = realAttrName.split(".");
391
- for (let i = 0; i < prop.length - 1; i++) {
392
- if (prop[i]) o = o[_a2 = prop[i]] ?? (o[_a2] = {});
357
+ const _initBinding = (binding) => {
358
+ if (!binding.node._bindings) binding.node._bindings = [];
359
+ binding.node._bindings.push({ attr: binding.attr, prop: binding.prop, tpl: binding.tpl, exp: binding.exp });
360
+ _updateBinding(binding);
361
+ };
362
+ const _parseNode = (node, scanObj) => {
363
+ if (node._bindings) {
364
+ node._states = /* @__PURE__ */ new Set();
365
+ node._bindings.forEach((b) => _updateBinding({ node, ...b }));
366
+ if (node._hasOnUpdate) node.dispatchEvent(new Event("update", { bubbles: false }));
367
+ return;
368
+ }
369
+ if (Component.exists(node.tagName) && !node._componentInitialized) {
370
+ Array.from(node.attributes).forEach((attr) => {
371
+ var _a2;
372
+ if (attr.name.startsWith("$.")) {
373
+ const realAttrName = attr.name.slice(2);
374
+ let tpl = _translate(attr.value);
375
+ if (tpl.includes("this.")) tpl = tpl.replace(/\bthis\./g, "this.parent.");
376
+ const result = _returnCode(tpl, { thisNode: node }, { parent: scanObj.thisObj || node }, node._ref || {});
377
+ let o = node;
378
+ const prop = realAttrName.split(".");
379
+ for (let i = 0; i < prop.length - 1; i++) {
380
+ if (prop[i]) o = o[_a2 = prop[i]] ?? (o[_a2] = {});
381
+ }
382
+ o[prop[prop.length - 1]] = result;
383
+ node.removeAttribute(attr.name);
393
384
  }
394
- o[prop[prop.length - 1]] = result;
395
- node.removeAttribute(attr.name);
396
- }
397
- });
398
- _makeComponent(node.tagName, node, scanObj);
399
- $$(node, "[slot-id]").forEach((p) => p.removeAttribute("slot-id"));
400
- node._componentInitialized = true;
401
- if (!node._thisObj) node._thisObj = node;
402
- }
403
- if (node.tagName === "TEMPLATE") {
404
- node._children = [...node.content.childNodes];
405
- if (!node._renderedNodes) node._renderedNodes = [];
406
- }
407
- if (hasBindings) return;
408
- let attrs = [];
409
- if (node.tagName === "TEMPLATE") {
410
- ["$if", "$each", "st-if", "st-each"].forEach((n) => node.hasAttribute(n) && attrs.push(node.getAttributeNode(n)));
411
- } else {
412
- 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("."));
413
- }
414
- if (node._thisObj && scanObj.thisObj) node._thisObj.parent = scanObj.thisObj;
415
- if (!node._thisObj) node._thisObj = scanObj.thisObj || null;
416
- if (!node._ref) node._ref = scanObj.extendVars || {};
417
- node._states = /* @__PURE__ */ new Set();
418
- attrs.forEach((attr) => {
419
- const exp = attr.name.startsWith("$") || attr.name.startsWith("st-");
420
- const realAttrName = exp ? attr.name.slice(attr.name.startsWith("$") ? 1 : 3) : attr.name;
421
- let tpl = attr.value;
422
- node.removeAttribute(attr.name);
423
- if (realAttrName.startsWith(".")) _initBinding({ node, prop: realAttrName.split("."), tpl, exp });
424
- else if (realAttrName.startsWith("on")) {
425
- const eventName = realAttrName.slice(2);
426
- if (eventName === "update") node._hasOnUpdate = true;
427
- if (eventName === "load" && !["BODY", "IMG", "IFRAME"].includes(node.tagName)) node._hasOnLoad = true;
428
- if (eventName === "unload" && !["BODY", "IMG", "IFRAME"].includes(node.tagName)) node._hasOnUnload = true;
429
- node.addEventListener(eventName, (e) => _runCode(tpl, { event: e, thisNode: node, ...e.detail || {} }, scanObj.thisObj || node, node._ref || {}));
385
+ });
386
+ _makeComponent(node.tagName, node, scanObj);
387
+ $$(node, "[slot-id]").forEach((p) => p.removeAttribute("slot-id"));
388
+ node._componentInitialized = true;
389
+ if (!node._thisObj) node._thisObj = node;
390
+ }
391
+ if (node.tagName === "TEMPLATE") {
392
+ node._children = [...node.content.childNodes];
393
+ if (!node._renderedNodes) node._renderedNodes = [];
394
+ }
395
+ let attrs = [];
396
+ if (node.tagName === "TEMPLATE") {
397
+ ["$if", "$each", "st-if", "st-each"].forEach((n) => node.hasAttribute(n) && attrs.push(node.getAttributeNode(n)));
430
398
  } else {
431
- if (realAttrName === "bind") {
432
- node.addEventListener(node.tagName === "TEXTAREA" || node.isContentEditable || node.type === "text" || node.type === "password" ? "input" : "change", (e) => {
433
- let newVal = node.isContentEditable ? e.target.innerHTML : node.type === "checkbox" ? e.target.checked : e.target.files || e.target.value || e.detail;
434
- setNoWriteBack(node);
435
- setDisableRunCodeError(true);
436
- if (node.type === "checkbox" && node._checkboxMultiMode) _runCode(`!!checked ? (!${tpl}.includes(val) && ${tpl}.push(val)) : (index = ${tpl}.indexOf(val), index > -1 && ${tpl}.splice(index, 1))`, { val: node.value, checked: newVal, thisNode: node }, scanObj.thisObj || node, node._ref || {});
437
- else _runCode(`${tpl} = val`, { val: newVal, thisNode: node }, scanObj.thisObj || node, node._ref || {});
438
- setDisableRunCodeError(false);
439
- setNoWriteBack(null);
440
- });
441
- } else if (realAttrName === "text" && !tpl) {
442
- tpl = node.textContent;
443
- node.textContent = "";
444
- }
445
- if (tpl) {
446
- tpl = _translate(tpl);
447
- _initBinding({ node, attr: realAttrName, tpl, exp });
448
- }
399
+ 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("."));
449
400
  }
450
- });
451
- if (node._hasOnLoad || node._componentInitialized) Promise.resolve().then(() => node.dispatchEvent(new Event("load", { bubbles: false })));
452
- if (node._hasOnUpdate) node.dispatchEvent(new Event("update", { bubbles: false }));
453
- if (node._thisObj) scanObj.thisObj = node._thisObj;
454
- };
455
- const _scanTree = (node, scanObj = {}) => {
456
- if (node.nodeType === 3) {
457
- if (node._stTranslated) return;
458
- const translated = _translate(node.textContent);
459
- if (translated !== node.textContent) node.textContent = translated;
460
- node._stTranslated = true;
461
- return;
462
- }
463
- if (node.nodeType !== 1) return;
464
- if (!node._stTranslated) {
465
- Array.from(node.attributes).forEach((attr) => {
466
- if (!attr.name.startsWith("$") && !attr.name.startsWith("st-") && !attr.name.startsWith(".")) {
467
- const translated = _translate(attr.value);
468
- if (translated !== attr.value) attr.value = translated;
401
+ if (node._thisObj && scanObj.thisObj) node._thisObj.parent = scanObj.thisObj;
402
+ if (!node._thisObj) node._thisObj = scanObj.thisObj || null;
403
+ if (!node._ref) node._ref = scanObj.extendVars || {};
404
+ node._states = /* @__PURE__ */ new Set();
405
+ attrs.forEach((attr) => {
406
+ let exp = 0;
407
+ if (attr.name.startsWith("$$") || attr.name.startsWith("st-st-")) exp = 2;
408
+ else if (attr.name.startsWith("$") || attr.name.startsWith("st-")) exp = 1;
409
+ const realAttrName = exp === 2 ? attr.name.startsWith("$$") ? attr.name.slice(2) : attr.name.slice(6) : exp === 1 ? attr.name.startsWith("$") ? attr.name.slice(1) : attr.name.slice(3) : attr.name;
410
+ let tpl = attr.value;
411
+ node.removeAttribute(attr.name);
412
+ if (realAttrName.startsWith(".")) _initBinding({ node, prop: realAttrName.split("."), tpl, exp });
413
+ else if (realAttrName.startsWith("on")) {
414
+ const eventName = realAttrName.slice(2);
415
+ if (eventName === "update") node._hasOnUpdate = true;
416
+ if (eventName === "load" && !["BODY", "IMG", "IFRAME"].includes(node.tagName)) node._hasOnLoad = true;
417
+ if (eventName === "unload" && !["BODY", "IMG", "IFRAME"].includes(node.tagName)) node._hasOnUnload = true;
418
+ node.addEventListener(eventName, (e) => _runCode(tpl, { event: e, thisNode: node, ...e.detail || {} }, scanObj.thisObj || node, node._ref || {}));
419
+ } else {
420
+ if (realAttrName === "bind") {
421
+ node.addEventListener(["textarea", "text", "password"].includes(node.type || "text") || node.isContentEditable ? "input" : "change", (e) => {
422
+ let newVal = node.isContentEditable ? e.target.innerHTML : node.type === "checkbox" ? e.target.checked : e.target.files || e.target.value || e.detail;
423
+ _setNoWriteBack(node);
424
+ setDisableRunCodeError(true);
425
+ if (node.type === "checkbox" && node._checkboxMultiMode) _runCode(`!!checked ? (!${tpl}.includes(val) && ${tpl}.push(val)) : (index = ${tpl}.indexOf(val), index > -1 && ${tpl}.splice(index, 1))`, { val: node.value, checked: newVal, thisNode: node }, scanObj.thisObj || node, node._ref || {});
426
+ else _runCode(`${tpl} = val`, { val: newVal, thisNode: node }, scanObj.thisObj || node, node._ref || {});
427
+ setDisableRunCodeError(false);
428
+ _setNoWriteBack(null);
429
+ });
430
+ } else if (realAttrName === "text" && !tpl) {
431
+ tpl = node.textContent;
432
+ node.textContent = "";
433
+ }
434
+ if (tpl) {
435
+ tpl = _translate(tpl);
436
+ _initBinding({ node, attr: realAttrName, tpl, exp });
437
+ }
469
438
  }
470
439
  });
471
- node._stTranslated = true;
472
- }
473
- let resolvedThisObj = node._thisObj;
474
- let resolvedRef = node._ref;
475
- if (resolvedThisObj === void 0 || resolvedRef === void 0) {
476
- let curr = node;
477
- while (curr && (resolvedThisObj === void 0 || resolvedRef === void 0)) {
478
- if (resolvedThisObj === void 0 && curr._thisObj !== void 0) resolvedThisObj = curr._thisObj;
479
- if (resolvedRef === void 0 && curr._ref !== void 0) resolvedRef = { ...curr._ref };
480
- curr = curr.parentNode;
440
+ if (node._hasOnLoad || node._componentInitialized) Promise.resolve().then(() => node.dispatchEvent(new Event("load", { bubbles: false })));
441
+ if (node._hasOnUpdate) node.dispatchEvent(new Event("update", { bubbles: false }));
442
+ if (node._thisObj) scanObj.thisObj = node._thisObj;
443
+ };
444
+ const _scanTree = (node, scanObj = {}) => {
445
+ if (node.nodeType === 3) {
446
+ if (node._stTranslated) return;
447
+ const translated = _translate(node.textContent);
448
+ if (translated !== node.textContent) node.textContent = translated;
449
+ node._stTranslated = true;
450
+ return;
481
451
  }
482
- }
483
- if (resolvedThisObj === void 0) resolvedThisObj = scanObj.thisObj;
484
- if (resolvedRef === void 0) resolvedRef = scanObj.extendVars;
485
- if (node.tagName !== "TEMPLATE" && (node.hasAttribute("$if") || node.hasAttribute("$each") || node.hasAttribute("st-if") || node.hasAttribute("st-each"))) {
486
- const template = document.createElement("TEMPLATE");
487
- const attrs = Array.from(node.attributes).filter((attr) => ["$if", "$each", "st-if", "st-each"].includes(attr.name) || (node.hasAttribute("$each") || node.hasAttribute("st-each")) && ["as", "index"].includes(attr.name));
488
- attrs.forEach((attr) => {
452
+ if (node.nodeType !== 1) return;
453
+ if (!node._stTranslated) {
454
+ Array.from(node.attributes).forEach((attr) => {
455
+ if (!attr.name.startsWith("$") && !attr.name.startsWith("st-") && !attr.name.startsWith(".")) {
456
+ const translated = _translate(attr.value);
457
+ if (translated !== attr.value) attr.value = translated;
458
+ }
459
+ });
460
+ node._stTranslated = true;
461
+ }
462
+ if (node.tagName !== "TEMPLATE" && (node.hasAttribute("$if") || node.hasAttribute("$each") || node.hasAttribute("st-if") || node.hasAttribute("st-each"))) {
463
+ const template = document.createElement("TEMPLATE");
464
+ const attrs = Array.from(node.attributes).filter((attr) => ["$if", "$each", "st-if", "st-each"].includes(attr.name) || (node.hasAttribute("$each") || node.hasAttribute("st-each")) && ["as", "index"].includes(attr.name));
465
+ attrs.forEach((attr) => {
466
+ template.setAttribute(attr.name, attr.value);
467
+ node.removeAttribute(attr.name);
468
+ });
469
+ node.parentNode.insertBefore(template, node);
470
+ template.content.appendChild(node);
471
+ template._ref = node._ref;
472
+ return;
473
+ }
474
+ if (node.tagName === "TEMPLATE" && (node.hasAttribute("$if") || node.hasAttribute("st-if")) && (node.hasAttribute("$each") || node.hasAttribute("st-each"))) {
475
+ const template = document.createElement("TEMPLATE");
476
+ const attrs = Array.from(node.attributes).filter((attr2) => ["$if", "$each", "st-if", "st-each"].includes(attr2.name));
477
+ const attr = attrs[attrs.length - 1];
489
478
  template.setAttribute(attr.name, attr.value);
490
479
  node.removeAttribute(attr.name);
491
- });
492
- node.parentNode.insertBefore(template, node);
493
- template.content.appendChild(node);
494
- template._ref = resolvedRef;
495
- template._thisObj = resolvedThisObj;
496
- _scanTree(template, scanObj);
497
- return;
498
- }
499
- if (node.tagName === "TEMPLATE" && (node.hasAttribute("$if") || node.hasAttribute("st-if")) && (node.hasAttribute("$each") || node.hasAttribute("st-each"))) {
500
- const template = document.createElement("TEMPLATE");
501
- const attrs = Array.from(node.attributes).filter((attr2) => ["$if", "$each", "st-if", "st-each"].includes(attr2.name));
502
- const attr = attrs[attrs.length - 1];
503
- template.setAttribute(attr.name, attr.value);
504
- node.removeAttribute(attr.name);
505
- if (attr.name === "$each" || attr.name === "st-each") {
506
- Array.from(node.attributes).filter((attr2) => ["as", "index"].includes(attr2.name)).forEach((attr2) => {
507
- template.setAttribute(attr2.name, attr2.value);
508
- node.removeAttribute(attr2.name);
480
+ if (attr.name === "$each" || attr.name === "st-each") {
481
+ Array.from(node.attributes).filter((attr2) => ["as", "index"].includes(attr2.name)).forEach((attr2) => {
482
+ template.setAttribute(attr2.name, attr2.value);
483
+ node.removeAttribute(attr2.name);
484
+ });
485
+ }
486
+ Array.from(node.content.childNodes).forEach((child) => template.content.appendChild(child));
487
+ node.content.appendChild(template);
488
+ template._ref = node._ref;
489
+ }
490
+ if (node.tagName === "IMG" && (node.hasAttribute("src") || node.hasAttribute("_src") || node.hasAttribute("$src"))) {
491
+ const imgNode = node;
492
+ Promise.resolve().then(() => {
493
+ const url = imgNode.getAttribute("_src") || imgNode.getAttribute("src");
494
+ if (url) fetch(url, { cache: "force-cache" }).then((r) => r.text()).then((svgText) => {
495
+ const realSvg = new DOMParser().parseFromString(svgText, "image/svg+xml").querySelector("svg");
496
+ if (realSvg) {
497
+ Array.from(imgNode.attributes).forEach((attr) => realSvg.setAttribute(attr.name, attr.value));
498
+ imgNode.replaceWith(realSvg);
499
+ }
500
+ });
509
501
  });
510
502
  }
511
- Array.from(node.content.childNodes).forEach((child) => template.content.appendChild(child));
512
- node.content.appendChild(template);
513
- template._ref = resolvedRef;
514
- template._thisObj = resolvedThisObj;
515
- }
516
- if (node.tagName === "IMG" && (node.hasAttribute("src") || node.hasAttribute("_src") || node.hasAttribute("$src"))) {
517
- const imgNode = node;
518
- Promise.resolve().then(() => {
519
- const url = imgNode.getAttribute("_src") || imgNode.getAttribute("src");
520
- if (url) fetch(url, { cache: "force-cache" }).then((r) => r.text()).then((svgText) => {
521
- const realSvg = new DOMParser().parseFromString(svgText, "image/svg+xml").querySelector("svg");
522
- if (realSvg) {
523
- Array.from(imgNode.attributes).forEach((attr) => realSvg.setAttribute(attr.name, attr.value));
524
- imgNode.replaceWith(realSvg);
503
+ if (node._thisObj !== void 0) scanObj.thisObj = node._thisObj || null;
504
+ else {
505
+ let curr = node;
506
+ while (curr && curr._thisObj === void 0) curr = curr.parentNode;
507
+ scanObj.thisObj = curr ? curr._thisObj : null;
508
+ }
509
+ if (node._ref === void 0) {
510
+ let curr = node;
511
+ while (curr && curr._ref === void 0) curr = curr.parentNode;
512
+ node._ref = curr ? { ...curr._ref } : {};
513
+ }
514
+ if (scanObj.extendVars) Object.assign(node._ref, scanObj.extendVars);
515
+ _parseNode(node, { ...scanObj });
516
+ const nodes = [...node.childNodes || []];
517
+ nodes.forEach((child) => _scanTree(child, { thisObj: scanObj.thisObj, extendVars: { ...node._ref } }));
518
+ };
519
+ const _unbindTree = (node) => {
520
+ if (node.nodeType !== 1) return;
521
+ if (node._hasOnUnload) node.dispatchEvent(new Event("unload", { bubbles: false }));
522
+ if (node._states) node._states.forEach((mappings) => {
523
+ for (const [key, bindingSet] of mappings) {
524
+ for (const binding of bindingSet) {
525
+ if (binding.node === node) bindingSet.delete(binding);
525
526
  }
526
- });
527
+ }
527
528
  });
528
- }
529
- if (node._thisObj !== void 0) scanObj.thisObj = node._thisObj || null;
530
- else {
531
- let curr = node;
532
- while (curr && curr._thisObj === void 0) curr = curr.parentNode;
533
- scanObj.thisObj = curr ? curr._thisObj : null;
534
- }
535
- if (node._ref === void 0) {
536
- let curr = node;
537
- while (curr && curr._ref === void 0) curr = curr.parentNode;
538
- node._ref = curr ? { ...curr._ref } : {};
539
- }
540
- if (node._refExt !== void 0) {
541
- Object.assign(node._ref, node._refExt);
542
- }
543
- if (scanObj.extendVars) Object.assign(node._ref, scanObj.extendVars);
544
- _parseNode(node, { ...scanObj });
545
- const nodes = [...node.childNodes || []];
546
- const nextScanObj = { thisObj: scanObj.thisObj, extendVars: { ...node._ref } };
547
- nodes.forEach((child) => {
548
- if (!child._stManaged) _scanTree(child, nextScanObj);
549
- });
550
- };
551
- const _unbindTree = (node) => {
552
- if (node.nodeType !== 1) return;
553
- if (node._hasOnUnload) node.dispatchEvent(new Event("unload", { bubbles: false }));
554
- if (node._states) node._states.forEach((mappings) => {
555
- for (const [key, bindingSet] of mappings) {
556
- for (const binding of bindingSet) {
557
- if (binding.node === node) bindingSet.delete(binding);
529
+ node.childNodes && node.childNodes.forEach((child) => _unbindTree(child));
530
+ };
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;
558
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
+ };
559
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();
560
599
  });
561
- node.childNodes && node.childNodes.forEach((child) => _unbindTree(child));
562
- };
563
- const RefreshState = _scanTree;
564
- const Util = {
565
- clone: window.structuredClone || ((obj) => JSON.parse(JSON.stringify(obj))),
566
- base64: (str) => btoa(String.fromCharCode(...new TextEncoder().encode(str))),
567
- unbase64: (str) => new TextDecoder().decode(Uint8Array.from(atob(str), (c) => c.charCodeAt(0))),
568
- urlbase64: (str) => Util.base64(str).replace(/[+/=]/g, (m) => ({ "+": "-", "/": "", "=": "" })[m]),
569
- unurlbase64: (str) => Util.unbase64(str.replace(/[-_.]/g, (m) => ({ "-": "+", "_": "/", ".": "=" })[m]).padEnd(Math.ceil(str.length / 4) * 4, "=")),
570
- safeJson: (str) => {
571
- try {
572
- return JSON.parse(str);
573
- } catch {
574
- return null;
575
- }
576
- },
577
- updateDefaults: (obj, defaults) => {
578
- for (const k in defaults) if (obj[k] === void 0) obj[k] = defaults[k];
579
- },
580
- copyFunction: (toObj, fromObj, ...funcNames) => {
581
- funcNames.forEach((name) => toObj[name] = fromObj[name].bind(fromObj));
582
- },
583
- getFunctionBody: (fn) => {
584
- const code = fn.toString();
585
- return code.slice(code.indexOf("{") + 1, code.lastIndexOf("}")).trim();
586
- },
587
- makeDom: (html) => {
588
- if (html.includes(">\n")) html = html.replace(/>\s+</g, "><").trim();
589
- const node = document.createElement("div");
590
- node.innerHTML = html;
591
- return node.children[0];
592
- },
593
- newAvg: () => {
594
- let total = 0, count = 0, avg = 0;
595
- return {
596
- add: (v) => {
597
- total += v;
598
- count++;
599
- return avg = total / count;
600
- },
601
- get: () => avg,
602
- clear: () => {
603
- total = 0, count = 0, avg = 0;
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
+ }
640
+ if (typeof document !== "undefined") {
641
+ const init = () => {
642
+ Component._initPending();
643
+ const htmlNode = document.documentElement;
644
+ if (!htmlNode.hasAttribute("$data-bs-theme") && !htmlNode.hasAttribute("data-bs-theme")) {
645
+ htmlNode.setAttribute("$data-bs-theme", "LocalStorage.darkMode?'dark':'light'");
604
646
  }
647
+ new MutationObserver((mutations) => {
648
+ mutations.forEach((mutation) => {
649
+ mutation.addedNodes.forEach((newNode) => {
650
+ if (newNode.isConnected) _scanTree(newNode);
651
+ });
652
+ mutation.removedNodes.forEach((oldNode) => _unbindTree(oldNode));
653
+ });
654
+ }).observe(document.documentElement, { childList: true, subtree: true });
655
+ _scanTree(document.documentElement);
605
656
  };
606
- },
607
- newTimeCount: () => {
608
- let startTime = 0, total = 0, count = 0;
609
- return {
610
- start: () => startTime = (/* @__PURE__ */ new Date()).getTime(),
611
- end: () => {
612
- const endTime = (/* @__PURE__ */ new Date()).getTime();
613
- const left = endTime - startTime;
614
- startTime = endTime;
615
- total += left;
616
- count++;
617
- return left;
618
- },
619
- avg: () => total / count
620
- };
657
+ if (document.readyState !== "loading") init();
658
+ else document.addEventListener("DOMContentLoaded", init, true);
621
659
  }
622
- };
623
- globalThis.Util = Util;
624
- let _hashParams = new URLSearchParams(((_a = window.location.hash) == null ? void 0 : _a.substring(1)) || "");
625
- const Hash = NewState({}, (k) => Util.safeJson(_hashParams.get(k)), (k, v) => {
626
- const oldStr = _hashParams.get(k);
627
- const newStr = v === void 0 ? void 0 : JSON.stringify(v);
628
- if (oldStr === newStr || oldStr === null && newStr === void 0) return;
629
- v === void 0 ? _hashParams.delete(k) : _hashParams.set(k, newStr);
630
- window.location.hash = "#" + _hashParams.toString();
631
- });
632
- if (typeof window !== "undefined") {
633
- window.addEventListener("hashchange", () => {
634
- var _a2;
635
- const oldHashParams = _hashParams;
636
- _hashParams = new URLSearchParams(((_a2 = window.location.hash) == null ? void 0 : _a2.substring(1)) || "");
637
- _hashParams.forEach((v, k) => {
638
- if (oldHashParams.get(k) !== v) Hash[k] = Util.safeJson(v);
639
- });
640
- oldHashParams.forEach((v, k) => {
641
- if (_hashParams.get(k) === void 0) Hash[k] = void 0;
642
- });
643
- });
644
- }
645
- const LocalStorage = NewState({}, (k) => Util.safeJson(localStorage.getItem(k)), (k, v) => {
646
- const oldStr = localStorage.getItem(k);
647
- const newStr = v === void 0 ? void 0 : JSON.stringify(v);
648
- if (oldStr === newStr || oldStr === null && newStr === void 0) return;
649
- v === void 0 ? localStorage.removeItem(k) : localStorage.setItem(k, newStr);
660
+ exports2.$ = $;
661
+ exports2.$$ = $$;
662
+ exports2.Component = Component;
663
+ exports2.Hash = Hash;
664
+ exports2.LocalStorage = LocalStorage;
665
+ exports2.NewState = NewState;
666
+ exports2.RefreshState = _unsafeRefreshState;
667
+ exports2.SetTranslator = SetTranslator;
668
+ exports2.State = State;
669
+ exports2.Util = Util;
670
+ exports2._scanTree = _scanTree;
671
+ exports2._unbindTree = _unbindTree;
672
+ Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
650
673
  });
651
- globalThis.Hash = Hash;
652
- globalThis.LocalStorage = LocalStorage;
653
- if (typeof document !== "undefined") {
654
- const init = () => {
655
- Component._initPending();
656
- new MutationObserver((mutations) => {
657
- mutations.forEach((mutation) => {
658
- mutation.addedNodes.forEach((newNode) => {
659
- if (newNode.isConnected) _scanTree(newNode);
660
- });
661
- mutation.removedNodes.forEach((oldNode) => _unbindTree(oldNode));
662
- });
663
- }).observe(document.documentElement, { childList: true, subtree: true });
664
- _scanTree(document.documentElement);
665
- };
666
- if (document.readyState !== "loading") init();
667
- else document.addEventListener("DOMContentLoaded", init, true);
668
- }
669
- export {
670
- $,
671
- $$,
672
- Component,
673
- Hash,
674
- LocalStorage,
675
- NewState,
676
- RefreshState,
677
- SetTranslator,
678
- Util,
679
- _scanTree,
680
- _unbindTree
681
- };