Compare commits

..

5 Commits

Author SHA1 Message Date
AI Engineer
eb0145ea85 fix(state): 修复组件 $. 属性在初始化时丢失响应式绑定的 Bug(by AI) 2026-07-06 08:02:02 +08:00
AI Engineer
1e46c8a76e feat(state): 合并组件的 class 和 样式,修复双重指令等 Bug(by AI) By: AICoder 2026-07-04 09:57:23 +08:00
AI Engineer
b4f7ca6468 fix(publish): publish.js 强制包名全小写以符合 npm 规范(by AI)
Co-Authored-By: deepseek-v4-pro[1m] <deepseek-ai@claude-code-best.win>
2026-06-22 19:29:12 +08:00
AI Engineer
bbb84ebdde chore(state): 同步 publish 版本号至 1.0.21(by AI)
Co-Authored-By: deepseek-v4-pro[1m] <deepseek-ai@claude-code-best.win>
2026-06-22 19:28:04 +08:00
AI Engineer
cc4e5226c0 fix(state): 修复 keyed nodes 重排时缺少 insertBefore,降级 structuredClone 为 JSON 序列化(by AI)
Co-Authored-By: deepseek-v4-pro[1m] <deepseek-ai@claude-code-best.win>
2026-06-22 19:23:22 +08:00
19 changed files with 528 additions and 520 deletions

View File

@ -1,5 +1,27 @@
# CHANGELOG
## v1.0.23 (2026-07-06)
### 修复
- **组件 `$.` 属性响应式绑定修复**:
- 注释了组件属性初始化时的 `node.removeAttribute(attr.name)`,以防止 `$.` 开头的组件属性在第一次赋完初值后被从 DOM 上永久删除,从而使其能够滑入后置的指令收集队列进行 `_initBinding` 注册,建立了完整的 Proxy 驱动链。
## v1.0.22 (2026-07-04)
### 核心增强与样式合并优化
- **双向样式智能合并与排序**:
- 重构了组件合并时的类名/样式排列机制。现在应用层(外部宿主)写的 `class/style` 将始终按高优先级排在组件内部样式的后侧(右侧),结构严格符合 `[内部静态, 内部动态, 外部动态, 外部静态]`
- 引入了**动态模板字符串合并Template String Merging**算法。当组件内外同时存在 `$class`/`$style``st-class`/`st-style` 绑定时,不采用覆写替换,而是将其物理合并为单一大模板字符串,确保各动态表达式能在正确的上下文(通过 parent 链)中独立安全求值。
- 在 `_updateBinding` 渲染分支中加入了对 class 和 style 的**惰性捕获备份Lazy Cache**机制,只在首次更新时从 DOM 读取备份静态基准值,大幅减少不必要的 DOM 属性重置。
### 修复
- **双重解析指令修复**:
- 修复了自 v1.0.19 大重构后,由于硬编码属性匹配列表导致双重解析指令(`$$if` / `$$each` 等)全系失效的 Bug。已恢复对非 `TEMPLATE` 节点的自动包裹提升以及对 `TEMPLATE` 节点上双重指令的正常提取。
- **自动化测试缺陷修正**:
- 修正了在测试中因重写 `document.body.innerHTML` 导致 `body` 内已被挂载的 `template` 元素被误抹去的严重缺陷。
- 修正了 `testPriority` 全局 `window.state` 缺失导致的空值求值缺陷,补齐了由于 `MutationObserver` 异步微任务渲染时序所需的 `await` 等待。
- 修正了 `testMerging` 里非法 CSS 属性赋予 JS 动态绑定 `$style` 导致的语法解析错误,并补全了对同名动态绑定合并与优先级的断言。
## v1.0.17 (2026-06-05)
### 重大变更 (Philosophical Restoration)

55
dist/state.js vendored
View File

