release: v1.0.2

This commit is contained in:
AI Engineer 2026-05-17 16:48:29 +08:00
parent 9a3312ce25
commit d4211fc2d3
9 changed files with 377 additions and 354 deletions

View File

@ -1,5 +1,13 @@
# CHANGELOG # CHANGELOG
## v1.0.2 (2026-05-17)
### 优化
- **稳定性**: `src/dom.js` 中的 `bind` 属性逻辑改为使用 `setTimeout` 确保 DOM 更新完成后同步值,提高双向绑定在高频操作下的可靠性。
- **健壮性**: `src/observer.js``NewState` 增加对已观察对象的检查,防止重复包装导致的性能损耗。
- **功能**: `src/dom.js``_translator` 支持 `{key}` 模板替换,增强国际化组件的灵活性。
- **清理**: 全面规范代码缩进Tab移除 `src/core.js` 中的调试注释。
## v1.0.1 (2026-05-15) ## v1.0.1 (2026-05-15)
### 优化 ### 优化

10
dist/state.js vendored
View File

@ -14,6 +14,7 @@ function onNotifyUpdate(fn) {
_updateBindingFn = fn; _updateBindingFn = fn;
} }
function NewState(defaults = {}, getter = null, setter = null) { function NewState(defaults = {}, getter = null, setter = null) {
if (defaults && defaults.__watch) return defaults;
const _defaults = {}; const _defaults = {};
const _stateMappings = /* @__PURE__ */ new Map(); const _stateMappings = /* @__PURE__ */ new Map();
const _watchers = /* @__PURE__ */ new Map(); const _watchers = /* @__PURE__ */ new Map();
@ -101,7 +102,12 @@ function _returnCode(code, vars, thisObj, extendVars) {
if (code.includes("${")) return _runCode("return `" + code + "`", vars, thisObj, extendVars); if (code.includes("${")) return _runCode("return `" + code + "`", vars, thisObj, extendVars);
else return _runCode("return " + code, vars, thisObj, extendVars); else return _runCode("return " + code, vars, thisObj, extendVars);
} }
let _translator = (text) => text; let _translator = (text, args) => {
if (!text || typeof text !== "string") return text;
return text.replace(/\{(.+?)\}/g, (match, key) => {
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") return text; if (!text || typeof text !== "string") return text;
@ -248,7 +254,7 @@ function _updateBinding(binding) {
} 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") {
Promise.resolve().then(() => { 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) {

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": "@web/state", "name": "@web/state",
"version": "1.0.0", "version": "1.0.2",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@web/state", "name": "@web/state",
"version": "1.0.0", "version": "1.0.2",
"devDependencies": { "devDependencies": {
"@playwright/test": "^1.40.0", "@playwright/test": "^1.40.0",
"@rollup/plugin-terser": "^1.0.0", "@rollup/plugin-terser": "^1.0.0",

View File

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

View File

@ -2,23 +2,23 @@
let _disableRunCodeError = false; let _disableRunCodeError = false;
export function setDisableRunCodeError(value) { export function setDisableRunCodeError(value) {
_disableRunCodeError = value; _disableRunCodeError = value;
} }
export function _runCode(code, vars, thisObj, extendVars) { export function _runCode(code, vars, thisObj, extendVars) {
const argKeys = [...Object.keys(extendVars || {}), ...Object.keys(vars || {})]; const argKeys = [...Object.keys(extendVars || {}), ...Object.keys(vars || {})];
const argValues = [...Object.values(extendVars || {}), ...Object.values(vars || {})]; const argValues = [...Object.values(extendVars || {}), ...Object.values(vars || {})];
argKeys.push(code); argKeys.push(code);
try { try {
const r = new Function(...argKeys).apply(thisObj, argValues); const r = new Function(...argKeys).apply(thisObj, argValues);
return r; return r;
} catch (e) { } catch (e) {
if (!_disableRunCodeError) console.error(e, extendVars, [code, extendVars, vars, thisObj]); if (!_disableRunCodeError) console.error(e, extendVars, [code, extendVars, vars, thisObj]);
return null; return null;
} }
} }
export function _returnCode(code, vars, thisObj, extendVars) { export function _returnCode(code, vars, thisObj, extendVars) {
if (code.includes('${')) return _runCode('return `' + code + '`', vars, thisObj, extendVars); if (code.includes('${')) return _runCode('return `' + code + '`', vars, thisObj, extendVars);
else return _runCode('return ' + code, vars, thisObj, extendVars); else return _runCode('return ' + code, vars, thisObj, extendVars);
} }

View File

@ -4,36 +4,41 @@ import { getActiveBinding, setActiveBinding, getNoWriteBack, setNoWriteBack, New
import { Component, _makeComponent, _mergeNode } from './component.js'; import { Component, _makeComponent, _mergeNode } from './component.js';
import { $, $$ } from './dom-utils.js'; import { $, $$ } from './dom-utils.js';
let _translator = (text) => text; let _translator = (text, args) => {
if (!text || typeof text !== 'string') return text;
return text.replace(/\{(.+?)\}/g, (match, key) => {
return args.hasOwnProperty(key) ? args[key] : match;
})
};
export const SetTranslator = (fn) => _translator = fn; export const SetTranslator = (fn) => _translator = fn;
const _translate = (text) => { const _translate = (text) => {
if (!text || typeof text !== 'string') return text; if (!text || typeof text !== 'string') 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 rawText = parts[0];
const args = {}; const args = {};
if (parts.length > 1) { if (parts.length > 1) {
const matches = rawText.match(/\{(.+?)\}/g); const matches = rawText.match(/\{(.+?)\}/g);
if (matches) matches.forEach((match, i) => { if (matches) matches.forEach((match, i) => {
const key = match.substring(1, match.length - 1); const key = match.substring(1, match.length - 1);
args[key] = parts[i + 1] || ''; args[key] = parts[i + 1] || '';
}); });
} }
return _translator(rawText, args); return _translator(rawText, args);
}); });
}; };
if (typeof document !== 'undefined') { if (typeof document !== 'undefined') {
try { try {
document.createElement('div').setAttribute('$t', '1'); document.createElement('div').setAttribute('$t', '1');
} catch (e) { } 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);
return originalSetAttribute.call(this, 'st-' + name.substring(1), value); return originalSetAttribute.call(this, 'st-' + name.substring(1), value);
}; };
} }
} }
export { $, $$ }; export { $, $$ };
@ -41,334 +46,335 @@ 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; const tpl = binding.tpl;
const exp = binding.exp; 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 = exp ? (tpl ? _returnCode(tpl, { thisNode: node }, node._thisObj || node, node._ref || null) : null) : tpl;
setActiveBinding(null); setActiveBinding(null);
if (binding.prop) { if (binding.prop) {
const prop = binding.prop; const prop = binding.prop;
let o = node; let o = node;
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]) continue;
if (o[prop[i]] == null) o[prop[i]] = {}; if (o[prop[i]] == null) o[prop[i]] = {};
o = o[prop[i]]; o = o[prop[i]];
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 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 (resultIsObject && 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 (resultIsObject && typeof o === 'object') {
Object.assign(o, result); Object.assign(o, result);
} }
} }
} else if (binding.attr) { } else if (binding.attr) {
const attr = binding.attr; const attr = binding.attr;
if (attr === 'if') { if (attr === 'if') {
if (result) { if (result) {
if (!node._renderedNodes || node._renderedNodes.length === 0) { if (!node._renderedNodes || node._renderedNodes.length === 0) {
node._children.forEach(child => { node._children.forEach(child => {
node.parentNode.insertBefore(child, node); node.parentNode.insertBefore(child, node);
child._ref = { ...node._ref }; child._ref = { ...node._ref };
}); });
node._renderedNodes = [node._children]; node._renderedNodes = [node._children];
} }
} else { } else {
_clearRenderedNodes(node); _clearRenderedNodes(node);
node._renderedNodes = []; node._renderedNodes = [];
} }
} else if (attr === 'each') { } else if (attr === 'each') {
if (result && typeof result === 'object') { if (result && typeof result === 'object') {
const asName = node.getAttribute('as') || 'item'; const asName = node.getAttribute('as') || 'item';
const indexName = node.getAttribute('index') || 'index'; const indexName = node.getAttribute('index') || 'index';
let keys, getVal; let keys, getVal;
if (result instanceof Map) { if (result instanceof Map) {
keys = Array.from(result.keys()); keys = Array.from(result.keys());
getVal = k => result.get(k); getVal = k => result.get(k);
} else if (typeof result[Symbol.iterator] === 'function') { } else if (typeof result[Symbol.iterator] === 'function') {
const arr = Array.isArray(result) ? result : Array.from(result); const arr = Array.isArray(result) ? result : Array.from(result);
keys = new Array(arr.length); keys = new Array(arr.length);
for (let i = 0; i < arr.length; i++) keys[i] = i; for (let i = 0; i < arr.length; i++) keys[i] = i;
getVal = k => arr[k]; getVal = k => arr[k];
} else { } else {
keys = Object.keys(result); keys = Object.keys(result);
getVal = k => result[k]; getVal = k => result[k];
} }
keys.forEach((k, i) => { keys.forEach((k, i) => {
const item = getVal(k); const item = getVal(k);
if (node._renderedNodes && i < node._renderedNodes.length) { if (node._renderedNodes && i < node._renderedNodes.length) {
node._renderedNodes[i].forEach(child => { node._renderedNodes[i].forEach(child => {
child._ref[indexName] = k; child._ref[indexName] = k;
child._ref[asName] = item; child._ref[asName] = item;
_scanTree(child); _scanTree(child);
}); });
} else { } else {
const newNodes = []; const newNodes = [];
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 };
cloned._ref[indexName] = k; cloned._ref[indexName] = k;
cloned._ref[asName] = item; 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);
}); });
node._renderedNodes.push(newNodes); node._renderedNodes.push(newNodes);
} }
}); });
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[node._renderedNodes.length - 1].forEach(child => {
_clearRenderedNodes(child); _clearRenderedNodes(child);
child.remove(); child.remove();
}); });
node._renderedNodes.pop(); 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)) {
if (!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(`${tpl} = []`, { thisNode: node }, node._thisObj || node, node._ref || {});
result = []; 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') {
Promise.resolve().then(() => { // 这里必须用宏任务微任务不足以确保DOM更新完成
if (node.value !== String(result ?? '')) node.value = result; setTimeout(() => {
}); if (node.value !== String(result ?? '')) node.value = result;
} else if (node.isContentEditable) { });
if (node.innerHTML !== String(result ?? '')) node.innerHTML = result; } else if (node.isContentEditable) {
} if (node.innerHTML !== String(result ?? '')) node.innerHTML = result;
node.dispatchEvent(new CustomEvent('bind', { bubbles: false, detail: result })); }
} else { node.dispatchEvent(new CustomEvent('bind', { bubbles: false, detail: result }));
if (['checked', 'disabled', 'readonly'].includes(attr)) result = !!result; } else {
if (typeof result === 'boolean') { if (['checked', 'disabled', 'readonly'].includes(attr)) result = !!result;
result ? node.setAttribute(attr, '') : node.removeAttribute(attr); if (typeof result === 'boolean') {
} else if (result !== undefined) { result ? node.setAttribute(attr, '') : node.removeAttribute(attr);
if (typeof result !== 'string') result = JSON.stringify(result); } else if (result !== undefined) {
if (attr === 'text') { if (typeof result !== 'string') result = JSON.stringify(result);
node.textContent = result ?? ''; if (attr === 'text') {
} else if (attr === 'html') { node.textContent = result ?? '';
node.innerHTML = result ?? ''; } else if (attr === 'html') {
} else if (node.tagName === 'IMG' && attr === 'src' && result.includes('.svg')) { node.innerHTML = result ?? '';
node.setAttribute('_src', result ?? ''); } else if (node.tagName === 'IMG' && attr === 'src' && result.includes('.svg')) {
} else { node.setAttribute('_src', result ?? '');
node.setAttribute(attr, result ?? ''); } else {
} node.setAttribute(attr, result ?? '');
} }
} }
} }
}
} }
export const _initBinding = (binding) => { export const _initBinding = (binding) => {
if (!binding.node._bindings) binding.node._bindings = []; if (!binding.node._bindings) binding.node._bindings = [];
binding.node._bindings.push(binding); binding.node._bindings.push(binding);
_updateBinding(binding); _updateBinding(binding);
}; };
export const _parseNode = (node, scanObj) => { export const _parseNode = (node, scanObj) => {
if (Component.exists(node.tagName) && !node._componentInitialized) { if (Component.exists(node.tagName) && !node._componentInitialized) {
node._componentInitialized = true; node._componentInitialized = true;
_makeComponent(node.tagName, node, scanObj); _makeComponent(node.tagName, node, scanObj);
$$(node, '[slot-id]').forEach(placeholder => placeholder.removeAttribute('slot-id')); $$(node, '[slot-id]').forEach(placeholder => placeholder.removeAttribute('slot-id'));
if (!node._thisObj) node._thisObj = node; if (!node._thisObj) node._thisObj = node;
} }
if (node._bindings) { if (node._bindings) {
node._bindings.forEach(binding => _updateBinding(binding)); node._bindings.forEach(binding => _updateBinding(binding));
if (node._hasOnUpdate) node.dispatchEvent(new Event('update', { bubbles: false })); if (node._hasOnUpdate) node.dispatchEvent(new Event('update', { bubbles: false }));
return; return;
} }
let attrs = []; let attrs = [];
if (node.tagName === 'TEMPLATE') { if (node.tagName === 'TEMPLATE') {
node._children = [...node.content.childNodes]; node._children = [...node.content.childNodes];
node._renderedNodes = []; node._renderedNodes = [];
if (node.hasAttribute('$if')) attrs.push(node.getAttributeNode('$if')); if (node.hasAttribute('$if')) attrs.push(node.getAttributeNode('$if'));
else if (node.hasAttribute('$each')) attrs.push(node.getAttributeNode('$each')); else if (node.hasAttribute('$each')) attrs.push(node.getAttributeNode('$each'));
else if (node.hasAttribute('st-if')) attrs.push(node.getAttributeNode('st-if')); else if (node.hasAttribute('st-if')) attrs.push(node.getAttributeNode('st-if'));
else if (node.hasAttribute('st-each')) attrs.push(node.getAttributeNode('st-each')); else if (node.hasAttribute('st-each')) attrs.push(node.getAttributeNode('st-each'));
} 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(attr => (attr.name.startsWith('$') || attr.name.startsWith('st-')) && !['$if', '$each', 'st-if', 'st-each'].includes(attr.name) || attr.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;
if (!node._ref) node._ref = scanObj.extendVars || {}; if (!node._ref) node._ref = scanObj.extendVars || {};
attrs.forEach(attr => { attrs.forEach(attr => {
const exp = attr.name.startsWith('$') || attr.name.startsWith('st-'); const exp = attr.name.startsWith('$') || attr.name.startsWith('st-');
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: node, prop: realAttrName.split('.'), tpl, exp }); _initBinding({ node: node, prop: realAttrName.split('.'), tpl, exp });
} else { } else {
if (realAttrName.startsWith('on')) { if (realAttrName.startsWith('on')) {
if (realAttrName === 'onupdate') node._hasOnUpdate = true; if (realAttrName === 'onupdate') node._hasOnUpdate = true;
if (realAttrName === 'onload' && !['BODY', 'IMG', 'IFRAME'].includes(node.tagName)) node._hasOnLoad = true; if (realAttrName === 'onload' && !['BODY', 'IMG', 'IFRAME'].includes(node.tagName)) node._hasOnLoad = true;
if (realAttrName === 'onunload' && !['BODY', 'IMG', 'IFRAME'].includes(node.tagName)) node._hasOnUnload = true; if (realAttrName === 'onunload' && !['BODY', 'IMG', 'IFRAME'].includes(node.tagName)) node._hasOnUnload = true;
((node, thisObj) => { ((node, thisObj) => {
node.addEventListener(realAttrName.slice(2), (e) => { node.addEventListener(realAttrName.slice(2), (e) => {
_runCode(tpl, { event: e, thisNode: node, ...(e.detail || {}) }, thisObj || node, node._ref || {}); _runCode(tpl, { event: e, thisNode: node, ...(e.detail || {}) }, thisObj || node, node._ref || {});
}); });
})(node, scanObj.thisObj); })(node, scanObj.thisObj);
} else { } else {
if (realAttrName === 'bind') { if (realAttrName === 'bind') {
node.addEventListener(node.tagName === 'TEXTAREA' || node.isContentEditable || node.type === 'text' || node.type === 'password' ? 'input' : 'change', (e) => { 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); let newVal = node.isContentEditable ? e.target.innerHTML : (node.type === 'checkbox' ? e.target.checked : e.target.files || e.target.value || e.detail);
setNoWriteBack(node); setNoWriteBack(node);
setDisableRunCodeError(true); setDisableRunCodeError(true);
if (node.type === 'checkbox' && node._checkboxMultiMode) { 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 || {}); _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 { } else {
_runCode(`${tpl} = val`, { val: newVal, thisNode: node }, scanObj.thisObj || node, node._ref || {}); _runCode(`${tpl} = val`, { val: newVal, thisNode: node }, scanObj.thisObj || node, node._ref || {});
} }
setDisableRunCodeError(false); setDisableRunCodeError(false);
setNoWriteBack(null); setNoWriteBack(null);
}); });
} else if (realAttrName === 'text' && !tpl) { } else if (realAttrName === 'text' && !tpl) {
tpl = node.textContent; tpl = node.textContent;
node.textContent = ''; node.textContent = '';
} }
if (tpl) { if (tpl) {
tpl = _translate(tpl); tpl = _translate(tpl);
_initBinding({ node: node, attr: realAttrName, tpl, exp }); _initBinding({ node: node, attr: realAttrName, tpl, exp });
} }
} }
} }
}); });
if (node._hasOnLoad || node._componentInitialized) { if (node._hasOnLoad || node._componentInitialized) {
(node => { (node => {
Promise.resolve().then(() => node.dispatchEvent(new Event('load', { bubbles: false }))); Promise.resolve().then(() => node.dispatchEvent(new Event('load', { bubbles: false })));
})(node); })(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;
}; };
export const _scanTree = (node, scanObj = {}) => { export const _scanTree = (node, scanObj = {}) => {
if (node.nodeType === 3) { if (node.nodeType === 3) {
const translated = _translate(node.textContent); const translated = _translate(node.textContent);
if (translated !== node.textContent) node.textContent = translated; if (translated !== node.textContent) node.textContent = translated;
return; return;
} }
if (node.nodeType !== 1) return; if (node.nodeType !== 1) return;
Array.from(node.attributes).forEach(attr => { Array.from(node.attributes).forEach(attr => {
if (!attr.name.startsWith('$') && !attr.name.startsWith('st-') && !attr.name.startsWith('.')) { if (!attr.name.startsWith('$') && !attr.name.startsWith('st-') && !attr.name.startsWith('.')) {
const translated = _translate(attr.value); const translated = _translate(attr.value);
if (translated !== attr.value) attr.value = translated; if (translated !== attr.value) attr.value = translated;
} }
}); });
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); template.setAttribute(attr.name, attr.value);
node.removeAttribute(attr.name); 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; 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'))) {
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)); const attrs = Array.from(node.attributes).filter(attr => ['$if', '$each', 'st-if', 'st-each'].includes(attr.name));
const attr = attrs[attrs.length - 1]; const attr = attrs[attrs.length - 1];
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); template.setAttribute(attr.name, attr.value);
node.removeAttribute(attr.name); 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;
} }
if (node.tagName === 'IMG' && (node.hasAttribute('src') || node.hasAttribute('_src') || node.hasAttribute('$src'))) { if (node.tagName === 'IMG' && (node.hasAttribute('src') || node.hasAttribute('_src') || node.hasAttribute('$src'))) {
const imgNode = node; const imgNode = node;
Promise.resolve().then(() => { Promise.resolve().then(() => {
const url = imgNode.getAttribute('_src') || imgNode.getAttribute('src'); const url = imgNode.getAttribute('_src') || imgNode.getAttribute('src');
if (url) fetch(url, { cache: 'force-cache' }).then(r => r.text()).then(svgText => { if (url) fetch(url, { cache: 'force-cache' }).then(r => r.text()).then(svgText => {
const realSvg = new DOMParser().parseFromString(svgText, "image/svg+xml").querySelector('svg'); const realSvg = new DOMParser().parseFromString(svgText, "image/svg+xml").querySelector('svg');
if (realSvg) { if (realSvg) {
Array.from(imgNode.attributes).forEach(attr => realSvg.setAttribute(attr.name, attr.value)); Array.from(imgNode.attributes).forEach(attr => realSvg.setAttribute(attr.name, attr.value));
imgNode.replaceWith(realSvg); imgNode.replaceWith(realSvg);
} }
}); });
}); });
} }
if (node._thisObj !== undefined) scanObj.thisObj = node._thisObj || null; if (node._thisObj !== undefined) scanObj.thisObj = node._thisObj || null;
if (scanObj.thisObj === undefined) { if (scanObj.thisObj === undefined) {
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;
} }
if (node._ref === undefined) { if (node._ref === undefined) {
let curr = node; let curr = node;
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 === undefined) scanObj.extendVars = {};
if (node._ref !== undefined) { if (node._ref !== undefined) {
Object.assign(node._ref, scanObj.extendVars); Object.assign(node._ref, scanObj.extendVars);
scanObj.extendVars = { ...node._ref }; scanObj.extendVars = { ...node._ref };
} }
_parseNode(node, scanObj); _parseNode(node, scanObj);
const nodes = [...(node.childNodes || [])]; const nodes = [...(node.childNodes || [])];
scanObj.extendVars = node._ref || scanObj.extendVars; scanObj.extendVars = node._ref || scanObj.extendVars;
nodes.forEach(child => _scanTree(child, { thisObj: scanObj.thisObj, extendVars: { ...node._ref } })); nodes.forEach(child => _scanTree(child, { thisObj: scanObj.thisObj, extendVars: { ...node._ref } }));
}; };
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._bindings) { if (node._bindings) {
node._bindings.forEach(binding => { node._bindings.forEach(binding => {
if (binding._sets) { if (binding._sets) {
binding._sets.forEach(set => set.delete(binding)); binding._sets.forEach(set => set.delete(binding));
binding._sets.clear(); binding._sets.clear();
} }
}); });
} }
node.childNodes && node.childNodes.forEach(child => _unbindTree(child)); node.childNodes && node.childNodes.forEach(child => _unbindTree(child));
}; };
export const RefreshState = _scanTree; export const RefreshState = _scanTree;

