@apigo.cc/state 1.0.19 → 1.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/state.js CHANGED
@@ -1,692 +1,662 @@
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
+ to.setAttribute(attr.name, attr.value);
227
+ }
228
+ });
214
229
  }
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());
230
+ to.classList.add(...from.classList);
231
+ const target = to.tagName === "TEMPLATE" ? to.content : to;
232
+ const sourceNodes = from.tagName === "TEMPLATE" ? from.content.childNodes : from.childNodes;
233
+ Array.from(sourceNodes).forEach((child) => target.appendChild(child));
234
+ if (from.tagName && Component.exists(from.tagName)) _makeComponent(from.tagName, to, scanObj, exists);
235
+ }
236
+ function _makeComponent(name, node, scanObj, exists = {}) {
237
+ if (exists[name]) return;
238
+ exists[name] = true;
239
+ if (scanObj.thisObj) {
240
+ Array.from(node.attributes).forEach((attr) => {
241
+ if ((attr.name.startsWith("$") || attr.name.startsWith("st-")) && attr.value.includes("this.")) {
242
+ attr.value = attr.value.replace(/\bthis\./g, "this.parent.");
239
243
  }
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;
244
+ });
245
+ }
246
+ const componentFunc = Component.getSetupFunction(name);
247
+ const slots = {};
248
+ Array.from(node.childNodes).forEach((child) => {
249
+ if (child.nodeType === Node.ELEMENT_NODE && child.hasAttribute("slot")) {
250
+ slots[child.getAttribute("slot")] = child;
251
+ child.removeAttribute("slot");
245
252
  }
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);
253
+ });
254
+ node.innerHTML = "";
255
+ node.state = NewState(node.state || {});
256
+ const template = Component.getTemplate(name);
257
+ if (template) {
258
+ const tplnode = template.content.cloneNode(true);
259
+ if (tplnode.childNodes.length) {
260
+ const rootNode = tplnode.children[0];
261
+ if (rootNode) _mergeNode(rootNode, node, scanObj, exists);
262
+ $$(node, "[slot-id]").forEach((placeholder) => {
263
+ const slotName = placeholder.getAttribute("slot-id");
264
+ if (slots[slotName]) {
265
+ placeholder.removeAttribute("slot-id");
266
+ placeholder.innerHTML = "";
267
+ _mergeNode(slots[slotName], placeholder, scanObj, exists);
257
268
  }
258
269
  });
259
270
  }
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
271
  }
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
- });
272
+ if (componentFunc) componentFunc(node);
273
+ }
274
+ let _translator = (text, args) => {
275
+ if (!text || typeof text !== "string") return text;
276
+ return text.replace(/\{(.+?)\}/g, (match, key) => args.hasOwnProperty(key) ? args[key] : match);
277
+ };
278
+ const SetTranslator = (fn) => _translator = fn;
279
+ const _translate = (text) => {
280
+ if (!text || typeof text !== "string" || !text.includes("{#")) return text;
281
+ return text.replace(/\{#(.+?)#\}/g, (m, content) => {
282
+ const parts = content.split("||").map((s) => s.trim());
283
+ const args = {};
284
+ if (parts.length > 1) {
285
+ const matches = parts[0].match(/\{(.+?)\}/g);
286
+ if (matches) matches.forEach((match, i) => args[match.substring(1, match.length - 1)] = parts[i + 1] || "");
275
287
  }
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);
288
+ return _translator(parts[0], args);
289
+ });
290
+ };
291
+ if (typeof document !== "undefined") {
292
+ try {
293
+ document.createElement("div").setAttribute("$t", "1");
294
+ } catch (e) {
295
+ const originalSetAttribute = Element.prototype.setAttribute;
296
+ Element.prototype.setAttribute = function(name, value) {
297
+ if (!name.startsWith("$")) return originalSetAttribute.call(this, name, value);
298
+ return originalSetAttribute.call(this, "st-" + name.substring(1), value);
299
+ };
303
300
  }
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") {
301
+ }
302
+ _onNotifyUpdate((binding) => _updateBinding(binding));
303
+ function _clearRenderedNodes(node) {
304
+ if (node._renderedNodes) node._renderedNodes.forEach((nodes) => nodes.forEach((child) => {
305
+ child.remove();
306
+ if (child._renderedNodes) _clearRenderedNodes(child);
307
+ }));
308
+ }
309
+ function _updateBinding(binding) {
310
+ const node = binding.node;
311
+ if (!node.isConnected && node.tagName !== "TEMPLATE") return;
312
+ _setActiveBinding(binding);
313
+ let result = binding.exp ? binding.tpl ? _returnCode(binding.tpl, { thisNode: node }, node._thisObj || node, node._ref || null) : null : binding.tpl;
314
+ if (binding.exp === 2 && typeof result === "string") {
322
315
  try {
323
- document.createElement("div").setAttribute("$t", "1");
316
+ result = _returnCode(result, { thisNode: node }, node._thisObj || node, node._ref || null);
324
317
  } 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
318
  }
331
319
  }
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
- }
320
+ _setActiveBinding(null);
321
+ if (binding.prop) {
322
+ const prop = binding.prop;
323
+ let o = node;
324
+ for (let i = 0; i < prop.length - 1; i++) {
325
+ if (!prop[i]) continue;
326
+ if (o[prop[i]] == null) o[prop[i]] = {};
327
+ o = o[prop[i]];
328
+ if (typeof o !== "object") break;
349
329
  }
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;
330
+ if (typeof o === "object" && o !== null) {
331
+ const lk = prop[prop.length - 1];
332
+ if (lk) {
333
+ if (typeof result === "object" && result != null && !Array.isArray(result) && o[lk] == null) o[lk] = {};
334
+ const lo = o[lk];
335
+ if (typeof lo === "object" && lo != null && lo.__watch) Object.assign(lo, result);
336
+ else {
337
+ if (o[lk] !== result) o[lk] = result;
338
+ }
339
+ } else if (typeof result === "object" && result != null && !Array.isArray(result)) {
340
+ Object.assign(o, result);
359
341
  }
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);
342
+ }
343
+ } else if (binding.attr) {
344
+ const attr = binding.attr;
345
+ if (attr === "if") {
346
+ if (result) {
347
+ if (!node._renderedNodes || node._renderedNodes.length === 0) {
348
+ node._children.forEach((child) => {
349
+ node.parentNode.insertBefore(child, node);
350
+ child._ref = { ...node._ref };
351
+ child._thisObj = node._thisObj;
352
+ });
353
+ node._renderedNodes = [node._children];
371
354
  }
355
+ } else {
356
+ _clearRenderedNodes(node);
357
+ node._renderedNodes = [];
372
358
  }
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
- }
359
+ } else if (attr === "each") {
360
+ if (result && typeof result === "object") {
361
+ const asName = node.getAttribute("as") || "item";
362
+ const indexName = node.getAttribute("index") || "index";
363
+ const keyName = node.getAttribute("key");
364
+ let keys, getVal;
365
+ if (result instanceof Map) {
366
+ keys = Array.from(result.keys());
367
+ getVal = (k) => result.get(k);
368
+ } else if (typeof result[Symbol.iterator] === "function") {
369
+ const arr = Array.isArray(result) ? result : Array.from(result);
370
+ keys = new Array(arr.length);
371
+ for (let i = 0; i < arr.length; i++) keys[i] = i;
372
+ getVal = (k) => arr[k];
385
373
  } else {
386
- _clearRenderedNodes(node);
387
- node._renderedNodes = [];
374
+ keys = Object.keys(result);
375
+ getVal = (k) => result[k];
388
376
  }
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];
377
+ if (!node._keyedNodes) node._keyedNodes = /* @__PURE__ */ new Map();
378
+ const newKeyedNodes = /* @__PURE__ */ new Map();
379
+ const currentRenderedNodes = [];
380
+ keys.forEach((k, i) => {
381
+ const item = getVal(k);
382
+ const rawKey = keyName ? item && typeof item === "object" ? item[keyName] : item : k;
383
+ const keyVal = rawKey === void 0 || rawKey === null || newKeyedNodes.has(rawKey) ? `st_key_${i}` : rawKey;
384
+ let existingNodes = node._keyedNodes.get(keyVal);
385
+ if (existingNodes) {
386
+ node._keyedNodes.delete(keyVal);
387
+ existingNodes.forEach((child) => {
388
+ node.parentNode.insertBefore(child, node);
389
+ child._ref[indexName] = k;
390
+ child._ref[asName] = item;
391
+ _scanTree(child);
392
+ });
403
393
  } 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 = [];
394
+ existingNodes = [];
395
+ node._children.forEach((child) => {
396
+ const cloned = child.cloneNode(true);
397
+ cloned._ref = { ...node._ref, [indexName]: k, [asName]: item };
398
+ cloned._thisObj = node._thisObj;
399
+ node.parentNode.insertBefore(cloned, node);
400
+ existingNodes.push(cloned);
401
+ });
451
402
  }
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 }));
403
+ newKeyedNodes.set(keyVal, existingNodes);
404
+ currentRenderedNodes.push(existingNodes);
405
+ });
406
+ node._keyedNodes.forEach((nodes) => nodes.forEach((child) => {
407
+ _clearRenderedNodes(child);
408
+ child.remove();
409
+ }));
410
+ node._keyedNodes = newKeyedNodes;
411
+ node._renderedNodes = currentRenderedNodes;
465
412
  } 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 ?? "");
