@apigo.cc/state 1.0.12 → 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,693 +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;
171
- }
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] || "");
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
+ }
190
154
  }
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
- const prefix = name.startsWith("$$") ? "st-st-" : "st-";
202
- return originalSetAttribute.call(this, prefix + name.substring(name.startsWith("$$") ? 2 : 1), value);
203
- };
155
+ if (componentFunc) componentFunc(node);
204
156
  }
205
- }
206
- onNotifyUpdate((binding) => _updateBinding(binding));
207
- function _clearRenderedNodes(node) {
208
- if (node._renderedNodes) node._renderedNodes.forEach((nodes) => nodes.forEach((child) => {
209
- child.remove();
210
- if (child._renderedNodes) _clearRenderedNodes(child);
211
- }));
212
- }
213
- function _updateBinding(binding) {
214
- const node = binding.node;
215
- if (!node.isConnected && node.tagName !== "TEMPLATE") return;
216
- setActiveBinding(binding);
217
- if (window.__perfTrace) window.__perfTrace.evalCount++;
218
- const evalStart = window.__perfTrace ? performance.now() : 0;
219
- let result = binding.exp ? binding.tpl ? _returnCode(binding.tpl, { thisNode: node }, node._thisObj || node, node._ref || null) : null : binding.tpl;
220
- if (binding.exp === 2 && typeof result === "string") {
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(",");
221
167
  try {
222
- result = _returnCode(result, { thisNode: node }, node._thisObj || node, node._ref || null);
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]);
223
174
  } catch (e) {
175
+ if (!_disableRunCodeError) console.error(e, extendVars, [code, extendVars, vars, thisObj]);
176
+ return null;
224
177
  }
225
178
  }
226
- if (window.__perfTrace) window.__perfTrace.evalTotal += performance.now() - evalStart;
227
- setActiveBinding(null);
228
- if (binding.prop) {
229
- const prop = binding.prop;
230
- let o = node;
231
- for (let i = 0; i < prop.length - 1; i++) {
232
- if (!prop[i]) continue;
233
- if (o[prop[i]] == null) o[prop[i]] = {};
234
- o = o[prop[i]];
235
- 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
+ };
236
209
  }
237
- if (typeof o === "object" && o !== null) {
238
- const lk = prop[prop.length - 1];
239
- if (lk) {
240
- if (typeof result === "object" && result != null && !Array.isArray(result) && o[lk] == null) o[lk] = {};
241
- const lo = o[lk];
242
- if (typeof lo === "object" && lo != null && lo.__watch) Object.assign(lo, result);
243
- else o[lk] = result;
244
- } else if (typeof result === "object" && result != null && !Array.isArray(result)) {
245
- 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) {
246
227
  }
247
228
  }