@ -4,7 +4,7 @@
"use strict";
var _a, _b;
const Util = {
clone: globalThis.structuredClone || ((obj) => JSON.parse(JSON.stringify(obj))),
clone: (obj) => JSON.parse(JSON.stringify(obj)),
base64: (str) => btoa(String.fromCharCode(...new TextEncoder().encode(str))),
unbase64: (str) => new TextDecoder().decode(Uint8Array.from(atob(str), (c) => c.charCodeAt(0))),
urlbase64: (str) => Util.base64(str).replace(/[+/=]/g, (m) => ({ "+": "-", "/": "", "=": "" })[m]),
@ -222,12 +222,26 @@
if (attr.name === "style") {
if (to.hasAttribute("style")) to.setAttribute("style", `${attr.value}; ${to.getAttribute("style")}`);
else to.setAttribute("style", attr.value);
} else if (!to.hasAttribute(attr.name)) {
} else if (to.hasAttribute(attr.name)) {
const isClass = ["$class", "st-class"].includes(attr.name);
const isStyle = ["$style", "st-style"].includes(attr.name);
if (isClass || isStyle) {
const oldVal = to.getAttribute(attr.name);
const newVal = attr.value;
const delimiter = isClass ? " " : "; ";
const oldExpr = oldVal.includes("${") ? oldVal : `\${${oldVal}}`;
const newExpr = newVal.includes("${") ? newVal : `\${${newVal}}`;
to.setAttribute(attr.name, `${newExpr}${delimiter}${oldExpr}`);
}
} else {
to.setAttribute(attr.name, attr.value);
}
});
}
const toClassList = [...to.classList];
to.className = "";
to.classList.add(...from.classList);
to.classList.add(...toClassList);
const target = to.tagName === "TEMPLATE" ? to.content : to;
const sourceNodes = from.tagName === "TEMPLATE" ? from.content.childNodes : from.childNodes;
Array.from(sourceNodes).forEach((child) => target.appendChild(child));
@ -318,6 +332,7 @@
}
}
_setActiveBinding(null);
binding.lastResult = result;
if (binding.prop) {
const prop = binding.prop;
let o = node;
@ -385,6 +400,7 @@
if (existingNodes) {
node._keyedNodes.delete(keyVal);
existingNodes.forEach((child) => {
node.parentNode.insertBefore(child, node);
child._ref[indexName] = k;
child._ref[asName] = item;
_scanTree(child);
@ -440,7 +456,21 @@
if (attr === "text") node.textContent = result ?? "";
else if (attr === "html") node.innerHTML = result ?? "";
else if (node.tagName === "IMG" && attr === "src" && result.includes(".svg")) node.setAttribute("_src", result ?? "");
else node.setAttribute(attr, result ?? "");
else if (attr === "class") {
if (node._staticClasses === void 0) {
node._staticClasses = node.getAttribute("class") || "";
}
const staticClasses = node._staticClasses;
const finalClass = result ? staticClasses ? `${result} ${staticClasses}` : result : staticClasses;
node.setAttribute("class", finalClass.trim().replace(/\s+/g, " "));
} else if (attr === "style") {
if (node._staticStyles === void 0) {
node._staticStyles = node.getAttribute("style") || "";
}
const staticStyles = node._staticStyles;
const finalStyle = result ? staticStyles ? `${result}; ${staticStyles}` : result : staticStyles;
node.setAttribute("style", finalStyle.trim().replace(/;;+/g, ";").replace(/^;+\s*|;\s*$/g, ""));
} else node.setAttribute(attr, result ?? "");
}
}
}
@ -471,7 +501,6 @@
if (prop[i]) o = o[_a2 = prop[i]] ?? (o[_a2] = {});
}
o[prop[prop.length - 1]] = result;
node.removeAttribute(attr.name);
}
});
_makeComponent(node.tagName, node, scanObj);
@ -485,9 +514,9 @@
}
let attrs = [];
if (node.tagName === "TEMPLATE") {
["$if", "$each", "st-if", "st-each"].forEach((n) => node.hasAttribute(n) && attrs.push(node.getAttributeNode(n)));
["$if", "$each", "st-if", "st-each", "$$if", "$$each", "st-st-if", "st-st-each"].forEach((n) => node.hasAttribute(n) && attrs.push(node.getAttributeNode(n)));
} else {
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("."));
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("."));
}
if (node._thisObj && scanObj.thisObj && node._thisObj !== scanObj.thisObj) node._thisObj.parent = scanObj.thisObj;
if (!node._thisObj) node._thisObj = scanObj.thisObj || null;
@ -551,9 +580,9 @@
});
node._stTranslated = true;
}
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") || node.hasAttribute("$$if") || node.hasAttribute("$$each") || node.hasAttribute("st-st-if") || node.hasAttribute("st-st-each"))) {
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", "$$if", "$$each", "st-st-if", "st-st-each"].includes(attr.name) || (node.hasAttribute("$each") || node.hasAttribute("st-each") || node.hasAttribute("$$each") || node.hasAttribute("st-st-each")) && ["as", "index"].includes(attr.name));
attrs.forEach((attr) => {
template.setAttribute(attr.name, attr.value);
node.removeAttribute(attr.name);
@ -564,13 +593,13 @@
_scanTree(template, scanObj);
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("$$if") || node.hasAttribute("st-st-if")) && (node.hasAttribute("$each") || node.hasAttribute("st-each") || node.hasAttribute("$$each") || node.hasAttribute("st-st-each"))) {
const template = document.createElement("TEMPLATE");
const attrs = Array.from(node.attributes).filter((attr2) => ["$if", "$each", "st-if", "st-each"].includes(attr2.name));
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));
const attr = attrs[attrs.length - 1];
template.setAttribute(attr.name, attr.value);
node.removeAttribute(attr.name);
if (attr.name === "$each" || attr.name === "st-each") {
if (["$each", "st-each", "$$each", "st-st-each"].includes(attr.name)) {
Array.from(node.attributes).filter((attr2) => ["as", "index"].includes(attr2.name)).forEach((attr2) => {
template.setAttribute(attr2.name, attr2.value);
node.removeAttribute(attr2.name);
@ -657,5 +686,9 @@
exports2.State = State;
exports2.Util = Util;
exports2.__unsafeRefreshState = __unsafeRefreshState;
exports2._returnCode = _returnCode;
exports2._runCode = _runCode;
exports2.onNotifyUpdate = _onNotifyUpdate;
exports2.setActiveBinding = _setActiveBinding;
Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
});

2
dist/state.min.js vendored

File diff suppressed because one or more lines are too long

4
package-lock.json generated
View File

@ -1,12 +1,12 @@
{
"name": "@apigo.cc/state",
"version": "1.0.19",
"version": "1.0.20",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@apigo.cc/state",
"version": "1.0.19",
"version": "1.0.20",
"devDependencies": {
"@playwright/test": "^1.40.0",
"@rollup/plugin-terser": "^1.0.0",

View File

@ -1,6 +1,6 @@
{
"name": "@apigo.cc/state",
"version": "1.0.20",
"version": "1.0.23",
"type": "module",
"main": "dist/state.js",
"module": "dist/state.js",

View File

@ -22,11 +22,9 @@ try {
const pkgPath = path.join(__dirname, '../package.json');
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
// 保持原有名称(如果已经带有 @apigo.cc/ 前缀)或替换前缀
if (!pkg.name.startsWith('@apigo.cc/')) {
const baseName = pkg.name.includes('/') ? pkg.name.split('/')[1] : pkg.name;
pkg.name = `@apigo.cc/${baseName}`;
}
// npm 要求包名全小写scope + name 强制 toLowerCase
const baseName = (pkg.name.includes('/') ? pkg.name.split('/')[1] : pkg.name).toLowerCase();
pkg.name = `@apigo.cc/${baseName}`;
pkg.version = version;
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n');

View File

@ -12,438 +12,469 @@ const _components = new Map();
const _pendingTemplates = [];
export const Component = {
getTemplate: name => document.querySelector(`template[component="${name.toUpperCase()}"]`),
register: (name, setupFunc, templateNode = null, ...globalNodes) => {
_components.set(name.toUpperCase(), setupFunc);
if (document.readyState !== 'loading') Component._addTemplate(name, templateNode, globalNodes);
else _pendingTemplates.push([name, templateNode, globalNodes]);
},
exists: (name) => _components.has(name.toUpperCase()),
getSetupFunction: (name) => _components.get(name.toUpperCase()),
_addTemplate: (name, templateNode, globalNodes) => {
if (templateNode) {
const template = document.createElement('TEMPLATE');
template.setAttribute('component', name.toUpperCase());
template.content.appendChild(templateNode);
document.body.appendChild(template);
}
if (globalNodes) globalNodes.forEach(node => document.body.appendChild(node));
},
_initPending: () => {
_pendingTemplates.forEach(([name, templateNode, globalNodes]) => Component._addTemplate(name, templateNode, globalNodes));
_pendingTemplates.length = 0;
}
getTemplate: name => document.querySelector(`template[component="${name.toUpperCase()}"]`),
register: (name, setupFunc, templateNode = null, ...globalNodes) => {
_components.set(name.toUpperCase(), setupFunc);
if (document.readyState !== 'loading') Component._addTemplate(name, templateNode, globalNodes);
else _pendingTemplates.push([name, templateNode, globalNodes]);
},
exists: (name) => _components.has(name.toUpperCase()),
getSetupFunction: (name) => _components.get(name.toUpperCase()),
_addTemplate: (name, templateNode, globalNodes) => {
if (templateNode) {
const template = document.createElement('TEMPLATE');
template.setAttribute('component', name.toUpperCase());
template.content.appendChild(templateNode);
document.body.appendChild(template);
}
if (globalNodes) globalNodes.forEach(node => document.body.appendChild(node));
},
_initPending: () => {
_pendingTemplates.forEach(([name, templateNode, globalNodes]) => Component._addTemplate(name, templateNode, globalNodes));
_pendingTemplates.length = 0;
}
};
export function _mergeNode(from, to, scanObj, exists = {}) {
if (from.attributes) {
Array.from(from.attributes).forEach(attr => {
if (attr.name === 'class') return;
if (attr.name === 'style') {
if (to.hasAttribute('style')) to.setAttribute('style', `${attr.value}; ${to.getAttribute('style')}`);
else to.setAttribute('style', attr.value);
} else if (!to.hasAttribute(attr.name)) {
to.setAttribute(attr.name, attr.value);
}
});
}
to.classList.add(...from.classList);
const target = to.tagName === 'TEMPLATE' ? to.content : to;
const sourceNodes = from.tagName === 'TEMPLATE' ? from.content.childNodes : from.childNodes;
Array.from(sourceNodes).forEach(child => target.appendChild(child));
if (from.tagName && Component.exists(from.tagName)) _makeComponent(from.tagName, to, scanObj, exists);
if (from.attributes) {
Array.from(from.attributes).forEach(attr => {
if (attr.name === 'class') return;
if (attr.name === 'style') {
if (to.hasAttribute('style')) to.setAttribute('style', `${attr.value}; ${to.getAttribute('style')}`);
else to.setAttribute('style', attr.value);
} else if (to.hasAttribute(attr.name)) {
const isClass = ['$class', 'st-class'].includes(attr.name);
const isStyle = ['$style', 'st-style'].includes(attr.name);
if (isClass || isStyle) {
const oldVal = to.getAttribute(attr.name);
const newVal = attr.value;
const delimiter = isClass ? " " : "; ";
const oldExpr = oldVal.includes('${') ? oldVal : `\${${oldVal}}`;
const newExpr = newVal.includes('${') ? newVal : `\${${newVal}}`;
to.setAttribute(attr.name, `${newExpr}${delimiter}${oldExpr}`);
}
} else {
to.setAttribute(attr.name, attr.value);
}
});
}
const toClassList = [...to.classList];
to.className = '';
to.classList.add(...from.classList);
to.classList.add(...toClassList);
const target = to.tagName === 'TEMPLATE' ? to.content : to;
const sourceNodes = from.tagName === 'TEMPLATE' ? from.content.childNodes : from.childNodes;
Array.from(sourceNodes).forEach(child => target.appendChild(child));
if (from.tagName && Component.exists(from.tagName)) _makeComponent(from.tagName, to, scanObj, exists);
}
export function _makeComponent(name, node, scanObj, exists = {}) {
if (exists[name]) return;
exists[name] = true;
if (scanObj.thisObj) {
Array.from(node.attributes).forEach(attr => {
if ((attr.name.startsWith('$') || attr.name.startsWith('st-')) && attr.value.includes('this.')) {
attr.value = attr.value.replace(/\bthis\./g, 'this.parent.');
}
});
}
const componentFunc = Component.getSetupFunction(name);
const slots = {};
Array.from(node.childNodes).forEach(child => {
if (child.nodeType === Node.ELEMENT_NODE && child.hasAttribute('slot')) {
slots[child.getAttribute('slot')] = child;
child.removeAttribute('slot');
}
});
node.innerHTML = '';
node.state = NewState(node.state || {});
const template = Component.getTemplate(name);
if (template) {
const tplnode = template.content.cloneNode(true);
if (tplnode.childNodes.length) {
const rootNode = tplnode.children[0];
if (rootNode) _mergeNode(rootNode, node, scanObj, exists);
$$(node, '[slot-id]').forEach(placeholder => {
const slotName = placeholder.getAttribute('slot-id');
if (slots[slotName]) {
placeholder.removeAttribute('slot-id');
placeholder.innerHTML = '';
_mergeNode(slots[slotName], placeholder, scanObj, exists);
}
});
}
}
if (componentFunc) componentFunc(node);
if (exists[name]) return;
exists[name] = true;
if (scanObj.thisObj) {
Array.from(node.attributes).forEach(attr => {
if ((attr.name.startsWith('$') || attr.name.startsWith('st-')) && attr.value.includes('this.')) {
attr.value = attr.value.replace(/\bthis\./g, 'this.parent.');
}
});
}
const componentFunc = Component.getSetupFunction(name);
const slots = {};
Array.from(node.childNodes).forEach(child => {
if (child.nodeType === Node.ELEMENT_NODE && child.hasAttribute('slot')) {
slots[child.getAttribute('slot')] = child;
child.removeAttribute('slot');
}
});
node.innerHTML = '';
node.state = NewState(node.state || {});
const template = Component.getTemplate(name);
if (template) {
const tplnode = template.content.cloneNode(true);
if (tplnode.childNodes.length) {
const rootNode = tplnode.children[0];
if (rootNode) _mergeNode(rootNode, node, scanObj, exists);
$$(node, '[slot-id]').forEach(placeholder => {
const slotName = placeholder.getAttribute('slot-id');
if (slots[slotName]) {
placeholder.removeAttribute('slot-id');
placeholder.innerHTML = '';
_mergeNode(slots[slotName], placeholder, scanObj, exists);
}
});
}
}
if (componentFunc) componentFunc(node);
}
// --- DOM Engine Logic ---
let _translator = (text, args) => {
if (!text || typeof text !== 'string') return text;
return text.replace(/\{(.+?)\}/g, (match, key) => args.hasOwnProperty(key) ? args[key] : match);
if (!text || typeof text !== 'string') return text;
return text.replace(/\{(.+?)\}/g, (match, key) => args.hasOwnProperty(key) ? args[key] : match);
};
export const SetTranslator = (fn) => _translator = fn;
const _translate = (text) => {
if (!text || typeof text !== 'string' || !text.includes('{#')) return text;
return text.replace(/\{#(.+?)#\}/g, (m, content) => {
const parts = content.split('||').map(s => s.trim());
const args = {};
if (parts.length > 1) {
const matches = parts[0].match(/\{(.+?)\}/g);
if (matches) matches.forEach((match, i) => args[match.substring(1, match.length - 1)] = parts[i + 1] || '');
}
return _translator(parts[0], args);
});
if (!text || typeof text !== 'string' || !text.includes('{#')) return text;
return text.replace(/\{#(.+?)#\}/g, (m, content) => {
const parts = content.split('||').map(s => s.trim());
const args = {};
if (parts.length > 1) {
const matches = parts[0].match(/\{(.+?)\}/g);
if (matches) matches.forEach((match, i) => args[match.substring(1, match.length - 1)] = parts[i + 1] || '');
}
return _translator(parts[0], args);
});
};
if (typeof document !== 'undefined') {
try { document.createElement('div').setAttribute('$t', '1'); } catch (e) {
const originalSetAttribute = Element.prototype.setAttribute;
Element.prototype.setAttribute = function (name, value) {
if (!name.startsWith('$')) return originalSetAttribute.call(this, name, value);
return originalSetAttribute.call(this, 'st-' + name.substring(1), value);
};
}
try { document.createElement('div').setAttribute('$t', '1'); } catch (e) {
const originalSetAttribute = Element.prototype.setAttribute;
Element.prototype.setAttribute = function (name, value) {
if (!name.startsWith('$')) return originalSetAttribute.call(this, name, value);
return originalSetAttribute.call(this, 'st-' + name.substring(1), value);
};
}
}
_onNotifyUpdate((binding) => _updateBinding(binding));
export function _clearRenderedNodes(node) {
if (node._renderedNodes) node._renderedNodes.forEach(nodes => nodes.forEach(child => {
child.remove();
if (child._renderedNodes) _clearRenderedNodes(child);
}));
if (node._renderedNodes) node._renderedNodes.forEach(nodes => nodes.forEach(child => {
child.remove();
if (child._renderedNodes) _clearRenderedNodes(child);
}));
}
export function _updateBinding(binding) {
const node = binding.node;
if (!node.isConnected && node.tagName !== 'TEMPLATE') return;
const node = binding.node;
if (!node.isConnected && node.tagName !== 'TEMPLATE') return;
_setActiveBinding(binding);
let result = binding.exp ? (binding.tpl ? _returnCode(binding.tpl, { thisNode: node }, node._thisObj || node, node._ref || null) : null) : binding.tpl;
_setActiveBinding(binding);
let result = binding.exp ? (binding.tpl ? _returnCode(binding.tpl, { thisNode: node }, node._thisObj || node, node._ref || null) : null) : binding.tpl;
if (binding.exp === 2 && typeof result === 'string') {
try { result = _returnCode(result, { thisNode: node }, node._thisObj || node, node._ref || null); } catch (e) { }
}
_setActiveBinding(null);
if (binding.exp === 2 && typeof result === 'string') {
try { result = _returnCode(result, { thisNode: node }, node._thisObj || node, node._ref || null); } catch (e) { }
}
_setActiveBinding(null);
binding.lastResult = result;
if (binding.prop) {
const prop = binding.prop;
let o = node;
for (let i = 0; i < prop.length - 1; i++) {
if (!prop[i]) continue;
if (o[prop[i]] == null) o[prop[i]] = {};
o = o[prop[i]];
if (typeof o !== 'object') break;
}
if (typeof o === 'object' && o !== null) {
const lk = prop[prop.length - 1];
if (lk) {
if (typeof result === 'object' && result != null && !Array.isArray(result) && o[lk] == null) o[lk] = {};
const lo = o[lk];
if (typeof lo === 'object' && lo != null && lo.__watch) Object.assign(lo, result);
else { if (o[lk] !== result) o[lk] = result; }
} else if (typeof result === 'object' && result != null && !Array.isArray(result)) {
Object.assign(o, result);
}
}
} else if (binding.attr) {
const attr = binding.attr;
if (attr === 'if') {
if (result) {
if (!node._renderedNodes || node._renderedNodes.length === 0) {
node._children.forEach(child => {
node.parentNode.insertBefore(child, node);
child._ref = { ...node._ref };
child._thisObj = node._thisObj;
});
node._renderedNodes = [node._children];
}
} else {
_clearRenderedNodes(node);
node._renderedNodes = [];
}
} else if (attr === 'each') {
if (result && typeof result === 'object') {
const asName = node.getAttribute('as') || 'item';
const indexName = node.getAttribute('index') || 'index';
const keyName = node.getAttribute('key');
let keys, getVal;
if (result instanceof Map) {
keys = Array.from(result.keys()); getVal = k => result.get(k);
} else if (typeof result[Symbol.iterator] === 'function') {
const arr = Array.isArray(result) ? result : Array.from(result);
keys = new Array(arr.length);
for (let i = 0; i < arr.length; i++) keys[i] = i;
getVal = k => arr[k];
} else {
keys = Object.keys(result); getVal = k => result[k];
}
if (binding.prop) {
const prop = binding.prop;
let o = node;
for (let i = 0; i < prop.length - 1; i++) {
if (!prop[i]) continue;
if (o[prop[i]] == null) o[prop[i]] = {};
o = o[prop[i]];
if (typeof o !== 'object') break;
}
if (typeof o === 'object' && o !== null) {
const lk = prop[prop.length - 1];
if (lk) {
if (typeof result === 'object' && result != null && !Array.isArray(result) && o[lk] == null) o[lk] = {};
const lo = o[lk];
if (typeof lo === 'object' && lo != null && lo.__watch) Object.assign(lo, result);
else { if (o[lk] !== result) o[lk] = result; }
} else if (typeof result === 'object' && result != null && !Array.isArray(result)) {
Object.assign(o, result);
}
}
} else if (binding.attr) {
const attr = binding.attr;
if (attr === 'if') {
if (result) {
if (!node._renderedNodes || node._renderedNodes.length === 0) {
node._children.forEach(child => {
node.parentNode.insertBefore(child, node);
child._ref = { ...node._ref };
child._thisObj = node._thisObj;
});
node._renderedNodes = [node._children];
}
} else {
_clearRenderedNodes(node);
node._renderedNodes = [];
}
} else if (attr === 'each') {
if (result && typeof result === 'object') {
const asName = node.getAttribute('as') || 'item';
const indexName = node.getAttribute('index') || 'index';
const keyName = node.getAttribute('key');
let keys, getVal;
if (result instanceof Map) {
keys = Array.from(result.keys()); getVal = k => result.get(k);
} else if (typeof result[Symbol.iterator] === 'function') {
const arr = Array.isArray(result) ? result : Array.from(result);
keys = new Array(arr.length);
for (let i = 0; i < arr.length; i++) keys[i] = i;
getVal = k => arr[k];
} else {
keys = Object.keys(result); getVal = k => result[k];
}
if (!node._keyedNodes) node._keyedNodes = new Map();
const newKeyedNodes = new Map();
const currentRenderedNodes = [];
if (!node._keyedNodes) node._keyedNodes = new Map();
const newKeyedNodes = new Map();
const currentRenderedNodes = [];
keys.forEach((k, i) => {
const item = getVal(k);
const rawKey = keyName ? (item && typeof item === 'object' ? item[keyName] : item) : k;
const keyVal = (rawKey === undefined || rawKey === null || newKeyedNodes.has(rawKey)) ? `st_key_${i}` : rawKey;
keys.forEach((k, i) => {
const item = getVal(k);
const rawKey = keyName ? (item && typeof item === 'object' ? item[keyName] : item) : k;
const keyVal = (rawKey === undefined || rawKey === null || newKeyedNodes.has(rawKey)) ? `st_key_${i}` : rawKey;
let existingNodes = node._keyedNodes.get(keyVal);
let existingNodes = node._keyedNodes.get(keyVal);
if (existingNodes) {
node._keyedNodes.delete(keyVal);
existingNodes.forEach(child => {
child._ref[indexName] = k;
child._ref[asName] = item;
_scanTree(child);
});
} else {
existingNodes = [];
node._children.forEach(child => {
const cloned = child.cloneNode(true);
cloned._ref = { ...node._ref, [indexName]: k, [asName]: item };
cloned._thisObj = node._thisObj;
node.parentNode.insertBefore(cloned, node);
existingNodes.push(cloned);
});
}
newKeyedNodes.set(keyVal, existingNodes);
currentRenderedNodes.push(existingNodes);
});
if (existingNodes) {
node._keyedNodes.delete(keyVal);
existingNodes.forEach(child => {
node.parentNode.insertBefore(child, node);
child._ref[indexName] = k;
child._ref[asName] = item;
_scanTree(child);
});
} else {
existingNodes = [];
node._children.forEach(child => {
const cloned = child.cloneNode(true);
cloned._ref = { ...node._ref, [indexName]: k, [asName]: item };
cloned._thisObj = node._thisObj;
node.parentNode.insertBefore(cloned, node);
existingNodes.push(cloned);
});
}
newKeyedNodes.set(keyVal, existingNodes);
currentRenderedNodes.push(existingNodes);
});
node._keyedNodes.forEach(nodes => nodes.forEach(child => { _clearRenderedNodes(child); child.remove(); }));
node._keyedNodes = newKeyedNodes;
node._renderedNodes = currentRenderedNodes;
} else {
_clearRenderedNodes(node);
node._renderedNodes = [];
}
} else if (attr === 'bind') {
if (['INPUT', 'SELECT', 'TEXTAREA'].includes(node.tagName) && !node.hasAttribute('autocomplete')) node.setAttribute('autocomplete', 'off');
if (node.type === 'checkbox') {
if (node.value !== 'on' && !result) { _runCode(`${binding.tpl} = []`, { thisNode: node }, node._thisObj || node, node._ref || {}); result = []; }
node._checkboxMultiMode = result instanceof Array;
const isChecked = result instanceof Array ? result.includes(node.value) : !!result;
if (node.checked !== isChecked) node.checked = isChecked;
} else if (node.type === 'radio') {
if (node.checked !== (node.value === String(result ?? ''))) node.checked = (node.value === String(result ?? ''));
} else if ('value' in node && node.type !== 'file') {
Promise.resolve().then(() => { if (node.value !== String(result ?? '')) node.value = result; });
} else if (node.isContentEditable) {
if (node.innerHTML !== String(result ?? '')) node.innerHTML = result;
}
node.dispatchEvent(new CustomEvent('bind', { bubbles: false, detail: result }));
} else {
if (['checked', 'disabled', 'readonly'].includes(attr)) result = !!result;
if (typeof result === 'boolean') result ? node.setAttribute(attr, '') : node.removeAttribute(attr);
else if (result !== undefined) {
if (typeof result !== 'string') result = JSON.stringify(result);
if (attr === 'text') node.textContent = result ?? '';
else if (attr === 'html') node.innerHTML = result ?? '';
else if (node.tagName === 'IMG' && attr === 'src' && result.includes('.svg')) node.setAttribute('_src', result ?? '');
else node.setAttribute(attr, result ?? '');
}
}
}
node._keyedNodes.forEach(nodes => nodes.forEach(child => { _clearRenderedNodes(child); child.remove(); }));
node._keyedNodes = newKeyedNodes;
node._renderedNodes = currentRenderedNodes;
} else {
_clearRenderedNodes(node);
node._renderedNodes = [];
}
} else if (attr === 'bind') {
if (['INPUT', 'SELECT', 'TEXTAREA'].includes(node.tagName) && !node.hasAttribute('autocomplete')) node.setAttribute('autocomplete', 'off');
if (node.type === 'checkbox') {
if (node.value !== 'on' && !result) { _runCode(`${binding.tpl} = []`, { thisNode: node }, node._thisObj || node, node._ref || {}); result = []; }
node._checkboxMultiMode = result instanceof Array;
const isChecked = result instanceof Array ? result.includes(node.value) : !!result;
if (node.checked !== isChecked) node.checked = isChecked;
} else if (node.type === 'radio') {
if (node.checked !== (node.value === String(result ?? ''))) node.checked = (node.value === String(result ?? ''));
} else if ('value' in node && node.type !== 'file') {
Promise.resolve().then(() => { if (node.value !== String(result ?? '')) node.value = result; });
} else if (node.isContentEditable) {
if (node.innerHTML !== String(result ?? '')) node.innerHTML = result;
}
node.dispatchEvent(new CustomEvent('bind', { bubbles: false, detail: result }));
} else {
if (['checked', 'disabled', 'readonly'].includes(attr)) result = !!result;
if (typeof result === 'boolean') result ? node.setAttribute(attr, '') : node.removeAttribute(attr);
else if (result !== undefined) {
if (typeof result !== 'string') result = JSON.stringify(result);
if (attr === 'text') node.textContent = result ?? '';
else if (attr === 'html') node.innerHTML = result ?? '';
else if (node.tagName === 'IMG' && attr === 'src' && result.includes('.svg')) node.setAttribute('_src', result ?? '');
else if (attr === 'class') {
if (node._staticClasses === undefined) {
node._staticClasses = node.getAttribute('class') || '';
}
const staticClasses = node._staticClasses;
const finalClass = result ? (staticClasses ? `${result} ${staticClasses}` : result) : staticClasses;
node.setAttribute('class', finalClass.trim().replace(/\s+/g, ' '));
} else if (attr === 'style') {
if (node._staticStyles === undefined) {
node._staticStyles = node.getAttribute('style') || '';
}
const staticStyles = node._staticStyles;
const finalStyle = result ? (staticStyles ? `${result}; ${staticStyles}` : result) : staticStyles;
node.setAttribute('style', finalStyle.trim().replace(/;;+/g, ';').replace(/^;+\s*|;\s*$/g, ''));
} else node.setAttribute(attr, result ?? '');
}
}
}
}
export function _initBinding(binding) {
if (!binding.node._bindings) binding.node._bindings = [];
binding.node._bindings.push({ attr: binding.attr, prop: binding.prop, tpl: binding.tpl, exp: binding.exp });
_updateBinding(binding);
if (!binding.node._bindings) binding.node._bindings = [];
binding.node._bindings.push({ attr: binding.attr, prop: binding.prop, tpl: binding.tpl, exp: binding.exp });
_updateBinding(binding);
}
export function _parseNode(node, scanObj) {
if (node._bindings) {
node._states = new Set();
node._bindings.forEach(b => _updateBinding({ node, ...b }));
if (node._hasOnUpdate) node.dispatchEvent(new Event('update', { bubbles: false }));
return;
}
if (node._bindings) {
node._states = new Set();
node._bindings.forEach(b => _updateBinding({ node, ...b }));
if (node._hasOnUpdate) node.dispatchEvent(new Event('update', { bubbles: false }));
return;
}
if (Component.exists(node.tagName) && !node._componentInitialized) {
Array.from(node.attributes).forEach(attr => {
if (attr.name.startsWith('$.')) {
const realAttrName = attr.name.slice(2);
let tpl = _translate(attr.value);
if (scanObj.thisObj && tpl.includes('this.')) tpl = tpl.replace(/\bthis\./g, 'this.parent.');
const result = _returnCode(tpl, { thisNode: node }, { parent: scanObj.thisObj || node }, node._ref || {});
let o = node;
const prop = realAttrName.split('.');
for (let i = 0; i < prop.length - 1; i++) { if (prop[i]) o = (o[prop[i]] ??= {}); }
o[prop[prop.length - 1]] = result;
node.removeAttribute(attr.name);
}
});
_makeComponent(node.tagName, node, scanObj);
$$(node, '[slot-id]').forEach(p => p.removeAttribute('slot-id'));
node._componentInitialized = true;
if (!node._thisObj) node._thisObj = node;
}
if (Component.exists(node.tagName) && !node._componentInitialized) {
Array.from(node.attributes).forEach(attr => {
if (attr.name.startsWith('$.')) {
const realAttrName = attr.name.slice(2);
let tpl = _translate(attr.value);
if (scanObj.thisObj && tpl.includes('this.')) tpl = tpl.replace(/\bthis\./g, 'this.parent.');
const result = _returnCode(tpl, { thisNode: node }, { parent: scanObj.thisObj || node }, node._ref || {});
let o = node;
const prop = realAttrName.split('.');
for (let i = 0; i < prop.length - 1; i++) { if (prop[i]) o = (o[prop[i]] ??= {}); }
o[prop[prop.length - 1]] = result;
// node.removeAttribute(attr.name);
}
});
_makeComponent(node.tagName, node, scanObj);
$$(node, '[slot-id]').forEach(p => p.removeAttribute('slot-id'));
node._componentInitialized = true;
if (!node._thisObj) node._thisObj = node;
}
if (node.tagName === 'TEMPLATE') {
node._children = [...node.content.childNodes];
if (!node._renderedNodes) node._renderedNodes = [];
}
if (node.tagName === 'TEMPLATE') {
node._children = [...node.content.childNodes];
if (!node._renderedNodes) node._renderedNodes = [];
}
let attrs = [];
if (node.tagName === 'TEMPLATE') {
['$if', '$each', 'st-if', 'st-each'].forEach(n => node.hasAttribute(n) && attrs.push(node.getAttributeNode(n)));
} else {
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('.'));
}
let attrs = [];
if (node.tagName === 'TEMPLATE') {
['$if', '$each', 'st-if', 'st-each', '$$if', '$$each', 'st-st-if', 'st-st-each'].forEach(n => node.hasAttribute(n) && attrs.push(node.getAttributeNode(n)));
} else {
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('.'));
}
if (node._thisObj && scanObj.thisObj && node._thisObj !== scanObj.thisObj) node._thisObj.parent = scanObj.thisObj;
if (!node._thisObj) node._thisObj = scanObj.thisObj || null;
if (!node._ref) node._ref = scanObj.extendVars || {};
node._states = new Set();
attrs.forEach(attr => {
let exp = 0;
if (attr.name.startsWith('$$') || attr.name.startsWith('st-st-')) exp = 2;
else if (attr.name.startsWith('$') || attr.name.startsWith('st-')) exp = 1;
if (node._thisObj && scanObj.thisObj && node._thisObj !== scanObj.thisObj) node._thisObj.parent = scanObj.thisObj;
if (!node._thisObj) node._thisObj = scanObj.thisObj || null;
if (!node._ref) node._ref = scanObj.extendVars || {};
node._states = new Set();
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);
let tpl = attr.value;
node.removeAttribute(attr.name);
if (realAttrName.startsWith('.')) _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 {
if (realAttrName === 'bind') {
const isTextInput = (['INPUT', 'TEXTAREA'].includes(node.tagName) && ['textarea', 'text', 'password', 'email', 'number', 'search', 'url', 'tel'].includes(node.type || 'text')) || node.isContentEditable;
node.addEventListener(isTextInput ? '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, attr: realAttrName, tpl, exp }); }
}
});
attrs.forEach(attr => {
let exp = 0;
if (attr.name.startsWith('$$') || attr.name.startsWith('st-st-')) exp = 2;
else if (attr.name.startsWith('$') || attr.name.startsWith('st-')) exp = 1;
if (node._hasOnLoad || node._componentInitialized) Promise.resolve().then(() => node.dispatchEvent(new Event('load', { bubbles: false })));
if (node._hasOnUpdate) node.dispatchEvent(new Event('update', { bubbles: false }));
if (node._thisObj) scanObj.thisObj = node._thisObj;
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);
let tpl = attr.value;
node.removeAttribute(attr.name);
if (realAttrName.startsWith('.')) _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 {
if (realAttrName === 'bind') {
const isTextInput = (['INPUT', 'TEXTAREA'].includes(node.tagName) && ['textarea', 'text', 'password', 'email', 'number', 'search', 'url', 'tel'].includes(node.type || 'text')) || node.isContentEditable;
node.addEventListener(isTextInput ? '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, attr: realAttrName, tpl, exp }); }
}
});
if (node._hasOnLoad || node._componentInitialized) Promise.resolve().then(() => node.dispatchEvent(new Event('load', { bubbles: false })));
if (node._hasOnUpdate) node.dispatchEvent(new Event('update', { bubbles: false }));
if (node._thisObj) scanObj.thisObj = node._thisObj;
}
export const _scanTree = (node, scanObj = {}) => {
if (node.nodeType === 3) {
if (node._stTranslated) return;
const translated = _translate(node.textContent);
if (translated !== node.textContent) node.textContent = translated;
node._stTranslated = true;
return;
}
if (node.nodeType !== 1) return;
if (node.nodeType === 3) {
if (node._stTranslated) return;
const translated = _translate(node.textContent);
if (translated !== node.textContent) node.textContent = translated;
node._stTranslated = true;
return;
}
if (node.nodeType !== 1) return;
if (!node._stTranslated) {
Array.from(node.attributes).forEach(attr => {
if (!attr.name.startsWith('$') && !attr.name.startsWith('st-') && !attr.name.startsWith('.')) {
const translated = _translate(attr.value);
if (translated !== attr.value) attr.value = translated;
}
});
node._stTranslated = true;
}
if (!node._stTranslated) {
Array.from(node.attributes).forEach(attr => {
if (!attr.name.startsWith('$') && !attr.name.startsWith('st-') && !attr.name.startsWith('.')) {
const translated = _translate(attr.value);
if (translated !== attr.value) attr.value = translated;
}
});
node._stTranslated = true;
}
if (node.tagName !== 'TEMPLATE' && (node.hasAttribute('$if') || node.hasAttribute('$each') || node.hasAttribute('st-if') || node.hasAttribute('st-each'))) {
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)));
attrs.forEach(attr => {
template.setAttribute(attr.name, attr.value);
node.removeAttribute(attr.name);
});
node.parentNode.insertBefore(template, node);
template.content.appendChild(node);
template._ref = node._ref;
_scanTree(template, scanObj);
return;
}
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'))) {
const template = document.createElement('TEMPLATE');
const attrs = Array.from(node.attributes).filter(attr => ['$if', '$each', 'st-if', 'st-each', '$$if', '$$each', 'st-st-if', 'st-st-each'].includes(attr.name) || ((node.hasAttribute('$each') || node.hasAttribute('st-each') || node.hasAttribute('$$each') || node.hasAttribute('st-st-each')) && ['as', 'index'].includes(attr.name)));
attrs.forEach(attr => {
template.setAttribute(attr.name, attr.value);
node.removeAttribute(attr.name);
});
node.parentNode.insertBefore(template, node);
template.content.appendChild(node);
template._ref = node._ref;
_scanTree(template, scanObj);
return;
}
if (node.tagName === 'TEMPLATE' && (node.hasAttribute('$if') || node.hasAttribute('st-if')) && (node.hasAttribute('$each') || node.hasAttribute('st-each'))) {
const template = document.createElement('TEMPLATE');
const attrs = Array.from(node.attributes).filter(attr => ['$if', '$each', 'st-if', 'st-each'].includes(attr.name));
const attr = attrs[attrs.length - 1];
template.setAttribute(attr.name, attr.value);
node.removeAttribute(attr.name);
if (attr.name === '$each' || attr.name === 'st-each') {
Array.from(node.attributes).filter(attr => ['as', 'index'].includes(attr.name)).forEach(attr => { template.setAttribute(attr.name, attr.value); node.removeAttribute(attr.name); });
}
Array.from(node.content.childNodes).forEach(child => template.content.appendChild(child));
node.content.appendChild(template);
template._ref = node._ref;
}
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'))) {
const template = document.createElement('TEMPLATE');
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));
const attr = attrs[attrs.length - 1];
template.setAttribute(attr.name, attr.value);
node.removeAttribute(attr.name);
if (['$each', 'st-each', '$$each', 'st-st-each'].includes(attr.name)) {
Array.from(node.attributes).filter(attr => ['as', 'index'].includes(attr.name)).forEach(attr => { template.setAttribute(attr.name, attr.value); node.removeAttribute(attr.name); });
}
Array.from(node.content.childNodes).forEach(child => template.content.appendChild(child));
node.content.appendChild(template);
template._ref = node._ref;
}
if (node.tagName === 'IMG' && (node.hasAttribute('src') || node.hasAttribute('_src') || node.hasAttribute('$src'))) {
const imgNode = node;
Promise.resolve().then(() => {
const url = imgNode.getAttribute('_src') || imgNode.getAttribute('src');
if (url) fetch(url, { cache: 'force-cache' }).then(r => r.text()).then(svgText => {
const realSvg = new DOMParser().parseFromString(svgText, "image/svg+xml").querySelector('svg');
if (realSvg) {
Array.from(imgNode.attributes).forEach(attr => realSvg.setAttribute(attr.name, attr.value));
imgNode.replaceWith(realSvg);
}
});
});
}
if (node.tagName === 'IMG' && (node.hasAttribute('src') || node.hasAttribute('_src') || node.hasAttribute('$src'))) {
const imgNode = node;
Promise.resolve().then(() => {
const url = imgNode.getAttribute('_src') || imgNode.getAttribute('src');
if (url) fetch(url, { cache: 'force-cache' }).then(r => r.text()).then(svgText => {
const realSvg = new DOMParser().parseFromString(svgText, "image/svg+xml").querySelector('svg');
if (realSvg) {
Array.from(imgNode.attributes).forEach(attr => realSvg.setAttribute(attr.name, attr.value));
imgNode.replaceWith(realSvg);
}
});
});
}
if (node._thisObj !== undefined) scanObj.thisObj = node._thisObj || null;
else {
let curr = node;
while (curr && curr._thisObj === undefined) curr = curr.parentNode;
scanObj.thisObj = curr ? curr._thisObj : null;
}
if (node._thisObj !== undefined) scanObj.thisObj = node._thisObj || null;
else {
let curr = node;
while (curr && curr._thisObj === undefined) curr = curr.parentNode;
scanObj.thisObj = curr ? curr._thisObj : null;
}
if (node._ref === undefined) {
let curr = node;
while (curr && curr._ref === undefined) curr = curr.parentNode;
node._ref = curr ? { ...curr._ref } : {};
}
if (scanObj.extendVars) Object.assign(node._ref, scanObj.extendVars);
if (node._ref === undefined) {
let curr = node;
while (curr && curr._ref === undefined) curr = curr.parentNode;
node._ref = curr ? { ...curr._ref } : {};
}
if (scanObj.extendVars) Object.assign(node._ref, scanObj.extendVars);
_parseNode(node, { ...scanObj });
_parseNode(node, { ...scanObj });
const nodes = [...(node.childNodes || [])];
nodes.forEach(child => _scanTree(child, { thisObj: scanObj.thisObj, extendVars: { ...node._ref } }));
const nodes = [...(node.childNodes || [])];
nodes.forEach(child => _scanTree(child, { thisObj: scanObj.thisObj, extendVars: { ...node._ref } }));
};
export const _unbindTree = (node) => {
if (node.nodeType !== 1) return;
if (node._hasOnUnload) node.dispatchEvent(new Event('unload', { bubbles: false }));
if (node._states) node._states.forEach(mappings => {
for (const [key, bindingSet] of mappings) {
for (const binding of bindingSet) { if (binding.node === node) bindingSet.delete(binding); }
}
});
node.childNodes && node.childNodes.forEach(child => _unbindTree(child));
if (node.nodeType !== 1) return;
if (node._hasOnUnload) node.dispatchEvent(new Event('unload', { bubbles: false }));
if (node._states) node._states.forEach(mappings => {
for (const [key, bindingSet] of mappings) {
for (const binding of bindingSet) { if (binding.node === node) bindingSet.delete(binding); }
}
});
node.childNodes && node.childNodes.forEach(child => _unbindTree(child));
};
// 全局挂载