413
+ _clearRenderedNodes(node);
414
+ node._renderedNodes = [];
415
+ }
416
+ } else if (attr === "bind") {
417
+ if (["INPUT", "SELECT", "TEXTAREA"].includes(node.tagName) && !node.hasAttribute("autocomplete")) node.setAttribute("autocomplete", "off");
418
+ if (node.type === "checkbox") {
419
+ if (node.value !== "on" && !result) {
420
+ _runCode(`${binding.tpl} = []`, { thisNode: node }, node._thisObj || node, node._ref || {});
421
+ result = [];
480
422
  }
423
+ node._checkboxMultiMode = result instanceof Array;
424
+ const isChecked = result instanceof Array ? result.includes(node.value) : !!result;
425
+ if (node.checked !== isChecked) node.checked = isChecked;
426
+ } else if (node.type === "radio") {
427
+ if (node.checked !== (node.value === String(result ?? ""))) node.checked = node.value === String(result ?? "");
428
+ } else if ("value" in node && node.type !== "file") {
429
+ Promise.resolve().then(() => {
430
+ if (node.value !== String(result ?? "")) node.value = result;
431
+ });
432
+ } else if (node.isContentEditable) {
433
+ if (node.innerHTML !== String(result ?? "")) node.innerHTML = result;
434
+ }
435
+ node.dispatchEvent(new CustomEvent("bind", { bubbles: false, detail: result }));
436
+ } else {
437
+ if (["checked", "disabled", "readonly"].includes(attr)) result = !!result;
438
+ if (typeof result === "boolean") result ? node.setAttribute(attr, "") : node.removeAttribute(attr);
439
+ else if (result !== void 0) {
440
+ if (typeof result !== "string") result = JSON.stringify(result);
441
+ if (attr === "text") node.textContent = result ?? "";
442
+ else if (attr === "html") node.innerHTML = result ?? "";
443
+ else if (node.tagName === "IMG" && attr === "src" && result.includes(".svg")) node.setAttribute("_src", result ?? "");
444
+ else node.setAttribute(attr, result ?? "");
481
445
  }
482
446
  }