248
- } else if (binding.attr) {
249
- const attr = binding.attr;
250
- if (attr === "if") {
251
- if (result) {
252
- if (!node._renderedNodes || node._renderedNodes.length === 0) {
253
- node._children.forEach((child) => {
254
- child._stManaged = true;
255
- node.parentNode.insertBefore(child, node);
256
- child._ref = { ...node._ref };
257
- });
258
- node._renderedNodes = [node._children];
259
- } else {
260
- 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);
261
250
  }
262
- } else {
263
- _clearRenderedNodes(node);
264
- node._renderedNodes = [];
265
251
  }
266
- } else if (attr === "each") {
267
- if (result && typeof result === "object") {
268
- const asName = node.getAttribute("as") || "item";
269
- const indexName = node.getAttribute("index") || "index";
270
- const keyName = node.getAttribute("key");
271
- let keys, getVal;
272
- if (result instanceof Map) {
273
- keys = Array.from(result.keys());
274
- getVal = (k) => result.get(k);
275
- } else if (typeof result[Symbol.iterator] === "function") {
276
- const arr = Array.isArray(result) ? result : Array.from(result);
277
- keys = new Array(arr.length);
278
- for (let i = 0; i < arr.length; i++) keys[i] = i;
279
- 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
+ }
280
264
  } else {
281
- keys = Object.keys(result);
282
- getVal = (k) => result[k];
265
+ _clearRenderedNodes(node);
266
+ node._renderedNodes = [];
283
267
  }
284
- if (!node._keyedNodes) node._keyedNodes = /* @__PURE__ */ new Map();
285
- const newKeyedNodes = /* @__PURE__ */ new Map();
286
- const currentRenderedNodes = [];
287
- keys.forEach((k, i) => {
288
- const item = getVal(k);
289
- const rawKey = keyName ? item && typeof item === "object" ? item[keyName] : item : k;
290
- const keyVal = rawKey === void 0 || rawKey === null || newKeyedNodes.has(rawKey) ? `st_key_fallback_${i}_${Math.random()}` : rawKey;
291
- let existingNodes = node._keyedNodes.get(keyVal);
292
- if (existingNodes) {
293
- node._keyedNodes.delete(keyVal);
294
- existingNodes.forEach((child) => {
295
- if (window.__statePerformanceTelemetry) window.__statePerformanceTelemetry.reuseCount++;
296
- let scopeChanged = false;
297
- for (let key in node._ref) {
298
- if (key === asName || key === indexName) continue;
299
- if (child._ref[key] !== node._ref[key]) {
300
- child._ref[key] = node._ref[key];
301
- scopeChanged = true;
302
- }
303
- }
304
- const indexChanged = child._ref[indexName] !== k;
305
- if (indexChanged) child._ref[indexName] = k;
306
- if (child._ref[asName] !== item || scopeChanged) {
307
- child._ref[asName] = item;
308
- if (window.__statePerformanceTelemetry) window.__statePerformanceTelemetry.scanCount++;
309
- _scanTree(child, { thisObj: node._thisObj, extendVars: child._ref });
310
- } else if (node.parentNode.lastChild !== child) {
311
- if (window.__statePerformanceTelemetry) window.__statePerformanceTelemetry.moveCount++;
312
- node.parentNode.insertBefore(child, node);
313
- }
314
- });
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];
315
282
  } else {
316
- existingNodes = [];
317
- node._children.forEach((child) => {
318
- const cloned = child.cloneNode(true);
319
- cloned._stManaged = true;
320
- cloned._ref = { ...node._ref, [indexName]: k, [asName]: item };
321
- cloned._thisObj = node._thisObj;
322
- node.parentNode.insertBefore(cloned, node);
323
- existingNodes.push(cloned);
324
- });
283
+ keys = Object.keys(result);
284
+ getVal = (k) => result[k];
325
285
  }
326
- newKeyedNodes.set(keyVal, existingNodes);
327
- currentRenderedNodes.push(existingNodes);
328
- existingNodes.forEach((child) => node.parentNode.insertBefore(child, node));
329
- });
330
- node._keyedNodes.forEach((nodes) => nodes.forEach((child) => {
331
- _clearRenderedNodes(child);
332
- child.remove();
333
- }));
334
- node._keyedNodes = newKeyedNodes;
335
- 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 }));
336
344
  } else {
337
- _clearRenderedNodes(node);
338
- if (node._keyedNodes) node._keyedNodes.forEach((nodes) => nodes.forEach((child) => child.remove()));
339
- node._keyedNodes = /* @__PURE__ */ new Map();
340
- node._renderedNodes = [];
341
- }
342
- } else if (attr === "bind") {
343
- if (["INPUT", "SELECT", "TEXTAREA"].includes(node.tagName) && !node.hasAttribute("autocomplete")) node.setAttribute("autocomplete", "off");
344
- if (node.type === "checkbox") {
345
- if (node.value !== "on" && !result) {
346
- _runCode(`${binding.tpl} = []`, { thisNode: node }, node._thisObj || node, node._ref || {});
347
- 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 ?? "");
348
353
  }
349
- node._checkboxMultiMode = result instanceof Array;
350
- const isChecked = result instanceof Array ? result.includes(node.value) : !!result;
351
- if (node.checked !== isChecked) node.checked = isChecked;
352
- } else if (node.type === "radio") {
353
- if (node.checked !== (node.value === String(result ?? ""))) node.checked = node.value === String(result ?? "");
354
- } else if ("value" in node && node.type !== "file") {
355
- setTimeout(() => {
356
- if (node.value !== String(result ?? "")) node.value = result;
357
- });
358
- } else if (node.isContentEditable) {
359
- if (node.innerHTML !== String(result ?? "")) node.innerHTML = result;
360
- }
361
- node.dispatchEvent(new CustomEvent("bind", { bubbles: false, detail: result }));
362
- } else {
363
- if (["checked", "disabled", "readonly"].includes(attr)) result = !!result;
364
- if (typeof result === "boolean") result ? node.setAttribute(attr, "") : node.removeAttribute(attr);
365
- else if (result !== void 0) {
366
- if (typeof result !== "string") result = JSON.stringify(result);
367
- if (attr === "text") node.textContent = result ?? "";
368
- else if (attr === "html") node.innerHTML = result ?? "";
369
- else if (node.tagName === "IMG" && attr === "src" && result.includes(".svg")) node.setAttribute("_src", result ?? "");
370
- else node.setAttribute(attr, result ?? "");
371
354
  }
372
355
  }
