@apigo.cc/state 1.0.19 → 1.0.22

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