View File

@ -35,8 +35,8 @@ if (typeof document !== 'undefined') {
else document.addEventListener('DOMContentLoaded', init, true);
}
export { NewState } from './observer.js';
export { NewState, _setActiveBinding as setActiveBinding, _onNotifyUpdate as onNotifyUpdate } from './observer.js';
export { Component, SetTranslator } from './engine.js';
export { $, $$, Util } from './utils.js';
export { Hash, LocalStorage, State } from './core.js';
export { Hash, LocalStorage, State, _runCode, _returnCode } from './core.js';
export const __unsafeRefreshState = _scanTree;

View File

@ -4,7 +4,7 @@
*/
export const Util = {
clone: globalThis.structuredClone || (obj => JSON.parse(JSON.stringify(obj))),
clone: obj => JSON.parse(JSON.stringify(obj)),
base64: str => btoa(String.fromCharCode(...new TextEncoder().encode(str))),
unbase64: str => new TextDecoder().decode(Uint8Array.from(atob(str), c => c.charCodeAt(0))),
urlbase64: str => Util.base64(str).replace(/[+/=]/g, m => ({ '+': '-', '/': '', '=': '' }[m])),

View File

@ -1,6 +1,4 @@
{
"status": "failed",
"failedTests": [
"8a84b43f13b676ea22b7-5fcda25ae3a58304c071"
]
"status": "passed",
"failedTests": []
}

View File

@ -1,89 +0,0 @@
# Instructions
- Following Playwright test failed.
- Explain why, be concise, respect Playwright best practices.
- Provide a snippet of code with the fix, if possible.
# Test info
- Name: all.spec.js >> modular unit tests and benchmark
- Location: test/all.spec.js:5:1
# Error details
```
Error: expect(received).toBe(expected) // Object.is equality
Expected: "passed"
Received: "failed"
```
# Test source
```ts
1 | import { test, expect } from '@playwright/test';
2 | import fs from 'fs';
3 | import path from 'path';
4 |
5 | test('modular unit tests and benchmark', async ({ page }) => {
6 | page.on('console', msg => console.log('BROWSER LOG:', msg.text()));
7 | await page.goto('http://localhost:8081/test/index.html');
8 |
9 | await page.waitForFunction(() => window.testStatus !== undefined, { timeout: 10000 });
10 | const status = await page.evaluate(() => window.testStatus);
> 11 | expect(status).toBe('passed');
| ^ Error: expect(received).toBe(expected) // Object.is equality
12 |
13 | // Read benchmarks from TEST.md
14 | const testMd = fs.readFileSync(path.join(process.cwd(), 'TEST.md'), 'utf-8');
15 | const getBench = (name) => {
16 | const match = testMd.match(new RegExp(`\\*\\*${name}\\*\\*\\s*\\|\\s*([\\d.]+)`));
17 | return match ? parseFloat(match[1]) : null;
18 | };
19 | const baseInitial = getBench('首次渲染 \\(1000 items\\)');
20 | const baseUpdate = getBench('浅更新 \\(Shallow Update\\)');
21 |
22 | // Benchmark: Large list rendering
23 | const renderTime = await page.evaluate(async () => {
24 | const start = performance.now();
25 | document.body.innerHTML = `
26 | <ul id="bench-list">
27 | <template $each="state.benchItems" as="item">
28 | <li $text="item.val"></li>
29 | </template>
30 | </ul>
31 | `;
32 | const items = [];
33 | for(let i=0; i<1000; i++) items.push({val: 'item ' + i});
34 | window.state.benchItems = items;
35 | const { _unsafeRefreshState } = await import('@apigo.cc/state');
36 | _unsafeRefreshState(document.documentElement);
37 | return performance.now() - start;
38 | });
39 | console.log(`BENCHMARK: 1000 items initial render: ${renderTime.toFixed(2)}ms`);
40 | if (baseInitial) expect(renderTime).toBeLessThan(baseInitial * 1.2);
41 |
42 | // Benchmark: Large list update
43 | const updateTime = await page.evaluate(async () => {
44 | const start = performance.now();
45 | window.state.benchItems[0].val = 'updated';
46 | window.state.benchItems = [...window.state.benchItems];
47 | return performance.now() - start;
48 | });
49 | console.log(`BENCHMARK: 1000 items update (shallow): ${updateTime.toFixed(2)}ms`);
50 | if (baseUpdate) expect(updateTime).toBeLessThan(baseUpdate * 1.2);
51 |
52 | // Extreme Data Test
53 | await page.evaluate(async () => {
54 | const { _unsafeRefreshState } = await import('@apigo.cc/state');
55 | document.body.innerHTML = '<div id="extreme" $each="state.extreme"></div>';
56 | window.state.extreme = null;
57 | _unsafeRefreshState(document.getElementById('extreme'));
58 | window.state.extreme = undefined;
59 | window.state.extreme = { a: 1 };
60 | window.state.extreme = [1, 2];
61 | window.state.extreme = "not iterable";
62 | });
63 | });
64 |
```

View File

@ -32,8 +32,8 @@ test('modular unit tests and benchmark', async ({ page }) => {
const items = [];
for(let i=0; i<1000; i++) items.push({val: 'item ' + i});
window.state.benchItems = items;
const { ___unsafeRefreshState } = await import('@apigo.cc/state');
___unsafeRefreshState(document.documentElement);
const { __unsafeRefreshState } = window.ApigoState;
__unsafeRefreshState(document.documentElement);
return performance.now() - start;
});
console.log(`BENCHMARK: 1000 items initial render: ${renderTime.toFixed(2)}ms`);
@ -51,10 +51,10 @@ test('modular unit tests and benchmark', async ({ page }) => {
// Extreme Data Test
await page.evaluate(async () => {
const { ___unsafeRefreshState } = await import('@apigo.cc/state');
const { __unsafeRefreshState } = window.ApigoState;
document.body.innerHTML = '<div id="extreme" $each="state.extreme"></div>';
window.state.extreme = null;
___unsafeRefreshState(document.getElementById('extreme'));
__unsafeRefreshState(document.getElementById('extreme'));
window.state.extreme = undefined;
window.state.extreme = { a: 1 };
window.state.extreme = [1, 2];

View File

@ -1,16 +1,18 @@
// test/component.test.js
window.testComponent = async function() {
const { Component, ___unsafeRefreshState, $ } = ApigoState;
const { Component, __unsafeRefreshState, $ } = ApigoState;
console.log('Testing component.js...');
// 1. Register component
Component.register('TestComp', container => {
container.state.msg = 'Component Content';
}, document.createRange().createContextualFragment('<div id="comp-inner" $text="this.state.msg"></div>').firstChild);
}, document.createRange().createContextualFragment('<div><div id="comp-inner" $text="this.state.msg"></div></div>').firstChild);
// 2. Render component
document.body.innerHTML = '<TestComp id="comp-inst"></TestComp>';
___unsafeRefreshState(document.documentElement);
const comp = document.createElement('TestComp');
comp.id = 'comp-inst';
document.body.appendChild(comp);
__unsafeRefreshState(document.documentElement);
const instance = $('#comp-inst');
if (!instance) throw new Error('Component instance not found');

View File

@ -1,6 +1,6 @@
// test/dom.test.js
window.testDom = async function() {
const { ___unsafeRefreshState, $, $$, NewState } = ApigoState;
const { __unsafeRefreshState, $, $$, NewState } = ApigoState;
console.log('Testing dom.js...');
const wait = () => new Promise(r => setTimeout(r, 10));
@ -10,7 +10,7 @@ window.testDom = async function() {
const state = NewState({ msg: 'hello' });
window.state = state; // TRY: 确保在非 ESM 环境下 state 全局可见
document.documentElement._thisObj = { state };
___unsafeRefreshState(document.documentElement);
__unsafeRefreshState(document.documentElement);
if ($('#test-text').textContent !== 'hello') throw new Error('$text binding failed');
state.msg = 'world';
@ -20,7 +20,7 @@ window.testDom = async function() {
// 2. $if directive
document.body.innerHTML = '<template $if="state.show"><div id="test-if">visible</div></template>';
state.show = false;
___unsafeRefreshState(document.documentElement);
__unsafeRefreshState(document.documentElement);
if ($('#test-if')) throw new Error('$if fail: should be hidden');
state.show = true;
@ -30,7 +30,8 @@ window.testDom = async function() {
// 3. $each directive
document.body.innerHTML = '<template $each="state.items"><div class="test-item" $text="item"></div></template>';
state.items = ['A', 'B'];
___unsafeRefreshState(document.documentElement);
__unsafeRefreshState(document.documentElement);
await wait();
if ($$('.test-item').length !== 2) throw new Error('$each fail: count mismatch');
if ($$('.test-item')[0].textContent !== 'A') throw new Error('$each fail: content mismatch');
@ -41,14 +42,14 @@ window.testDom = async function() {
// 4. Event binding $onclick
document.body.innerHTML = '<button id="test-click" $onclick="state.count++"></button>';
state.count = 0;
___unsafeRefreshState(document.documentElement);
__unsafeRefreshState(document.documentElement);
$('#test-click').click();
if (state.count !== 1) throw new Error('$onclick failed');
// 5. $bind (input)
document.body.innerHTML = '<input id="test-bind" $bind="state.val">';
state.val = 'init';
___unsafeRefreshState(document.documentElement);
__unsafeRefreshState(document.documentElement);
await wait(); // TRY: 等待 $bind 的 setTimeout 完成
const input = $('#test-bind');
if (input.value !== 'init') throw new Error('$bind initial failed');
@ -74,13 +75,13 @@ window.testDom = async function() {
const root = $('#double-eval-root');
root._thisObj = { state: doubleState };
___unsafeRefreshState(root);
__unsafeRefreshState(root);
await wait();
if ($('#inner-node')) throw new Error('$$if failed: should be hidden initially');
console.log('Enabling inner node...');
doubleState.innerShow = true;
___unsafeRefreshState(root);
__unsafeRefreshState(root);
await wait();
const inner = $('#inner-node');
if (!inner) throw new Error('$$if failed: should be visible after innerShow=true');
@ -100,12 +101,12 @@ window.testDom = async function() {
nestedRoot._thisObj = { state: doubleState };
doubleState.outer = true;
doubleState.innerShow = false;
___unsafeRefreshState(nestedRoot);
__unsafeRefreshState(nestedRoot);
await wait();
if ($('#nested-inner')) throw new Error('nested $$if failed: should be hidden initially');
doubleState.innerShow = true;
___unsafeRefreshState(nestedRoot);
__unsafeRefreshState(nestedRoot);
await wait();
if (!$('#nested-inner')) throw new Error('nested $$if failed: should be visible after update');

View File

@ -1,6 +1,6 @@
// test/foundation.test.js
window.testFoundation = async function() {
const { ___unsafeRefreshState, Component, NewState, $, Util } = ApigoState;
const { __unsafeRefreshState, Component, NewState, $, Util } = ApigoState;
console.log('Testing framework foundation...');
Component.register('NavTest', container => {
@ -26,7 +26,7 @@ window.testFoundation = async function() {
const inst = document.createElement('NAVTEST');
inst.id = 'nav-inst';
document.body.appendChild(inst);
___unsafeRefreshState(document.documentElement);
__unsafeRefreshState(document.documentElement);
await new Promise(r => setTimeout(r, 100));
const nav = $('#nav-inst');

View File

@ -1,6 +1,6 @@
// test/inheritance.test.js
window.testInheritance = async function() {
const { ___unsafeRefreshState, Component, NewState, $, Util } = ApigoState;
const { __unsafeRefreshState, Component, NewState, $, Util } = ApigoState;
console.log('Testing inheritance...');
Component.register('MyComp', container => {
@ -26,7 +26,7 @@ window.testInheritance = async function() {
inst.id = 'comp-inst';
document.body.appendChild(inst);
___unsafeRefreshState(document.documentElement);
__unsafeRefreshState(document.documentElement);
await new Promise(r => setTimeout(r, 100));
const comp = $('#comp-inst');

View File

@ -1,14 +1,19 @@
// test/merging.test.js
window.testMerging = async function() {
const { Component, ___unsafeRefreshState, $ } = ApigoState;
const { Component, __unsafeRefreshState, $ } = ApigoState;
console.log('Testing complex class/style merging (DataTable Resizer scenario)...');
Component.register('Resizer-Real', container => {
container.isVertical = true;
}, document.createRange().createContextualFragment('<div $class="tpl-static ${this.isVertical?\'tpl-v\':\'tpl-h\'}" $style="color:blue"></div>').firstChild);
}, document.createRange().createContextualFragment('<div $class="tpl-static ${this.isVertical?\'tpl-v\':\'tpl-h\'}" $style="\'color:blue\'"></div>').firstChild);
document.body.innerHTML = '<Resizer-Real id="res-inst" class="ins-static" style="opacity:0.5"></Resizer-Real>';
___unsafeRefreshState(document.documentElement);
const res = document.createElement('Resizer-Real');
res.id = 'res-inst';
res.className = 'ins-static';
res.setAttribute('style', 'opacity:0.5');
res.setAttribute('$class', "'ins-dynamic'");
document.body.appendChild(res);
__unsafeRefreshState(document.documentElement);
await new Promise(r => setTimeout(r, 50));
const inst = $('#res-inst');
@ -17,9 +22,14 @@ window.testMerging = async function() {
const classList = Array.from(inst.classList);
console.log('Final ClassList:', classList);
if (!classList.includes('ins-static') || !classList.includes('tpl-static')) {
if (!classList.includes('ins-static') || !classList.includes('tpl-static') || !classList.includes('ins-dynamic')) {
throw new Error('Class merging failed');
}
const tplIndex = classList.indexOf('tpl-static');
const insIndex = classList.indexOf('ins-static');
if (tplIndex > insIndex) {
throw new Error('Class merging order incorrect: tpl-static should be before ins-static');
}
const style = inst.getAttribute('style');
console.log('Final Style:', style);

View File

@ -1,14 +1,16 @@
// test/priority.test.js
window.testPriority = async function() {
const { ___unsafeRefreshState, $, NewState } = ApigoState;
const { __unsafeRefreshState, $, NewState } = ApigoState;
console.log('Testing directive priorities...');
// Test $if vs $text (if should hide text)
document.body.innerHTML = '<div id="prio-test" $if="state.hide" $text="state.msg"></div>';
document.body.innerHTML = '<div id="prio-test" $if="!state.hide" $text="state.msg"></div>';
const state = NewState({ hide: false, msg: 'visible' });
window.state = state;
document.documentElement._thisObj = { state };
___unsafeRefreshState(document.documentElement);
__unsafeRefreshState(document.documentElement);
await new Promise(r => setTimeout(r, 20));
if ($('#prio-test').textContent !== 'visible') throw new Error('Basic visibility failed');
state.hide = true;

View File

@ -1,6 +1,6 @@
// test/timing.test.js
window.testTiming = async function() {
const { ___unsafeRefreshState, Component, NewState, $, Util } = ApigoState;
const { __unsafeRefreshState, Component, NewState, $, Util } = ApigoState;
console.log('Testing initialization timing...');
Component.register('TimingComp', container => {
@ -14,7 +14,7 @@ window.testTiming = async function() {
`));
document.body.innerHTML += `<TimingComp id="timing-inst"></TimingComp>`;
___unsafeRefreshState(document.documentElement);
__unsafeRefreshState(document.documentElement);
await new Promise(r => setTimeout(r, 100));