373
356
  }
374
- }
375
- const _initBinding = (binding) => {
376
- if (!binding.node._bindings) binding.node._bindings = [];
377
- binding.node._bindings.push({ attr: binding.attr, prop: binding.prop, tpl: binding.tpl, exp: binding.exp });
378
- _updateBinding(binding);
379
- };
380
- const _parseNode = (node, scanObj) => {
381
- let hasBindings = false;
382
- if (node._bindings) {
383
- node._states = /* @__PURE__ */ new Set();
384
- node._bindings.forEach((b) => _updateBinding({ node, ...b }));
385
- if (node._hasOnUpdate) node.dispatchEvent(new Event("update", { bubbles: false }));
386
- hasBindings = true;
387
- }
388
- if (Component.exists(node.tagName) && !node._componentInitialized) {
389
- Array.from(node.attributes).forEach((attr) => {
390
- var _a2;
391
- if (attr.name.startsWith("$.")) {
392
- const realAttrName = attr.name.slice(2);
393
- let tpl = _translate(attr.value);
394
- if (tpl.includes("this.")) tpl = tpl.replace(/\bthis\./g, "this.parent.");
395
- const result = _returnCode(tpl, { thisNode: node }, { parent: scanObj.thisObj || node }, node._ref || {});
396
- let o = node;
397
- const prop = realAttrName.split(".");
398
- for (let i = 0; i < prop.length - 1; i++) {
399
- 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);
400
384
  }
401
- o[prop[prop.length - 1]] = result;
402
- node.removeAttribute(attr.name);
403
- }
404
- });
405
- _makeComponent(node.tagName, node, scanObj);
406
- $$(node, "[slot-id]").forEach((p) => p.removeAttribute("slot-id"));
407
- node._componentInitialized = true;
408
- if (!node._thisObj) node._thisObj = node;
409
- }
410
- if (node.tagName === "TEMPLATE") {
411
- node._children = [...node.content.childNodes];
412
- if (!node._renderedNodes) node._renderedNodes = [];
413
- }
414
- if (hasBindings) return;
415
- let attrs = [];
416
- const triggerAttrs = ["$if", "$each", "st-if", "st-each", "$$if", "$$each", "st-st-if", "st-st-each"];
417
- if (node.tagName === "TEMPLATE") {
418
- triggerAttrs.forEach((n) => node.hasAttribute(n) && attrs.push(node.getAttributeNode(n)));
419
- } else {
420
- attrs = Array.from(node.attributes).filter((a) => (a.name.startsWith("$") || a.name.startsWith("st-")) && !triggerAttrs.includes(a.name) || a.name.includes("."));
421
- }
422
- if (node._thisObj && scanObj.thisObj) node._thisObj.parent = scanObj.thisObj;
423
- if (!node._thisObj) node._thisObj = scanObj.thisObj || null;
424
- if (!node._ref) node._ref = scanObj.extendVars || {};
425
- node._states = /* @__PURE__ */ new Set();
426
- attrs.forEach((attr) => {
427
- let exp = 0;
428
- if (attr.name.startsWith("$$") || attr.name.startsWith("st-st-")) exp = 2;
429
- else if (attr.name.startsWith("$") || attr.name.startsWith("st-")) exp = 1;
430
- 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;
431
- let tpl = attr.value;
432
- node.removeAttribute(attr.name);
433
- if (realAttrName.startsWith(".")) _initBinding({ node, prop: realAttrName.split("."), tpl, exp });
434
- else if (realAttrName.startsWith("on")) {
435
- const eventName = realAttrName.slice(2);
436
- if (eventName === "update") node._hasOnUpdate = true;
437
- if (eventName === "load" && !["BODY", "IMG", "IFRAME"].includes(node.tagName)) node._hasOnLoad = true;
438
- if (eventName === "unload" && !["BODY", "IMG", "IFRAME"].includes(node.tagName)) node._hasOnUnload = true;
439
- 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)));
440
398
  } else {
441
- if (realAttrName === "bind") {
442
- node.addEventListener(node.tagName === "TEXTAREA" || node.isContentEditable || node.type === "text" || node.type === "password" ? "input" : "change", (e) => {
443
- let newVal = node.isContentEditable ? e.target.innerHTML : node.type === "checkbox" ? e.target.checked : e.target.files || e.target.value || e.detail;
444
- setNoWriteBack(node);
445
- setDisableRunCodeError(true);
446
- 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 || {});
447
- else _runCode(`${tpl} = val`, { val: newVal, thisNode: node }, scanObj.thisObj || node, node._ref || {});
448
- setDisableRunCodeError(false);
449
- setNoWriteBack(null);
450
- });
451
- } else if (realAttrName === "text" && !tpl) {
452
- tpl = node.textContent;
453
- node.textContent = "";
454
- }
455
- if (tpl) {
456
- tpl = _translate(tpl);
457
- _initBinding({ node, attr: realAttrName, tpl, exp });
458
- }
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("."));
459
400
  }