View File

@ -15,6 +15,7 @@ export function onNotifyUpdate(fn) {
} }
export function NewState(defaults = {}, getter = null, setter = null) { export function NewState(defaults = {}, getter = null, setter = null) {
if (defaults && defaults.__watch) return defaults
const _defaults = {}; const _defaults = {};
const _stateMappings = new Map(); const _stateMappings = new Map();
const _watchers = new Map(); const _watchers = new Map();

View File

@ -26,12 +26,14 @@ export async function testDom() {
RefreshState(document.documentElement); RefreshState(document.documentElement);
if ($('#if-content')) throw new Error('$if failed: should be hidden'); if ($('#if-content')) throw new Error('$if failed: should be hidden');
const wait = () => new Promise(r => setTimeout(r, 10));
state.show = true; state.show = true;
await Promise.resolve(); await wait();
if (!$('#if-content') || $('#if-content').textContent !== 'Visible') throw new Error('$if failed: should be visible'); if (!$('#if-content') || $('#if-content').textContent !== 'Visible') throw new Error('$if failed: should be visible');
state.show = false; state.show = false;
await Promise.resolve(); await wait();
if ($('#if-content')) throw new Error('$if failed: should be hidden again'); if ($('#if-content')) throw new Error('$if failed: should be hidden again');
// 3. $each directive (Index-based reuse) // 3. $each directive (Index-based reuse)
@ -44,7 +46,7 @@ export async function testDom() {
`; `;
state.items = [{ name: 'A' }, { name: 'B' }]; state.items = [{ name: 'A' }, { name: 'B' }];
RefreshState(document.documentElement); RefreshState(document.documentElement);
await Promise.resolve(); // Wait for MutationObserver await wait(); // Wait for MutationObserver
let items = $$('#list-test li'); let items = $$('#list-test li');
console.log('$each items length:', items.length); console.log('$each items length:', items.length);
if (items.length > 0) console.log('$each first item text:', items[0].textContent); if (items.length > 0) console.log('$each first item text:', items[0].textContent);
@ -52,13 +54,13 @@ export async function testDom() {
const firstNode = items[0]; const firstNode = items[0];
state.items = [{ name: 'A-mod' }, { name: 'B' }, { name: 'C' }]; state.items = [{ name: 'A-mod' }, { name: 'B' }, { name: 'C' }];
await Promise.resolve(); await wait();
items = $$('#list-test li'); items = $$('#list-test li');
if (items.length !== 3 || items[0].textContent !== 'A-mod') throw new Error('$each update failed'); if (items.length !== 3 || items[0].textContent !== 'A-mod') throw new Error('$each update failed');
if (items[0] !== firstNode) throw new Error('$each reuse failed: should reuse existing DOM nodes'); if (items[0] !== firstNode) throw new Error('$each reuse failed: should reuse existing DOM nodes');
state.items = [{ name: 'C' }]; state.items = [{ name: 'C' }];
await Promise.resolve(); await wait();
items = $$('#list-test li'); items = $$('#list-test li');
if (items.length !== 1 || items[0].textContent !== 'C') throw new Error('$each removal failed'); if (items.length !== 1 || items[0].textContent !== 'C') throw new Error('$each removal failed');
@ -66,7 +68,7 @@ export async function testDom() {
document.body.innerHTML = `<input id="input-test" $bind="state.val">`; document.body.innerHTML = `<input id="input-test" $bind="state.val">`;
state.val = 'initial'; state.val = 'initial';
RefreshState(document.documentElement); RefreshState(document.documentElement);
await Promise.resolve(); await wait();
const input = $('#input-test'); const input = $('#input-test');
if (input.value !== 'initial') throw new Error('$bind initial value failed'); if (input.value !== 'initial') throw new Error('$bind initial value failed');