483
447
  }
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);
448
+ }
449
+ function _initBinding(binding) {
450
+ if (!binding.node._bindings) binding.node._bindings = [];
451
+ binding.node._bindings.push({ attr: binding.attr, prop: binding.prop, tpl: binding.tpl, exp: binding.exp });
452
+ _updateBinding(binding);
453
+ }
454
+ function _parseNode(node, scanObj) {
455
+ if (node._bindings) {
456
+ node._states = /* @__PURE__ */ new Set();
457
+ node._bindings.forEach((b) => _updateBinding({ node, ...b }));
458
+ if (node._hasOnUpdate) node.dispatchEvent(new Event("update", { bubbles: false }));
459
+ return;
488
460
  }
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);
461
+ if (Component.exists(node.tagName) && !node._componentInitialized) {
462
+ Array.from(node.attributes).forEach((attr) => {
463
+ var _a2;
464
+ if (attr.name.startsWith("$.")) {
465
+ const realAttrName = attr.name.slice(2);
466
+ let tpl = _translate(attr.value);
467
+ if (scanObj.thisObj && tpl.includes("this.")) tpl = tpl.replace(/\bthis\./g, "this.parent.");
468
+ const result = _returnCode(tpl, { thisNode: node }, { parent: scanObj.thisObj || node }, node._ref || {});
469
+ let o = node;
470
+ const prop = realAttrName.split(".");
471
+ for (let i = 0; i < prop.length - 1; i++) {
472
+ if (prop[i]) o = o[_a2 = prop[i]] ?? (o[_a2] = {});
511
473
  }
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)));
474
+ o[prop[prop.length - 1]] = result;
475
+ node.removeAttribute(attr.name);
476
+ }
477
+ });
478
+ _makeComponent(node.tagName, node, scanObj);
479
+ $$(node, "[slot-id]").forEach((p) => p.removeAttribute("slot-id"));
480
+ node._componentInitialized = true;
481
+ if (!node._thisObj) node._thisObj = node;
482
+ }
483
+ if (node.tagName === "TEMPLATE") {
484
+ node._children = [...node.content.childNodes];
485
+ if (!node._renderedNodes) node._renderedNodes = [];
486
+ }
487
+ let attrs = [];
488
+ if (node.tagName === "TEMPLATE") {
489
+ ["$if", "$each", "st-if", "st-each"].forEach((n) => node.hasAttribute(n) && attrs.push(node.getAttributeNode(n)));
490
+ } else {
491
+ attrs = Array.from(node.attributes).filter((a) => (a.name.startsWith("$") || a.name.startsWith("st-")) && !["$if", "$each", "st-if", "st-each"].includes(a.name) || a.name.includes("."));
492
+ }
493
+ if (node._thisObj && scanObj.thisObj && node._thisObj !== scanObj.thisObj) node._thisObj.parent = scanObj.thisObj;
494
+ if (!node._thisObj) node._thisObj = scanObj.thisObj || null;
495
+ if (!node._ref) node._ref = scanObj.extendVars || {};
496
+ node._states = /* @__PURE__ */ new Set();
497
+ attrs.forEach((attr) => {
498
+ let exp = 0;
499
+ if (attr.name.startsWith("$$") || attr.name.startsWith("st-st-")) exp = 2;
500
+ else if (attr.name.startsWith("$") || attr.name.startsWith("st-")) exp = 1;
501
+ 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;
502
+ let tpl = attr.value;
503
+ node.removeAttribute(attr.name);
504
+ if (realAttrName.startsWith(".")) _initBinding({ node, prop: realAttrName.split("."), tpl, exp });
505
+ else if (realAttrName.startsWith("on")) {
506
+ const eventName = realAttrName.slice(2);
507
+ if (eventName === "update") node._hasOnUpdate = true;
508
+ if (eventName === "load" && !["BODY", "IMG", "IFRAME"].includes(node.tagName)) node._hasOnLoad = true;
509
+ if (eventName === "unload" && !["BODY", "IMG", "IFRAME"].includes(node.tagName)) node._hasOnUnload = true;
510
+ node.addEventListener(eventName, (e) => _runCode(tpl, { event: e, thisNode: node, ...e.detail || {} }, scanObj.thisObj || node, node._ref || {}));
525
511
  } 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("."));
512
+ if (realAttrName === "bind") {
513
+ const isTextInput = ["INPUT", "TEXTAREA"].includes(node.tagName) && ["textarea", "text", "password", "email", "number", "search", "url", "tel"].includes(node.type || "text") || node.isContentEditable;
514
+ node.addEventListener(isTextInput ? "input" : "change", (e) => {
515
+ let newVal = node.isContentEditable ? e.target.innerHTML : node.type === "checkbox" ? e.target.checked : e.target.files || e.target.value || e.detail;
516
+ _setNoWriteBack(node);
517
+ setDisableRunCodeError(true);
518
+ 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 || {});
519
+ else _runCode(`${tpl} = val`, { val: newVal, thisNode: node }, scanObj.thisObj || node, node._ref || {});
520
+ setDisableRunCodeError(false);
521
+ _setNoWriteBack(null);
522
+ });
523
+ } else if (realAttrName === "text" && !tpl) {
524
+ tpl = node.textContent;
525
+ node.textContent = "";
526
+ }
527
+ if (tpl) {
528
+ tpl = _translate(tpl);
529
+ _initBinding({ node, attr: realAttrName, tpl, exp });
530
+ }
527
531
  }
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
- }
532
+ });
533
+ if (node._hasOnLoad || node._componentInitialized) Promise.resolve().then(() => node.dispatchEvent(new Event("load", { bubbles: false })));
534
+ if (node._hasOnUpdate) node.dispatchEvent(new Event("update", { bubbles: false }));
535
+ if (node._thisObj) scanObj.thisObj = node._thisObj;
536
+ }
537
+ const _scanTree = (node, scanObj = {}) => {
538
+ if (node.nodeType === 3) {
539
+ if (node._stTranslated) return;
540
+ const translated = _translate(node.textContent);
541
+ if (translated !== node.textContent) node.textContent = translated;
542
+ node._stTranslated = true;
543
+ return;
544
+ }
545
+ if (node.nodeType !== 1) return;
546
+ if (!node._stTranslated) {
547
+ Array.from(node.attributes).forEach((attr) => {
548
+ if (!attr.name.startsWith("$") && !attr.name.startsWith("st-") && !attr.name.startsWith(".")) {
549
+ const translated = _translate(attr.value);
550
+ if (translated !== attr.value) attr.value = translated;
565
551
  }
566
552
  });
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;
553
+ node._stTranslated = true;
570
554
  }
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];
555
+ if (node.tagName !== "TEMPLATE" && (node.hasAttribute("$if") || node.hasAttribute("$each") || node.hasAttribute("st-if") || node.hasAttribute("st-each"))) {
556
+ const template = document.createElement("TEMPLATE");
557
+ 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));
558
+ attrs.forEach((attr) => {
605
559
  template.setAttribute(attr.name, attr.value);
606
560
  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
- });
561
+ });
562
+ node.parentNode.insertBefore(template, node);
563
+ template.content.appendChild(node);
564
+ template._ref = node._ref;
565
+ _scanTree(template, scanObj);
566
+ return;
567
+ }
568
+ if (node.tagName === "TEMPLATE" && (node.hasAttribute("$if") || node.hasAttribute("st-if")) && (node.hasAttribute("$each") || node.hasAttribute("st-each"))) {
569
+ const template = document.createElement("TEMPLATE");
570
+ const attrs = Array.from(node.attributes).filter((attr2) => ["$if", "$each", "st-if", "st-each"].includes(attr2.name));
571
+ const attr = attrs[attrs.length - 1];
572
+ template.setAttribute(attr.name, attr.value);
573
+ node.removeAttribute(attr.name);
574
+ if (attr.name === "$each" || attr.name === "st-each") {
575
+ Array.from(node.attributes).filter((attr2) => ["as", "index"].includes(attr2.name)).forEach((attr2) => {
576
+ template.setAttribute(attr2.name, attr2.value);
577
+ node.removeAttribute(attr2.name);
628
578
  });
629
579
  }
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 } }));
580
+ Array.from(node.content.childNodes).forEach((child) => template.content.appendChild(child));
581
+ node.content.appendChild(template);
582
+ template._ref = node._ref;
648
583
  }
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);
584
+ if (node.tagName === "IMG" && (node.hasAttribute("src") || node.hasAttribute("_src") || node.hasAttribute("$src"))) {
585
+ const imgNode = node;
586
+ Promise.resolve().then(() => {
587
+ const url = imgNode.getAttribute("_src") || imgNode.getAttribute("src");
588
+ if (url) fetch(url, { cache: "force-cache" }).then((r) => r.text()).then((svgText) => {
589
+ const realSvg = new DOMParser().parseFromString(svgText, "image/svg+xml").querySelector("svg");
590
+ if (realSvg) {
591
+ Array.from(imgNode.attributes).forEach((attr) => realSvg.setAttribute(attr.name, attr.value));
592
+ imgNode.replaceWith(realSvg);
656
593
  }
657
- }
594
+ });
658
595
  });