460
- });
461
- if (node._hasOnLoad || node._componentInitialized) Promise.resolve().then(() => node.dispatchEvent(new Event("load", { bubbles: false })));
462
- if (node._hasOnUpdate) node.dispatchEvent(new Event("update", { bubbles: false }));
463
- if (node._thisObj) scanObj.thisObj = node._thisObj;
464
- };
465
- const _scanTree = (node, scanObj = {}) => {
466
- if (node.nodeType === 3) {
467
- if (node._stTranslated) return;
468
- const translated = _translate(node.textContent);
469
- if (translated !== node.textContent) node.textContent = translated;
470
- node._stTranslated = true;
471
- return;
472
- }
473
- if (node.nodeType !== 1) return;
474
- if (!node._stTranslated) {
475
- Array.from(node.attributes).forEach((attr) => {
476
- if (!attr.name.startsWith("$") && !attr.name.startsWith("st-") && !attr.name.startsWith(".")) {
477
- const translated = _translate(attr.value);
478
- 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
+ }
479
438
  }
480
439
  });
481
- node._stTranslated = true;
482
- }
483
- let resolvedThisObj = node._thisObj;
484
- let resolvedRef = node._ref;
485
- if (resolvedThisObj === void 0 || resolvedRef === void 0) {
486
- let curr = node;
487
- while (curr && (resolvedThisObj === void 0 || resolvedRef === void 0)) {
488
- if (resolvedThisObj === void 0 && curr._thisObj !== void 0) resolvedThisObj = curr._thisObj;
489
- if (resolvedRef === void 0 && curr._ref !== void 0) resolvedRef = { ...curr._ref };
490
- 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;
491
451
  }
492
- }
493
- if (resolvedThisObj === void 0) resolvedThisObj = scanObj.thisObj;
494
- if (resolvedRef === void 0) resolvedRef = scanObj.extendVars;
495
- const triggerAttrs = ["$if", "$each", "st-if", "st-each", "$$if", "$$each", "st-st-if", "st-st-each"];
496
- const eachAttrs = ["$each", "st-each", "$$each", "st-st-each"];
497
- if (node.tagName !== "TEMPLATE" && triggerAttrs.some((t) => node.hasAttribute(t))) {
498
- const template = document.createElement("TEMPLATE");
499
- const attrs = Array.from(node.attributes).filter((attr) => triggerAttrs.includes(attr.name) || eachAttrs.some((t) => node.hasAttribute(t)) && ["as", "index"].includes(attr.name));
500
- 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];
501
478
  template.setAttribute(attr.name, attr.value);
502
479
  node.removeAttribute(attr.name);
