chore: release state v1.0.10 with critical bug fixes

This commit is contained in:
AI Engineer 2026-05-19 07:17:00 +08:00
parent 33f72ddb61
commit d688483f5a
6 changed files with 159 additions and 268 deletions

View File

@ -1,5 +1,12 @@
# CHANGELOG # CHANGELOG
## v1.0.10 (2026-05-18)
### 修复
- **生命周期**: 修复了 `onunload` 监听器因字符串匹配错误导致的失效问题。
- **插槽合并**: 修复了 `_mergeNode` 在处理 `TEMPLATE` 节点时未正确指向 `.content` 的问题。
- **架构对齐**: 恢复了 `_parseNode` 的原始执行顺序,确保组件初始化与属性绑定时序的绝对安全性。
## v1.0.9 (2026-05-18) ## v1.0.9 (2026-05-18)
### 修复 ### 修复

196
dist/state.js vendored
View File

@ -105,7 +105,9 @@ function _mergeNode(from, to, scanObj, exists = {}) {
}); });
} }
to.classList.add(...from.classList); to.classList.add(...from.classList);
Array.from(from.childNodes).forEach((child) => to.appendChild(child)); const fromContent = from.tagName === "TEMPLATE" ? from.content : from;
const toContent = to.tagName === "TEMPLATE" ? to.content : to;
Array.from(fromContent.childNodes).forEach((child) => toContent.appendChild(child));
if (from.tagName && Component.exists(from.tagName)) _makeComponent(from.tagName, to, scanObj, exists); if (from.tagName && Component.exists(from.tagName)) _makeComponent(from.tagName, to, scanObj, exists);
} }
function _makeComponent(name, node, scanObj, exists = {}) { function _makeComponent(name, node, scanObj, exists = {}) {
@ -174,25 +176,19 @@ function _returnCode(code, vars, thisObj, extendVars) {
} }
let _translator = (text, args) => { let _translator = (text, args) => {
if (!text || typeof text !== "string") return text; if (!text || typeof text !== "string") return text;
return text.replace(/\{(.+?)\}/g, (match, key) => { return text.replace(/\{(.+?)\}/g, (match, key) => args.hasOwnProperty(key) ? args[key] : match);
return args.hasOwnProperty(key) ? args[key] : match;
});
}; };
const SetTranslator = (fn) => _translator = fn; const SetTranslator = (fn) => _translator = fn;
const _translate = (text) => { const _translate = (text) => {
if (!text || typeof text !== "string" || !text.includes("{#")) return text; if (!text || typeof text !== "string" || !text.includes("{#")) return text;
return text.replace(/\{#(.+?)#\}/g, (m, content) => { return text.replace(/\{#(.+?)#\}/g, (m, content) => {
const parts = content.split("||").map((s) => s.trim()); const parts = content.split("||").map((s) => s.trim());
const rawText = parts[0];
const args = {}; const args = {};
if (parts.length > 1) { if (parts.length > 1) {
const matches = rawText.match(/\{(.+?)\}/g); const matches = parts[0].match(/\{(.+?)\}/g);
if (matches) matches.forEach((match, i) => { if (matches) matches.forEach((match, i) => args[match.substring(1, match.length - 1)] = parts[i + 1] || "");
const key = match.substring(1, match.length - 1);
args[key] = parts[i + 1] || "";
});
} }
return _translator(rawText, args); return _translator(parts[0], args);
}); });
}; };
if (typeof document !== "undefined") { if (typeof document !== "undefined") {
@ -208,19 +204,16 @@ if (typeof document !== "undefined") {
} }
onNotifyUpdate((binding) => _updateBinding(binding)); onNotifyUpdate((binding) => _updateBinding(binding));
function _clearRenderedNodes(node) { function _clearRenderedNodes(node) {
if (node._renderedNodes) node._renderedNodes.forEach((nodes) => { if (node._renderedNodes) node._renderedNodes.forEach((nodes) => nodes.forEach((child) => {
nodes.forEach((child) => { child.remove();
child.remove(); if (child._renderedNodes) _clearRenderedNodes(child);
if (child._renderedNodes) _clearRenderedNodes(child); }));
});
});
} }
function _updateBinding(binding) { function _updateBinding(binding) {
const node = binding.node; const node = binding.node;
const tpl = binding.tpl; if (!node.isConnected && node.tagName !== "TEMPLATE") return;
const exp = binding.exp;
setActiveBinding(binding); setActiveBinding(binding);
let result = exp ? tpl ? _returnCode(tpl, { thisNode: node }, node._thisObj || node, node._ref || null) : null : tpl; let result = binding.exp ? binding.tpl ? _returnCode(binding.tpl, { thisNode: node }, node._thisObj || node, node._ref || null) : null : binding.tpl;
setActiveBinding(null); setActiveBinding(null);
if (binding.prop) { if (binding.prop) {
const prop = binding.prop; const prop = binding.prop;
@ -232,14 +225,13 @@ function _updateBinding(binding) {
if (typeof o !== "object") break; if (typeof o !== "object") break;
} }
if (typeof o === "object" && o !== null) { if (typeof o === "object" && o !== null) {
const resultIsObject = typeof result === "object" && result != null && !Array.isArray(result);
const lk = prop[prop.length - 1]; const lk = prop[prop.length - 1];
if (lk) { if (lk) {
if (resultIsObject && o[lk] == null) o[lk] = {}; if (typeof result === "object" && result != null && !Array.isArray(result) && o[lk] == null) o[lk] = {};
const lo = o[lk]; const lo = o[lk];
if (typeof lo === "object" && lo != null && lo.__watch) Object.assign(lo, result); if (typeof lo === "object" && lo != null && lo.__watch) Object.assign(lo, result);
else o[lk] = result; else o[lk] = result;
} else if (resultIsObject && typeof o === "object") { } else if (typeof result === "object" && result != null && !Array.isArray(result)) {
Object.assign(o, result); Object.assign(o, result);
} }
} }
@ -288,9 +280,7 @@ function _updateBinding(binding) {
if (!node._renderedNodes) node._renderedNodes = []; if (!node._renderedNodes) node._renderedNodes = [];
node._children.forEach((child) => { node._children.forEach((child) => {
const cloned = child.cloneNode(true); const cloned = child.cloneNode(true);
cloned._ref = { ...node._ref }; cloned._ref = { ...node._ref, [indexName]: k, [asName]: item };
cloned._ref[indexName] = k;
cloned._ref[asName] = item;
cloned._thisObj = node._thisObj; cloned._thisObj = node._thisObj;
node.parentNode.insertBefore(cloned, node); node.parentNode.insertBefore(cloned, node);
newNodes.push(cloned); newNodes.push(cloned);
@ -299,23 +289,20 @@ function _updateBinding(binding) {
} }
}); });
while (node._renderedNodes && node._renderedNodes.length > keys.length) { while (node._renderedNodes && node._renderedNodes.length > keys.length) {
node._renderedNodes[node._renderedNodes.length - 1].forEach((child) => { node._renderedNodes.pop().forEach((child) => {
_clearRenderedNodes(child); _clearRenderedNodes(child);
child.remove(); child.remove();
}); });
node._renderedNodes.pop();
} }
} else { } else {
_clearRenderedNodes(node); _clearRenderedNodes(node);
node._renderedNodes = []; node._renderedNodes = [];
} }
} else if (attr === "bind") { } else if (attr === "bind") {
if (["INPUT", "SELECT", "TEXTAREA"].includes(node.tagName)) { if (["INPUT", "SELECT", "TEXTAREA"].includes(node.tagName) && !node.hasAttribute("autocomplete")) node.setAttribute("autocomplete", "off");
if (!node.hasAttribute("autocomplete")) node.setAttribute("autocomplete", "off");
}
if (node.type === "checkbox") { if (node.type === "checkbox") {
if (node.value !== "on" && !result) { if (node.value !== "on" && !result) {
_runCode(`${tpl} = []`, { thisNode: node }, node._thisObj || node, node._ref || {}); _runCode(`${binding.tpl} = []`, { thisNode: node }, node._thisObj || node, node._ref || {});
result = []; result = [];
} }
node._checkboxMultiMode = result instanceof Array; node._checkboxMultiMode = result instanceof Array;
@ -333,19 +320,13 @@ function _updateBinding(binding) {
node.dispatchEvent(new CustomEvent("bind", { bubbles: false, detail: result })); node.dispatchEvent(new CustomEvent("bind", { bubbles: false, detail: result }));
} else { } else {
if (["checked", "disabled", "readonly"].includes(attr)) result = !!result; if (["checked", "disabled", "readonly"].includes(attr)) result = !!result;
if (typeof result === "boolean") { if (typeof result === "boolean") result ? node.setAttribute(attr, "") : node.removeAttribute(attr);
result ? node.setAttribute(attr, "") : node.removeAttribute(attr); else if (result !== void 0) {
} else if (result !== void 0) {
if (typeof result !== "string") result = JSON.stringify(result); if (typeof result !== "string") result = JSON.stringify(result);
if (attr === "text") { if (attr === "text") node.textContent = result ?? "";
node.textContent = result ?? ""; else if (attr === "html") node.innerHTML = result ?? "";
} else if (attr === "html") { else if (node.tagName === "IMG" && attr === "src" && result.includes(".svg")) node.setAttribute("_src", result ?? "");
node.innerHTML = result ?? ""; else node.setAttribute(attr, result ?? "");
} else if (node.tagName === "IMG" && attr === "src" && result.includes(".svg")) {
node.setAttribute("_src", result ?? "");
} else {
node.setAttribute(attr, result ?? "");
}
} }
} }
} }
@ -356,49 +337,45 @@ const _initBinding = (binding) => {
_updateBinding(binding); _updateBinding(binding);
}; };
const _parseNode = (node, scanObj) => { const _parseNode = (node, scanObj) => {
let hasBindings = false;
if (node._bindings) { if (node._bindings) {
node._states = /* @__PURE__ */ new Set(); node._states = /* @__PURE__ */ new Set();
node._bindings.forEach((bindingData) => { node._bindings.forEach((b) => _updateBinding({ node, ...b }));
const binding = { node, ...bindingData };
_updateBinding(binding);
});
if (node._hasOnUpdate) node.dispatchEvent(new Event("update", { bubbles: false })); if (node._hasOnUpdate) node.dispatchEvent(new Event("update", { bubbles: false }));
return; hasBindings = true;
} }
if (Component.exists(node.tagName) && !node._componentInitialized) { if (Component.exists(node.tagName) && !node._componentInitialized) {
Array.from(node.attributes).forEach((attr) => { Array.from(node.attributes).forEach((attr) => {
var _a2;
if (attr.name.startsWith("$.")) { if (attr.name.startsWith("$.")) {
const realAttrName = attr.name.slice(2); const realAttrName = attr.name.slice(2);
let tpl = attr.value; let tpl = _translate(attr.value);
if (tpl.includes("this.")) tpl = tpl.replace(/\bthis\./g, "this.parent."); if (tpl.includes("this.")) tpl = tpl.replace(/\bthis\./g, "this.parent.");
tpl = _translate(tpl);
const result = _returnCode(tpl, { thisNode: node }, { parent: scanObj.thisObj || node }, node._ref || {}); const result = _returnCode(tpl, { thisNode: node }, { parent: scanObj.thisObj || node }, node._ref || {});
let o = node; let o = node;
const prop = realAttrName.split("."); const prop = realAttrName.split(".");
for (let i = 0; i < prop.length - 1; i++) { for (let i = 0; i < prop.length - 1; i++) {
if (!prop[i]) continue; if (prop[i]) o = o[_a2 = prop[i]] ?? (o[_a2] = {});
if (o[prop[i]] == null) o[prop[i]] = {};
o = o[prop[i]];
} }
o[prop[prop.length - 1]] = result; o[prop[prop.length - 1]] = result;
node.removeAttribute(attr.name); node.removeAttribute(attr.name);
} }
}); });
_makeComponent(node.tagName, node, scanObj); _makeComponent(node.tagName, node, scanObj);
$$(node, "[slot-id]").forEach((placeholder) => placeholder.removeAttribute("slot-id")); $$(node, "[slot-id]").forEach((p) => p.removeAttribute("slot-id"));
node._componentInitialized = true; node._componentInitialized = true;
if (!node._thisObj) node._thisObj = node; if (!node._thisObj) node._thisObj = node;
} }
let attrs = [];
if (node.tagName === "TEMPLATE") { if (node.tagName === "TEMPLATE") {
node._children = [...node.content.childNodes]; node._children = [...node.content.childNodes];
node._renderedNodes = []; if (!node._renderedNodes) node._renderedNodes = [];
if (node.hasAttribute("$if")) attrs.push(node.getAttributeNode("$if")); }
else if (node.hasAttribute("$each")) attrs.push(node.getAttributeNode("$each")); if (hasBindings) return;
else if (node.hasAttribute("st-if")) attrs.push(node.getAttributeNode("st-if")); let attrs = [];
else if (node.hasAttribute("st-each")) attrs.push(node.getAttributeNode("st-each")); if (node.tagName === "TEMPLATE") {
["$if", "$each", "st-if", "st-each"].forEach((n) => node.hasAttribute(n) && attrs.push(node.getAttributeNode(n)));
} else { } else {
attrs = Array.from(node.attributes).filter((attr) => (attr.name.startsWith("$") || attr.name.startsWith("st-")) && !["$if", "$each", "st-if", "st-each"].includes(attr.name) || attr.name.includes(".")); 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("."));
} }
if (node._thisObj && scanObj.thisObj) node._thisObj.parent = scanObj.thisObj; if (node._thisObj && scanObj.thisObj) node._thisObj.parent = scanObj.thisObj;
if (!node._thisObj) node._thisObj = scanObj.thisObj || null; if (!node._thisObj) node._thisObj = scanObj.thisObj || null;
@ -409,49 +386,35 @@ const _parseNode = (node, scanObj) => {
const realAttrName = exp ? attr.name.slice(attr.name.startsWith("$") ? 1 : 3) : attr.name; const realAttrName = exp ? attr.name.slice(attr.name.startsWith("$") ? 1 : 3) : attr.name;
let tpl = attr.value; let tpl = attr.value;
node.removeAttribute(attr.name); node.removeAttribute(attr.name);
if (realAttrName.startsWith(".")) { if (realAttrName.startsWith(".")) _initBinding({ node, prop: realAttrName.split("."), tpl, exp });
_initBinding({ node, prop: realAttrName.split("."), tpl, exp }); else if (realAttrName.startsWith("on")) {
const eventName = realAttrName.slice(2);
if (eventName === "update") node._hasOnUpdate = true;
if (eventName === "load" && !["BODY", "IMG", "IFRAME"].includes(node.tagName)) node._hasOnLoad = true;
if (eventName === "unload" && !["BODY", "IMG", "IFRAME"].includes(node.tagName)) node._hasOnUnload = true;
node.addEventListener(eventName, (e) => _runCode(tpl, { event: e, thisNode: node, ...e.detail || {} }, scanObj.thisObj || node, node._ref || {}));
} else { } else {
if (realAttrName.startsWith("on")) { if (realAttrName === "bind") {
const eventName = realAttrName.slice(2); node.addEventListener(node.tagName === "TEXTAREA" || node.isContentEditable || node.type === "text" || node.type === "password" ? "input" : "change", (e) => {
if (eventName === "update") node._hasOnUpdate = true; let newVal = node.isContentEditable ? e.target.innerHTML : node.type === "checkbox" ? e.target.checked : e.target.files || e.target.value || e.detail;
if (eventName === "load" && !["BODY", "IMG", "IFRAME"].includes(node.tagName)) node._hasOnLoad = true; setNoWriteBack(node);
if (eventName === "unload" && !["BODY", "IMG", "IFRAME"].includes(node.tagName)) node._hasOnUnload = true; setDisableRunCodeError(true);
((node2, thisObj) => { 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 || {});
node2.addEventListener(eventName, (e) => { else _runCode(`${tpl} = val`, { val: newVal, thisNode: node }, scanObj.thisObj || node, node._ref || {});
_runCode(tpl, { event: e, thisNode: node2, ...e.detail || {} }, thisObj || node2, node2._ref || {}); setDisableRunCodeError(false);
}); setNoWriteBack(null);
})(node, scanObj.thisObj); });
} else { } else if (realAttrName === "text" && !tpl) {
if (realAttrName === "bind") { tpl = node.textContent;
node.addEventListener(node.tagName === "TEXTAREA" || node.isContentEditable || node.type === "text" || node.type === "password" ? "input" : "change", (e) => { node.textContent = "";
let newVal = node.isContentEditable ? e.target.innerHTML : node.type === "checkbox" ? e.target.checked : e.target.files || e.target.value || e.detail; }
setNoWriteBack(node); if (tpl) {
setDisableRunCodeError(true); tpl = _translate(tpl);
if (node.type === "checkbox" && node._checkboxMultiMode) { _initBinding({ node, attr: realAttrName, tpl, exp });
_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 || {});
} else {
_runCode(`${tpl} = val`, { val: newVal, thisNode: node }, scanObj.thisObj || node, node._ref || {});
}
setDisableRunCodeError(false);
setNoWriteBack(null);
});
} else if (realAttrName === "text" && !tpl) {
tpl = node.textContent;
node.textContent = "";
}
if (tpl) {
tpl = _translate(tpl);
_initBinding({ node, attr: realAttrName, tpl, exp });
}
} }
} }
}); });
if (node._hasOnLoad || node._componentInitialized) { if (node._hasOnLoad || node._componentInitialized) Promise.resolve().then(() => node.dispatchEvent(new Event("load", { bubbles: false })));
((node2) => {
Promise.resolve().then(() => node2.dispatchEvent(new Event("load", { bubbles: false })));
})(node);
}
if (node._hasOnUpdate) node.dispatchEvent(new Event("update", { bubbles: false })); if (node._hasOnUpdate) node.dispatchEvent(new Event("update", { bubbles: false }));
if (node._thisObj) scanObj.thisObj = node._thisObj; if (node._thisObj) scanObj.thisObj = node._thisObj;
}; };
@ -483,7 +446,6 @@ const _scanTree = (node, scanObj = {}) => {
node.parentNode.insertBefore(template, node); node.parentNode.insertBefore(template, node);
template.content.appendChild(node); template.content.appendChild(node);
template._ref = node._ref; template._ref = node._ref;
node = template;
return; return;
} }
if (node.tagName === "TEMPLATE" && (node.hasAttribute("$if") || node.hasAttribute("st-if")) && (node.hasAttribute("$each") || node.hasAttribute("st-each"))) { if (node.tagName === "TEMPLATE" && (node.hasAttribute("$if") || node.hasAttribute("st-if")) && (node.hasAttribute("$each") || node.hasAttribute("st-each"))) {
@ -498,9 +460,7 @@ const _scanTree = (node, scanObj = {}) => {
node.removeAttribute(attr2.name); node.removeAttribute(attr2.name);
}); });
} }
Array.from(node.content.childNodes).forEach((child) => { Array.from(node.content.childNodes).forEach((child) => template.content.appendChild(child));
template.content.appendChild(child);
});
node.content.appendChild(template); node.content.appendChild(template);
template._ref = node._ref; template._ref = node._ref;
} }
@ -518,7 +478,7 @@ const _scanTree = (node, scanObj = {}) => {
}); });
} }
if (node._thisObj !== void 0) scanObj.thisObj = node._thisObj || null; if (node._thisObj !== void 0) scanObj.thisObj = node._thisObj || null;
if (scanObj.thisObj === void 0) { else {
let curr = node; let curr = node;
while (curr && curr._thisObj === void 0) curr = curr.parentNode; while (curr && curr._thisObj === void 0) curr = curr.parentNode;
scanObj.thisObj = curr ? curr._thisObj : null; scanObj.thisObj = curr ? curr._thisObj : null;
@ -528,28 +488,22 @@ const _scanTree = (node, scanObj = {}) => {
while (curr && curr._ref === void 0) curr = curr.parentNode; while (curr && curr._ref === void 0) curr = curr.parentNode;
node._ref = curr ? { ...curr._ref } : {}; node._ref = curr ? { ...curr._ref } : {};
} }
if (scanObj.extendVars === void 0) scanObj.extendVars = {}; if (scanObj.extendVars) Object.assign(node._ref, scanObj.extendVars);
if (node._ref !== void 0) {
Object.assign(node._ref, scanObj.extendVars);
scanObj.extendVars = { ...node._ref };
}
_parseNode(node, scanObj); _parseNode(node, scanObj);
const nodes = [...node.childNodes || []]; const nodes = [...node.childNodes || []];
scanObj.extendVars = node._ref || scanObj.extendVars; const nextScanObj = { thisObj: scanObj.thisObj, extendVars: { ...node._ref } };
nodes.forEach((child) => _scanTree(child, { thisObj: scanObj.thisObj, extendVars: { ...node._ref } })); nodes.forEach((child) => _scanTree(child, nextScanObj));
}; };
const _unbindTree = (node) => { const _unbindTree = (node) => {
if (node.nodeType !== 1) return; if (node.nodeType !== 1) return;
if (node._hasOnUnload) node.dispatchEvent(new Event("unload", { bubbles: false })); if (node._hasOnUnload) node.dispatchEvent(new Event("unload", { bubbles: false }));
if (node._states) { if (node._states) node._states.forEach((mappings) => {
node._states.forEach((stateMappings) => { for (const [key, bindingSet] of mappings) {
for (const [key, bindingSet] of stateMappings) { for (const binding of bindingSet) {
for (const binding of bindingSet) { if (binding.node === node) bindingSet.delete(binding);
if (binding.node === node) bindingSet.delete(binding);
}
} }
}); }
} });
node.childNodes && node.childNodes.forEach((child) => _unbindTree(child)); node.childNodes && node.childNodes.forEach((child) => _unbindTree(child));
}; };
const RefreshState = _scanTree; const RefreshState = _scanTree;