659
- node.childNodes && node.childNodes.forEach((child) => _unbindTree(child));
660
596
  }
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'");
597
+ if (node._thisObj !== void 0) scanObj.thisObj = node._thisObj || null;
598
+ else {
599
+ let curr = node;
600
+ while (curr && curr._thisObj === void 0) curr = curr.parentNode;
601
+ scanObj.thisObj = curr ? curr._thisObj : null;
602
+ }
603
+ if (node._ref === void 0) {
604
+ let curr = node;
605
+ while (curr && curr._ref === void 0) curr = curr.parentNode;
606
+ node._ref = curr ? { ...curr._ref } : {};
607
+ }
608
+ if (scanObj.extendVars) Object.assign(node._ref, scanObj.extendVars);
609
+ _parseNode(node, { ...scanObj });
610
+ const nodes = [...node.childNodes || []];
611
+ nodes.forEach((child) => _scanTree(child, { thisObj: scanObj.thisObj, extendVars: { ...node._ref } }));
612
+ };
613
+ const _unbindTree = (node) => {
614
+ if (node.nodeType !== 1) return;
615
+ if (node._hasOnUnload) node.dispatchEvent(new Event("unload", { bubbles: false }));
616
+ if (node._states) node._states.forEach((mappings) => {
617
+ for (const [key, bindingSet] of mappings) {
618
+ for (const binding of bindingSet) {
619
+ if (binding.node === node) bindingSet.delete(binding);
667
620
  }
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
- });
621
+ }
622
+ });
623
+ node.childNodes && node.childNodes.forEach((child) => _unbindTree(child));
624
+ };
625
+ globalThis.Component = Component;
626
+ globalThis.SetTranslator = SetTranslator;
627
+ globalThis.__unsafeRefreshState = _scanTree;
628
+ if (typeof document !== "undefined") {
629
+ const init = () => {
630
+ if (globalThis.Component && globalThis.Component._initPending) {
631
+ globalThis.Component._initPending();
632
+ }
633
+ const htmlNode = document.documentElement;
634
+ if (!htmlNode.hasAttribute("$data-bs-theme") && !htmlNode.hasAttribute("data-bs-theme")) {
635
+ htmlNode.setAttribute("$data-bs-theme", "LocalStorage.darkMode?'dark':'light'");
636
+ }
637
+ new MutationObserver((mutations) => {
638
+ mutations.forEach((mutation) => {
639
+ mutation.addedNodes.forEach((newNode) => {
640
+ if (newNode.isConnected) _scanTree(newNode);
676
641
  });
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);
642
+ mutation.removedNodes.forEach((oldNode) => _unbindTree(oldNode));
643
+ });
644
+ }).observe(document.documentElement, { childList: true, subtree: true });
645
+ _scanTree(document.documentElement);
646
+ };
647
+ if (document.readyState !== "loading") init();
648
+ else document.addEventListener("DOMContentLoaded", init, true);
649
+ }
650
+ const __unsafeRefreshState = _scanTree;
651
+ exports2.$ = $;
652
+ exports2.$$ = $$;
653
+ exports2.Component = Component;
654
+ exports2.Hash = Hash;
655
+ exports2.LocalStorage = LocalStorage;
656
+ exports2.NewState = NewState;
657
+ exports2.SetTranslator = SetTranslator;
658
+ exports2.State = State;
659
+ exports2.Util = Util;
660
+ exports2.__unsafeRefreshState = __unsafeRefreshState;
661
+ Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
692
662
  });