503
- });
504
- node.parentNode.insertBefore(template, node);
505
- template.content.appendChild(node);
506
- template._ref = resolvedRef;
507
- template._thisObj = resolvedThisObj;
508
- _scanTree(template, scanObj);
509
- return;
510
- }
511
- if (node.tagName === "TEMPLATE" && (node.hasAttribute("$if") || node.hasAttribute("st-if") || node.hasAttribute("$$if") || node.hasAttribute("st-st-if")) && (node.hasAttribute("$each") || node.hasAttribute("st-each") || node.hasAttribute("$$each") || node.hasAttribute("st-st-each"))) {
512
- const template = document.createElement("TEMPLATE");
513
- const attrs = Array.from(node.attributes).filter((attr2) => triggerAttrs.includes(attr2.name));
514
- const attr = attrs[attrs.length - 1];
515
- template.setAttribute(attr.name, attr.value);
516
- node.removeAttribute(attr.name);
517
- if (eachAttrs.includes(attr.name)) {
518
- Array.from(node.attributes).filter((attr2) => ["as", "index"].includes(attr2.name)).forEach((attr2) => {
519
- template.setAttribute(attr2.name, attr2.value);
520
- 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
+ });
521
501
  });
522
502
  }
523
- Array.from(node.content.childNodes).forEach((child) => template.content.appendChild(child));
524
- node.content.appendChild(template);
525
- template._ref = resolvedRef;
526
- template._thisObj = resolvedThisObj;
527
- }
528
- if (node.tagName === "IMG" && (node.hasAttribute("src") || node.hasAttribute("_src") || node.hasAttribute("$src"))) {
529
- const imgNode = node;
530
- Promise.resolve().then(() => {
531
- const url = imgNode.getAttribute("_src") || imgNode.getAttribute("src");
532
- if (url) fetch(url, { cache: "force-cache" }).then((r) => r.text()).then((svgText) => {
533
- const realSvg = new DOMParser().parseFromString(svgText, "image/svg+xml").querySelector("svg");
534
- if (realSvg) {
535
- Array.from(imgNode.attributes).forEach((attr) => realSvg.setAttribute(attr.name, attr.value));
536
- 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);
537
526
  }
538
- });
527
+ }
539
528
  });