2
dist/state.min.js vendored

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,6 @@
{ {
"name": "@web/state", "name": "@web/state",
"version": "1.0.9", "version": "1.0.10",
"type": "module", "type": "module",
"main": "dist/state.js", "main": "dist/state.js",

View File

@ -42,7 +42,9 @@ export function _mergeNode(from, to, scanObj, exists = {}) {
}); });
} }
to.classList.add(...from.classList); to.classList.add(...from.classList);
Array.from(from.childNodes).forEach(child => to.appendChild(child)); const fromContent = from.tagName === 'TEMPLATE' ? from.content : from;
const toContent = to.tagName === 'TEMPLATE' ? to.content : to;
Array.from(fromContent.childNodes).forEach(child => toContent.appendChild(child));
if (from.tagName && Component.exists(from.tagName)) _makeComponent(from.tagName, to, scanObj, exists); if (from.tagName && Component.exists(from.tagName)) _makeComponent(from.tagName, to, scanObj, exists);
} }

View File

@ -6,9 +6,7 @@ import { $, $$ } from './dom-utils.js';
let _translator = (text, args) => { let _translator = (text, args) => {
if (!text || typeof text !== 'string') return text; if (!text || typeof text !== 'string') return text;
return text.replace(/\{(.+?)\}/g, (match, key) => { return text.replace(/\{(.+?)\}/g, (match, key) => args.hasOwnProperty(key) ? args[key] : match);
return args.hasOwnProperty(key) ? args[key] : match;
})
}; };
export const SetTranslator = (fn) => _translator = fn; export const SetTranslator = (fn) => _translator = fn;
@ -16,23 +14,17 @@ const _translate = (text) => {
if (!text || typeof text !== 'string' || !text.includes('{#')) return text; if (!text || typeof text !== 'string' || !text.includes('{#')) return text;
return text.replace(/\{#(.+?)#\}/g, (m, content) => { return text.replace(/\{#(.+?)#\}/g, (m, content) => {
const parts = content.split('||').map(s => s.trim()); const parts = content.split('||').map(s => s.trim());
const rawText = parts[0];
const args = {}; const args = {};
if (parts.length > 1) { if (parts.length > 1) {
const matches = rawText.match(/\{(.+?)\}/g); const matches = parts[0].match(/\{(.+?)\}/g);
if (matches) matches.forEach((match, i) => { if (matches) matches.forEach((match, i) => args[match.substring(1, match.length - 1)] = parts[i + 1] || '');
const key = match.substring(1, match.length - 1);
args[key] = parts[i + 1] || '';
});
} }
return _translator(rawText, args); return _translator(parts[0], args);
}); });
}; };
if (typeof document !== 'undefined') { if (typeof document !== 'undefined') {
try { try { document.createElement('div').setAttribute('$t', '1'); } catch (e) {
document.createElement('div').setAttribute('$t', '1');
} catch (e) {
const originalSetAttribute = Element.prototype.setAttribute; const originalSetAttribute = Element.prototype.setAttribute;
Element.prototype.setAttribute = function (name, value) { Element.prototype.setAttribute = function (name, value) {
if (!name.startsWith('$')) return originalSetAttribute.call(this, name, value); if (!name.startsWith('$')) return originalSetAttribute.call(this, name, value);
@ -46,21 +38,18 @@ export { $, $$ };
onNotifyUpdate((binding) => _updateBinding(binding)); onNotifyUpdate((binding) => _updateBinding(binding));
export function _clearRenderedNodes(node) { export function _clearRenderedNodes(node) {
if (node._renderedNodes) node._renderedNodes.forEach(nodes => { if (node._renderedNodes) node._renderedNodes.forEach(nodes => nodes.forEach(child => {
nodes.forEach(child => { child.remove();
child.remove(); if (child._renderedNodes) _clearRenderedNodes(child);
if (child._renderedNodes) _clearRenderedNodes(child); }));
});
});
} }
export function _updateBinding(binding) { export function _updateBinding(binding) {
const node = binding.node; const node = binding.node;
const tpl = binding.tpl; if (!node.isConnected && node.tagName !== 'TEMPLATE') return;
const exp = binding.exp;
setActiveBinding(binding); setActiveBinding(binding);
let result = exp ? (tpl ? _returnCode(tpl, { thisNode: node }, node._thisObj || node, node._ref || null) : null) : tpl; let result = binding.exp ? (binding.tpl ? _returnCode(binding.tpl, { thisNode: node }, node._thisObj || node, node._ref || null) : null) : binding.tpl;
setActiveBinding(null); setActiveBinding(null);
if (binding.prop) { if (binding.prop) {
@ -73,14 +62,13 @@ export function _updateBinding(binding) {
if (typeof o !== 'object') break; if (typeof o !== 'object') break;
} }
if (typeof o === 'object' && o !== null) { if (typeof o === 'object' && o !== null) {
const resultIsObject = typeof result === 'object' && result != null && !Array.isArray(result);
const lk = prop[prop.length - 1]; const lk = prop[prop.length - 1];
if (lk) { if (lk) {
if (resultIsObject && o[lk] == null) o[lk] = {}; if (typeof result === 'object' && result != null && !Array.isArray(result) && o[lk] == null) o[lk] = {};
const lo = o[lk]; const lo = o[lk];
if (typeof lo === 'object' && lo != null && lo.__watch) Object.assign(lo, result); if (typeof lo === 'object' && lo != null && lo.__watch) Object.assign(lo, result);
else o[lk] = result; else o[lk] = result;
} else if (resultIsObject && typeof o === 'object') { } else if (typeof result === 'object' && result != null && !Array.isArray(result)) {
Object.assign(o, result); Object.assign(o, result);
} }
} }
@ -129,9 +117,7 @@ export function _updateBinding(binding) {
if (!node._renderedNodes) node._renderedNodes = []; if (!node._renderedNodes) node._renderedNodes = [];
node._children.forEach(child => { node._children.forEach(child => {
const cloned = child.cloneNode(true); const cloned = child.cloneNode(true);
cloned._ref = { ...node._ref }; cloned._ref = { ...node._ref, [indexName]: k, [asName]: item };
cloned._ref[indexName] = k;
cloned._ref[asName] = item;
cloned._thisObj = node._thisObj; cloned._thisObj = node._thisObj;
node.parentNode.insertBefore(cloned, node); node.parentNode.insertBefore(cloned, node);
newNodes.push(cloned); newNodes.push(cloned);
@ -140,53 +126,39 @@ export function _updateBinding(binding) {
} }
}); });
while (node._renderedNodes && node._renderedNodes.length > keys.length) { while (node._renderedNodes && node._renderedNodes.length > keys.length) {
node._renderedNodes[node._renderedNodes.length - 1].forEach(child => { node._renderedNodes.pop().forEach(child => {
_clearRenderedNodes(child); _clearRenderedNodes(child);
child.remove(); child.remove();
}); });
node._renderedNodes.pop();
} }
} else { } else {
_clearRenderedNodes(node); _clearRenderedNodes(node);
node._renderedNodes = []; node._renderedNodes = [];
} }
} else if (attr === 'bind') { } else if (attr === 'bind') {
if (['INPUT', 'SELECT', 'TEXTAREA'].includes(node.tagName)) { if (['INPUT', 'SELECT', 'TEXTAREA'].includes(node.tagName) && !node.hasAttribute('autocomplete')) node.setAttribute('autocomplete', 'off');
if (!node.hasAttribute('autocomplete')) node.setAttribute('autocomplete', 'off');
}
if (node.type === 'checkbox') { if (node.type === 'checkbox') {
if (node.value !== 'on' && !result) { if (node.value !== 'on' && !result) { _runCode(`${binding.tpl} = []`, { thisNode: node }, node._thisObj || node, node._ref || {}); result = []; }
_runCode(`${tpl} = []`, { thisNode: node }, node._thisObj || node, node._ref || {});
result = [];
}
node._checkboxMultiMode = result instanceof Array; node._checkboxMultiMode = result instanceof Array;
const isChecked = result instanceof Array ? result.includes(node.value) : !!result; const isChecked = result instanceof Array ? result.includes(node.value) : !!result;
if (node.checked !== isChecked) node.checked = isChecked; if (node.checked !== isChecked) node.checked = isChecked;
} else if (node.type === 'radio') { } else if (node.type === 'radio') {
if (node.checked !== (node.value === String(result ?? ''))) node.checked = (node.value === String(result ?? '')); if (node.checked !== (node.value === String(result ?? ''))) node.checked = (node.value === String(result ?? ''));
} else if ('value' in node && node.type !== 'file') { } else if ('value' in node && node.type !== 'file') {
setTimeout(() => { setTimeout(() => { if (node.value !== String(result ?? '')) node.value = result; });
if (node.value !== String(result ?? '')) node.value = result;
});
} else if (node.isContentEditable) { } else if (node.isContentEditable) {
if (node.innerHTML !== String(result ?? '')) node.innerHTML = result; if (node.innerHTML !== String(result ?? '')) node.innerHTML = result;
} }
node.dispatchEvent(new CustomEvent('bind', { bubbles: false, detail: result })); node.dispatchEvent(new CustomEvent('bind', { bubbles: false, detail: result }));
} else { } else {
if (['checked', 'disabled', 'readonly'].includes(attr)) result = !!result; if (['checked', 'disabled', 'readonly'].includes(attr)) result = !!result;
if (typeof result === 'boolean') { if (typeof result === 'boolean') result ? node.setAttribute(attr, '') : node.removeAttribute(attr);
result ? node.setAttribute(attr, '') : node.removeAttribute(attr); else if (result !== undefined) {
} else if (result !== undefined) {
if (typeof result !== 'string') result = JSON.stringify(result); if (typeof result !== 'string') result = JSON.stringify(result);
if (attr === 'text') { if (attr === 'text') node.textContent = result ?? '';
node.textContent = result ?? ''; else if (attr === 'html') node.innerHTML = result ?? '';
} else if (attr === 'html') { else if (node.tagName === 'IMG' && attr === 'src' && result.includes('.svg')) node.setAttribute('_src', result ?? '');
node.innerHTML = result ?? ''; else node.setAttribute(attr, result ?? '');
} else if (node.tagName === 'IMG' && attr === 'src' && result.includes('.svg')) {
node.setAttribute('_src', result ?? '');
} else {
node.setAttribute(attr, result ?? '');
}
} }
} }
} }
@ -199,52 +171,46 @@ export const _initBinding = (binding) => {
}; };
export const _parseNode = (node, scanObj) => { export const _parseNode = (node, scanObj) => {
let hasBindings = false;
if (node._bindings) { if (node._bindings) {
node._states = new Set(); node._states = new Set();
node._bindings.forEach(bindingData => { node._bindings.forEach(b => _updateBinding({ node, ...b }));
const binding = { node: node, ...bindingData };
_updateBinding(binding);
});
if (node._hasOnUpdate) node.dispatchEvent(new Event('update', { bubbles: false })); if (node._hasOnUpdate) node.dispatchEvent(new Event('update', { bubbles: false }));
return; hasBindings = true;
} }
if (Component.exists(node.tagName) && !node._componentInitialized) { if (Component.exists(node.tagName) && !node._componentInitialized) {
Array.from(node.attributes).forEach(attr => { Array.from(node.attributes).forEach(attr => {
if (attr.name.startsWith('$.')) { if (attr.name.startsWith('$.')) {
const realAttrName = attr.name.slice(2); const realAttrName = attr.name.slice(2);
let tpl = attr.value; let tpl = _translate(attr.value);
if (tpl.includes('this.')) tpl = tpl.replace(/\bthis\./g, 'this.parent.'); if (tpl.includes('this.')) tpl = tpl.replace(/\bthis\./g, 'this.parent.');
tpl = _translate(tpl);
const result = _returnCode(tpl, { thisNode: node }, { parent: scanObj.thisObj || node }, node._ref || {}); const result = _returnCode(tpl, { thisNode: node }, { parent: scanObj.thisObj || node }, node._ref || {});
let o = node; let o = node;
const prop = realAttrName.split('.'); const prop = realAttrName.split('.');
for (let i = 0; i < prop.length - 1; i++) { for (let i = 0; i < prop.length - 1; i++) { if (prop[i]) o = (o[prop[i]] ??= {}); }
if (!prop[i]) continue;
if (o[prop[i]] == null) o[prop[i]] = {};
o = o[prop[i]];
}
o[prop[prop.length - 1]] = result; o[prop[prop.length - 1]] = result;
node.removeAttribute(attr.name); node.removeAttribute(attr.name);
} }
}); });
_makeComponent(node.tagName, node, scanObj); _makeComponent(node.tagName, node, scanObj);
$$(node, '[slot-id]').forEach(placeholder => placeholder.removeAttribute('slot-id')); $$(node, '[slot-id]').forEach(p => p.removeAttribute('slot-id'));
node._componentInitialized = true; node._componentInitialized = true;
if (!node._thisObj) node._thisObj = node; if (!node._thisObj) node._thisObj = node;
} }
let attrs = [];
if (node.tagName === 'TEMPLATE') { if (node.tagName === 'TEMPLATE') {
node._children = [...node.content.childNodes]; node._children = [...node.content.childNodes];
node._renderedNodes = []; if (!node._renderedNodes) node._renderedNodes = [];
if (node.hasAttribute('$if')) attrs.push(node.getAttributeNode('$if')); }
else if (node.hasAttribute('$each')) attrs.push(node.getAttributeNode('$each'));
else if (node.hasAttribute('st-if')) attrs.push(node.getAttributeNode('st-if')); if (hasBindings) return;
else if (node.hasAttribute('st-each')) attrs.push(node.getAttributeNode('st-each'));
let attrs = [];
if (node.tagName === 'TEMPLATE') {
['$if', '$each', 'st-if', 'st-each'].forEach(n => node.hasAttribute(n) && attrs.push(node.getAttributeNode(n)));
} else { } else {
attrs = Array.from(node.attributes).filter(attr => (attr.name.startsWith('$') || attr.name.startsWith('st-')) && !['$if', '$each', 'st-if', 'st-each'].includes(attr.name) || attr.name.includes('.')); 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('.'));
} }
if (node._thisObj && scanObj.thisObj) node._thisObj.parent = scanObj.thisObj; if (node._thisObj && scanObj.thisObj) node._thisObj.parent = scanObj.thisObj;
@ -257,50 +223,28 @@ export const _parseNode = (node, scanObj) => {
const realAttrName = exp ? attr.name.slice(attr.name.startsWith('$') ? 1 : 3) : attr.name; const realAttrName = exp ? attr.name.slice(attr.name.startsWith('$') ? 1 : 3) : attr.name;
let tpl = attr.value; let tpl = attr.value;
node.removeAttribute(attr.name); node.removeAttribute(attr.name);
if (realAttrName.startsWith('.')) { if (realAttrName.startsWith('.')) _initBinding({ node, prop: realAttrName.split('.'), tpl, exp });
_initBinding({ node: node, prop: realAttrName.split('.'), tpl, exp }); else if (realAttrName.startsWith('on')) {
const eventName = realAttrName.slice(2);
if (eventName === 'update') node._hasOnUpdate = true;
if (eventName === 'load' && !['BODY', 'IMG', 'IFRAME'].includes(node.tagName)) node._hasOnLoad = true;
if (eventName === 'unload' && !['BODY', 'IMG', 'IFRAME'].includes(node.tagName)) node._hasOnUnload = true;
node.addEventListener(eventName, (e) => _runCode(tpl, { event: e, thisNode: node, ...(e.detail || {}) }, scanObj.thisObj || node, node._ref || {}));
} else { } else {
if (realAttrName.startsWith('on')) { if (realAttrName === 'bind') {
const eventName = realAttrName.slice(2); node.addEventListener(node.tagName === 'TEXTAREA' || node.isContentEditable || node.type === 'text' || node.type === 'password' ? 'input' : 'change', (e) => {
if (eventName === 'update') node._hasOnUpdate = true; let newVal = node.isContentEditable ? e.target.innerHTML : (node.type === 'checkbox' ? e.target.checked : e.target.files || e.target.value || e.detail);
if (eventName === 'load' && !['BODY', 'IMG', 'IFRAME'].includes(node.tagName)) node._hasOnLoad = true; setNoWriteBack(node); setDisableRunCodeError(true);
if (eventName === 'unload' && !['BODY', 'IMG', 'IFRAME'].includes(node.tagName)) node._hasOnUnload = true; 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 || {});
((node, thisObj) => { else _runCode(`${tpl} = val`, { val: newVal, thisNode: node }, scanObj.thisObj || node, node._ref || {});
node.addEventListener(eventName, (e) => { setDisableRunCodeError(false); setNoWriteBack(null);
_runCode(tpl, { event: e, thisNode: node, ...(e.detail || {}) }, thisObj || node, node._ref || {}); });
}); } else if (realAttrName === 'text' && !tpl) { tpl = node.textContent; node.textContent = ''; }
})(node, scanObj.thisObj); if (tpl) { tpl = _translate(tpl); _initBinding({ node, attr: realAttrName, tpl, exp }); }
} else {
if (realAttrName === 'bind') {
node.addEventListener(node.tagName === 'TEXTAREA' || node.isContentEditable || node.type === 'text' || node.type === 'password' ? 'input' : 'change', (e) => {
let newVal = node.isContentEditable ? e.target.innerHTML : (node.type === 'checkbox' ? e.target.checked : e.target.files || e.target.value || e.detail);
setNoWriteBack(node);
setDisableRunCodeError(true);
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 || {});
} else {
_runCode(`${tpl} = val`, { val: newVal, thisNode: node }, scanObj.thisObj || node, node._ref || {});
}
setDisableRunCodeError(false);
setNoWriteBack(null);
});
} else if (realAttrName === 'text' && !tpl) {
tpl = node.textContent;
node.textContent = '';
}
if (tpl) {
tpl = _translate(tpl);
_initBinding({ node: node, attr: realAttrName, tpl, exp });
}
}
} }
}); });
if (node._hasOnLoad || node._componentInitialized) { if (node._hasOnLoad || node._componentInitialized) Promise.resolve().then(() => node.dispatchEvent(new Event('load', { bubbles: false })));
(node => {
Promise.resolve().then(() => node.dispatchEvent(new Event('load', { bubbles: false })));
})(node);
}
if (node._hasOnUpdate) node.dispatchEvent(new Event('update', { bubbles: false })); if (node._hasOnUpdate) node.dispatchEvent(new Event('update', { bubbles: false }));
if (node._thisObj) scanObj.thisObj = node._thisObj; if (node._thisObj) scanObj.thisObj = node._thisObj;
}; };
@ -310,8 +254,7 @@ export const _scanTree = (node, scanObj = {}) => {
if (node._stTranslated) return; if (node._stTranslated) return;
const translated = _translate(node.textContent); const translated = _translate(node.textContent);
if (translated !== node.textContent) node.textContent = translated; if (translated !== node.textContent) node.textContent = translated;
node._stTranslated = true; node._stTranslated = true; return;
return;
} }
if (node.nodeType !== 1) return; if (node.nodeType !== 1) return;
@ -328,14 +271,10 @@ export const _scanTree = (node, scanObj = {}) => {
if (node.tagName !== 'TEMPLATE' && (node.hasAttribute('$if') || node.hasAttribute('$each') || node.hasAttribute('st-if') || node.hasAttribute('st-each'))) { if (node.tagName !== 'TEMPLATE' && (node.hasAttribute('$if') || node.hasAttribute('$each') || node.hasAttribute('st-if') || node.hasAttribute('st-each'))) {
const template = document.createElement('TEMPLATE'); const template = document.createElement('TEMPLATE');
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))); 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)));
attrs.forEach(attr => { attrs.forEach(attr => { template.setAttribute(attr.name, attr.value); node.removeAttribute(attr.name); });
template.setAttribute(attr.name, attr.value);
node.removeAttribute(attr.name);
});
node.parentNode.insertBefore(template, node); node.parentNode.insertBefore(template, node);
template.content.appendChild(node); template.content.appendChild(node);
template._ref = node._ref; template._ref = node._ref;
node = template;
return; return;
} }
if (node.tagName === 'TEMPLATE' && (node.hasAttribute('$if') || node.hasAttribute('st-if')) && (node.hasAttribute('$each') || node.hasAttribute('st-each'))) { if (node.tagName === 'TEMPLATE' && (node.hasAttribute('$if') || node.hasAttribute('st-if')) && (node.hasAttribute('$each') || node.hasAttribute('st-each'))) {
@ -345,14 +284,9 @@ export const _scanTree = (node, scanObj = {}) => {
template.setAttribute(attr.name, attr.value); template.setAttribute(attr.name, attr.value);
node.removeAttribute(attr.name); node.removeAttribute(attr.name);
if (attr.name === '$each' || attr.name === 'st-each') { if (attr.name === '$each' || attr.name === 'st-each') {
Array.from(node.attributes).filter(attr => ['as', 'index'].includes(attr.name)).forEach(attr => { Array.from(node.attributes).filter(attr => ['as', 'index'].includes(attr.name)).forEach(attr => { template.setAttribute(attr.name, attr.value); node.removeAttribute(attr.name); });
template.setAttribute(attr.name, attr.value);
node.removeAttribute(attr.name);
});
} }
Array.from(node.content.childNodes).forEach(child => { Array.from(node.content.childNodes).forEach(child => template.content.appendChild(child));
template.content.appendChild(child);
});
node.content.appendChild(template); node.content.appendChild(template);
template._ref = node._ref; template._ref = node._ref;
} }
@ -372,7 +306,7 @@ export const _scanTree = (node, scanObj = {}) => {
} }
if (node._thisObj !== undefined) scanObj.thisObj = node._thisObj || null; if (node._thisObj !== undefined) scanObj.thisObj = node._thisObj || null;
if (scanObj.thisObj === undefined) { else {
let curr = node; let curr = node;
while (curr && curr._thisObj === undefined) curr = curr.parentNode; while (curr && curr._thisObj === undefined) curr = curr.parentNode;
scanObj.thisObj = curr ? curr._thisObj : null; scanObj.thisObj = curr ? curr._thisObj : null;
@ -382,29 +316,23 @@ export const _scanTree = (node, scanObj = {}) => {
while (curr && curr._ref === undefined) curr = curr.parentNode; while (curr && curr._ref === undefined) curr = curr.parentNode;
node._ref = curr ? { ...curr._ref } : {}; node._ref = curr ? { ...curr._ref } : {};
} }
if (scanObj.extendVars === undefined) scanObj.extendVars = {}; if (scanObj.extendVars) Object.assign(node._ref, scanObj.extendVars);
if (node._ref !== undefined) {
Object.assign(node._ref, scanObj.extendVars);
scanObj.extendVars = { ...node._ref };
}
_parseNode(node, scanObj); _parseNode(node, scanObj);
const nodes = [...(node.childNodes || [])]; const nodes = [...(node.childNodes || [])];
scanObj.extendVars = node._ref || scanObj.extendVars; const nextScanObj = { thisObj: scanObj.thisObj, extendVars: { ...node._ref } };
nodes.forEach(child => _scanTree(child, { thisObj: scanObj.thisObj, extendVars: { ...node._ref } })); nodes.forEach(child => _scanTree(child, nextScanObj));
}; };
export const _unbindTree = (node) => { export const _unbindTree = (node) => {
if (node.nodeType !== 1) return; if (node.nodeType !== 1) return;
if (node._hasOnUnload) node.dispatchEvent(new Event('unload', { bubbles: false })); if (node._hasOnUnload) node.dispatchEvent(new Event('unload', { bubbles: false }));
if (node._states) { if (node._states) node._states.forEach(mappings => {
node._states.forEach(stateMappings => { for (const [key, bindingSet] of mappings) {
for (const [key, bindingSet] of stateMappings) { for (const binding of bindingSet) { if (binding.node === node) bindingSet.delete(binding); }
for (const binding of bindingSet) { }
if (binding.node === node) bindingSet.delete(binding); });
}
}
});
}
node.childNodes && node.childNodes.forEach(child => _unbindTree(child)); node.childNodes && node.childNodes.forEach(child => _unbindTree(child));
}; };