540
- }
541
- if (node._thisObj !== void 0) scanObj.thisObj = node._thisObj || null;
542
- else {
543
- let curr = node;
544
- while (curr && curr._thisObj === void 0) curr = curr.parentNode;
545
- scanObj.thisObj = curr ? curr._thisObj : null;
546
- }
547
- if (node._ref === void 0) {
548
- let curr = node;
549
- while (curr && curr._ref === void 0) curr = curr.parentNode;
550
- node._ref = curr ? { ...curr._ref } : {};
551
- }
552
- if (node._refExt !== void 0) {
553
- Object.assign(node._ref, node._refExt);
554
- }
555
- if (scanObj.extendVars) Object.assign(node._ref, scanObj.extendVars);
556
- _parseNode(node, { ...scanObj });
557
- const nodes = [...node.childNodes || []];
558
- const nextScanObj = { thisObj: scanObj.thisObj, extendVars: { ...node._ref } };
559
- nodes.forEach((child) => {
560
- if (!child._stManaged) _scanTree(child, nextScanObj);
561
- });
562
- };
563
- const _unbindTree = (node) => {
564
- if (node.nodeType !== 1) return;
565
- if (node._hasOnUnload) node.dispatchEvent(new Event("unload", { bubbles: false }));
566
- if (node._states) node._states.forEach((mappings) => {
567
- for (const [key, bindingSet] of mappings) {
568
- for (const binding of bindingSet) {
569
- 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;
570
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
+ };
571
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();
572
599
  });
573
- node.childNodes && node.childNodes.forEach((child) => _unbindTree(child));
574
- };
575
- const RefreshState = _scanTree;
576
- const Util = {
577
- clone: window.structuredClone || ((obj) => JSON.parse(JSON.stringify(obj))),
578
- base64: (str) => btoa(String.fromCharCode(...new TextEncoder().encode(str))),
579
- unbase64: (str) => new TextDecoder().decode(Uint8Array.from(atob(str), (c) => c.charCodeAt(0))),
580
- urlbase64: (str) => Util.base64(str).replace(/[+/=]/g, (m) => ({ "+": "-", "/": "", "=": "" })[m]),
581
- unurlbase64: (str) => Util.unbase64(str.replace(/[-_.]/g, (m) => ({ "-": "+", "_": "/", ".": "=" })[m]).padEnd(Math.ceil(str.length / 4) * 4, "=")),
582
- safeJson: (str) => {
583
- try {
584
- return JSON.parse(str);
585
- } catch {
586
- return null;
587
- }
588
- },
589
- updateDefaults: (obj, defaults) => {
590
- for (const k in defaults) if (obj[k] === void 0) obj[k] = defaults[k];
591
- },
592
- copyFunction: (toObj, fromObj, ...funcNames) => {
593
- funcNames.forEach((name) => toObj[name] = fromObj[name].bind(fromObj));
594
- },
595
- getFunctionBody: (fn) => {
596
- const code = fn.toString();
597
- return code.slice(code.indexOf("{") + 1, code.lastIndexOf("}")).trim();
598
- },
599
- makeDom: (html) => {
600
- if (html.includes(">\n")) html = html.replace(/>\s+</g, "><").trim();
601
- const node = document.createElement("div");
602
- node.innerHTML = html;
603
- return node.children[0];
604
- },
605
- newAvg: () => {
606
- let total = 0, count = 0, avg = 0;
607
- return {
608
- add: (v) => {
609
- total += v;
610
- count++;
611
- return avg = total / count;
612
- },
613
- get: () => avg,
614
- clear: () => {
615
- 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'");
616
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);
617
656
  };
618
- },
619
- newTimeCount: () => {
620
- let startTime = 0, total = 0, count = 0;
621
- return {
622
- start: () => startTime = (/* @__PURE__ */ new Date()).getTime(),
623
- end: () => {
624
- const endTime = (/* @__PURE__ */ new Date()).getTime();
625
- const left = endTime - startTime;
626
- startTime = endTime;
627
- total += left;
628
- count++;
629
- return left;
630
- },
631
- avg: () => total / count
632
- };
657
+ if (document.readyState !== "loading") init();
658
+ else document.addEventListener("DOMContentLoaded", init, true);
633
659
  }
634
- };
635
- globalThis.Util = Util;
636
- let _hashParams = new URLSearchParams(((_a = window.location.hash) == null ? void 0 : _a.substring(1)) || "");
637
- const Hash = NewState({}, (k) => Util.safeJson(_hashParams.get(k)), (k, v) => {
638
- const oldStr = _hashParams.get(k);
639
- const newStr = v === void 0 ? void 0 : JSON.stringify(v);
640
- if (oldStr === newStr || oldStr === null && newStr === void 0) return;
641
- v === void 0 ? _hashParams.delete(k) : _hashParams.set(k, newStr);
642
- window.location.hash = "#" + _hashParams.toString();
643
- });
644
- if (typeof window !== "undefined") {
645
- window.addEventListener("hashchange", () => {
646
- var _a2;
647
- const oldHashParams = _hashParams;
648
- _hashParams = new URLSearchParams(((_a2 = window.location.hash) == null ? void 0 : _a2.substring(1)) || "");
649
- _hashParams.forEach((v, k) => {
650
- if (oldHashParams.get(k) !== v) Hash[k] = Util.safeJson(v);
651
- });
652
- oldHashParams.forEach((v, k) => {
653
- if (_hashParams.get(k) === void 0) Hash[k] = void 0;
654
- });
655
- });
656
- }
657
- const LocalStorage = NewState({}, (k) => Util.safeJson(localStorage.getItem(k)), (k, v) => {
658
- const oldStr = localStorage.getItem(k);
659
- const newStr = v === void 0 ? void 0 : JSON.stringify(v);
660
- if (oldStr === newStr || oldStr === null && newStr === void 0) return;
661
- 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" });
662
673
  });
663
- globalThis.Hash = Hash;
664
- globalThis.LocalStorage = LocalStorage;
665
- if (typeof document !== "undefined") {
666
- const init = () => {
667
- Component._initPending();
668
- new MutationObserver((mutations) => {
669
- mutations.forEach((mutation) => {
670
- mutation.addedNodes.forEach((newNode) => {
671
- if (newNode.isConnected) _scanTree(newNode);
672
- });
673
- mutation.removedNodes.forEach((oldNode) => _unbindTree(oldNode));
674
- });
675
- }).observe(document.documentElement, { childList: true, subtree: true });
676
- _scanTree(document.documentElement);
677
- };
678
- if (document.readyState !== "loading") init();
679
- else document.addEventListener("DOMContentLoaded", init, true);
680
- }
681
- export {
682
- $,
683
- $$,
684
- Component,
685
- Hash,
686
- LocalStorage,
687
- NewState,
688
- RefreshState,
689
- SetTranslator,
690
- Util,
691
- _scanTree,
692
- _unbindTree
693
- };