release: v1.0.13 By: AICoder

This commit is contained in:
AI Engineer 2026-06-05 19:03:52 +08:00
parent e77a69d6cc
commit b04be8d437
11 changed files with 1514 additions and 837 deletions

212
README.md
View File

@ -1,174 +1,80 @@
# State.js AI 开发指南
# @apigo.cc/state - AI 逻辑操作说明书
> ⚠️ **AI 强制指令 (AI Mandate):**
> 1. **尊重原创逻辑**本项目State.js核心架构极其精炼且经过精雕细琢。**严禁擅自修改原有逻辑**(如 `_returnCode`, `_runCode`, `NewState` 等底层函数),除非你能证明修改后的质量、性能与简洁度均显著优于原版。
> 2. **禁止过度设计**:不要尝试引入复杂的编译器、多语句解析器或防御性代码。任何试图将“简单问题复杂化”的重构大概率会破坏现有结构。
> 3. **汇报与许可**:若你认为有必要修改库的核心逻辑,**必须首先向人类开发者汇报修改的必要性与潜在影响**,只有在得到明确允许后方可进行。
> 4. **回归测试**:任何改动必须通过现有 Playwright 自动化测试,确保 `DataTable` 等复杂组件场景的渲染与合并逻辑完全正常。
本框架基于原生 `Proxy``MutationObserver` 实现数据与 DOM 的原子级同步。本手册仅供 AI 构建、维护及驱动基于此引擎的应用。
State.js 是基于 Vanilla JS 的无编译数据驱动 UI 框架。依赖原生 DOM 与 Proxy通过解析 HTML `$指令` 属性映射状态。
---
> **核心设定:** 你是一个追求极致代码压缩和执行效率的资深极客。
> **编码原则:**
> 1. **拒绝废话变量:** 除非一个变量会被复用两次以上,否则**绝对禁止**声明临时变量。
> 2. **极致精简:** 极度偏爱链式调用Chaining、短路求值、三元运算符和 One-liner。能一行写完的逻辑绝不拆成三行。
> 3. **无解释模式:** 假设你的对话者是顶尖黑客,不需要解释基础 API不需要防御性废话直接给出最硬核的最终代码即可。
## 1. 核心状态逻辑映射
## 一、 核心语法与指令字典
### `NewState(defaults, getter, setter)`
* **功能**:创建响应式代理。
* **内部机制**:拦截所有属性读写。若属性值变更,触发所有引用该属性的 DOM 节点的更新任务(异步微任务)。
* **扩展逻辑**:通过 `getter/setter` 拦截器可实现数据持久化(如同步至 URL Hash 或 LocalStorage
* **原子操作**
* `obj.__watch(key, cb)`: 建立 key -> callback 的直接依赖。
* `obj.__unwatch(key, cb)`: 解除依赖。
### 1\. 属性与数据绑定矩阵
---
| 语法 | 类型 | 解析与执行规则 |
## 2. 指令映射全集 (AI-Ready)
指令语法:`$attribute="code"`。作用域默认为全局,组件内优先访问 `node.state`
### 结构化映射
| 指令 | 触发逻辑 | DOM 行为 |
| :--- | :--- | :--- |
| `$attr="exp"` | 动态 JS 表达式 | 映射为 HTML 属性。若包含 `\${}`,作为模板字符串计算;若不包含,作为纯 JS 表达式执行并保留返回值类型。 |
| `$$attr="exp"` | 双重计算表达式 | **二次评估机制**:首先评估 `exp` 获取字符串结果,若结果为字符串,则将其作为代码再次执行。适用于动态指令场景(如后端下发指令)。 |
| `.prop="val"` | 静态 DOM 属性 | 将字符串字面量赋值给底层 DOM 节点的 JS 属性。 |
| `$.prop="exp"` | 动态 DOM 属性 | 将 JS 执行结果赋值给底层 DOM 节点的 JS 属性。<br>**对象自动初始化**:对深层路径(如 `$.state.schema`)赋值时,若路径上的中间节点不存在,框架会自动生成空对象(`{}`)以防止报错。 |
| `$bind="exp"` | 双向数据绑定 | 适用于原生表单元素及遵循 `$bind` 契约的组件(如 `<Modal>` 的显示状态绑定、`<AutoForm>` 的数据绑定)。 |
| **`$if`** | `Boolean(result)` | `true`: 挂载节点; `false`: 移除节点。建议配合 `<template>`。 |
| **`$each`** | `Iterable` | 基于 `key` 属性执行节点复用。无 `key` 时按索引重建。支持 `as`, `index` 定义局部变量。 |
### 2. attr绑定规范 (例如 `$style` vs `style`)
* **唯一正确写法**:动态样式强制使用 `$style` 指令,并利用模板字符串 `${}` 进行变量插值,而不是字符串拼接。
* ❌ 不推荐:`$style="'transform:translateY(' + this.state.offsetY + 'px)'"`
* ❌ 不推荐:`$.style.transform="'transform:translateY(' + this.state.offsetY + 'px)'"`
* ✅ 正确:`$style="transform: translateY(\${this.state.offsetY}px);"`
* **覆盖原则**`$style` 的优先级高于原生 `style` 属性。如果同一个节点同时存在 `$style``style``$style` 会**完全覆盖** `style` 的内容。因此,最佳实践是将该节点的所有静态和动态样式全部合并写在 `$style` 中。
### 数据双向绑定 (`$bind`)
AI 必须根据不同的元素类型执行以下逻辑:
- **`input[type=text/password]`, `textarea`**: 监听 `input` 事件,同步字符串。
- **`input[type=checkbox]`**:
- 绑定值为 `Array`: 若选中,`push(value)`(去重);若取消,`splice(index, 1)`
- 绑定值为非 `Array`: 同步 `checked``true/false`
- **`input[type=radio]`**: 选中项 `value === 绑定值` 时设置 `checked``true`
- **`select`**: 同步选中项的 `value`
- **`[contenteditable]`**: 监听 `input`,同步 `innerHTML`
- **`input[type=file]`**: 同步 `files` 对象。
### 3\. 控制流指令
### 属性操作映射
- **`$text`**: 映射至 `textContent`
- **`$html`**: 映射至 `innerHTML`
- **`$class`**: **严格要求使用模板字符串**。范式:`class="static-name ${condition ? 'dynamic-name' : ''}"`。严禁覆盖原有类名。
- **`.path.to.prop`**: 直接映射至 DOM 对象原生属性。例如:`.style.color="'red'"` 映射为 `el.style.color = 'red'`
- **`$src`**: 增强逻辑。若值以 `.svg` 结尾,异步 Fetch 并替换为内联 `<svg>` 节点。
- **`$$attr`**: 二级求值。`eval(eval(expr))` 逻辑,用于动态生成指令代码。
* **`$if="exp"`**: 动态挂载/卸载 DOM 节点(布尔值映射)。
* **`$each="exp"`**: 遍历 Iterable 对象Array, Object, Map, Set
* **默认变量**:单层循环时,默认可直接使用隐式变量 `item`(当前项)和 `index`(索引)。
* **嵌套约束**:当 `$each`存在嵌套时,**必须**使用 `as``index` 属性显式重命名迭代变量以防止遮蔽Shadowing。例`<div $each="list" as="row" index="rowIdx">`
* **作用域继承**:内层循环可直接访问外层作用域的变量及组件实例上下文。
---
### 4\. 文本、属性与 i18n 多语言
## 3. 生命周期与事件逻辑
* **`$text="exp"`**: 将 JS 表达式结果渲染为 `textContent`
* **原地解析 (`$text`)**: 仅声明属性不赋值,框架会提取节点原有文本,将其中的 `\${}` 表达式进行响应式计算。
* **i18n 多语言 (`{#...#}`)**:
* **自动解析**:框架在扫描 DOM 树时会自动解析文本节点TextNode及静态属性`placeholder`, `title`)中的 `{#...#}` 标签。
* **SetTranslator(fn)**: 导出一个全局 API用于设置前端翻译逻辑。若不设置框架会自动剥离 `{# #}` 符号并保留原文。
* **基础格式**`{#文本#}`
* **带参格式**`{#模板文本{变量名1}{变量名2} || 参数1 || 参数2#}`
* **示例**`{#欢迎 {name} 来到 {place} || 怼怼 || 地球#}`。翻译器将接收到 `rawText="欢迎 {name} 来到 {place}"``args={name: "怼怼", place: "地球"}`
- **`$on[event]`**: 映射为 `addEventListener`。注入 `event`, `thisNode`, `this`
- **生命周期**
- **`$onload`**: `DOMNodeInserted` 且指令解析完成后触发。
- **`$onunload`**: `DOMNodeRemoved` 前触发,必须用于清理定时器或外部监听。
- **`$onupdate`**: 属性 setter 触发且渲染微任务完成后执行。
## 二、 核心 API 导出清单
---
### 1. 状态管理 (Observer)
* **`NewState(defaults: Object, getter?: Function, setter?: Function): Proxy`**
* 创建单层响应式 Proxy。
* `getter(key)`: 自定义读取逻辑。
* `setter(key, value)`: 自定义写入逻辑。
* **`Hash: Proxy`**
* 映射 URL Hash 的响应式状态,修改属性将同步至 URL。
* **`LocalStorage: Proxy`**
* 映射 LocalStorage 的响应式状态,修改属性将持久化存储。
* **`<State>.__watch(key: string|null, callback: Function)`**
* 监听指定属性变化。若 `key``null`,则监听所有属性变化。
* **`<State>.__unwatch(key: string, callback: Function)`**
* 取消监听。
## 4. 组件上下文逻辑
### 2. 系统 API (Global)
* **`RefreshState(node: HTMLElement)`**
* 手动触发指定节点及其子树的指令扫描与绑定。
* **`SetTranslator(fn: (rawText: string, args: Object) => string)`**
* 设置全局 i18n 翻译器。
- **初始化**`Component.register(tagName, setupFn)`
- **作用域隔离**:每个组件持有独立 `state`
- **穿透访问**:通过 `this.parent` 访问父级作用域链。
- **插槽映射**`slot="name"` (声明) -> `slot-id="name"` (宿主)。
### 3. 组件系统 (Component)
* **`Component.register(name: string, setupFunc: Function, template?: HTMLElement)`**
* 注册自定义组件。
* `setupFunc(container)`: 组件逻辑初始化入口。
* `template`: 组件的 DOM 模板。
---
### 4. 工具类 (Util)
* **`Util.makeDom(html: string): HTMLElement`**: HTML 字符串转 DOM。
* **`Util.copyFunction(to: Object, from: Object, ...names: string[])`**: 批量绑定方法。
* **`Util.safeJson(str: string): any`**: 安全解析 JSON。
## 5. 国际化 (I18n) 逻辑
### 5. DOM 查询
* **`$(selector: string, context?: HTMLElement): HTMLElement`**: querySelector 封装。
* **`$$(selector: string, context?: HTMLElement): NodeList`**: querySelectorAll 封装。
- **语法结构**`{# Key{param} || paramValue #}`
- **处理链路**:正则匹配 `{# ... #}` -> 提取 Key -> 注入 `||` 后的参数值 -> 调用全局 `_translator` 函数。
---
## 三、 自定义组件开发约束 (SOP)
## 6. 运行约束 (Constraints)
### 1\. 组件模板转义规则 (Template Literal Escaping)
由于模板使用 JS 字符串声明,若模板内部需使用框架的 `\${}` 语法绑定动态属性,**必须进行反斜杠转义 (`\${...}`)**,防止被原生 JS 提前求值。
* **正确**`<div $class="\${this.state.type}">`
### 2\. `$bind` 接口契约
若自定义组件需支持 `$bind` 双向绑定,需在 `setupFunc` 中实现:
* **数据输入 (响应更新)**`container.addEventListener('bind', (e) => { const val = e.detail; ... })`
* **数据输出 (触发更新)**`container.dispatchEvent(new CustomEvent('change', { bubbles: false, detail: newValue }))`
* **插槽注入规则**:消费者调用组件时,**必须**使用 `<div slot-id="插槽名">` 的形式显式向组件内注入对应节点。如果组件只有一个插槽位时调用代码可以直接写内容不需要使用模版来定义插槽。
### 3. 容器与 DOM 就绪机制 (DOM Readiness)
* **`container` 的本质**:在 `setupFunc` 中,传入的 `container` 参数**即为调用组件的 DOM 节点**。组件模板的根节点会合并到该节点变成同一个节点但是调用组件时属性中的this指向上层组件而组件内的this指向组件实例。
* **同步就绪**:当进入 `setupFunc` 时,组件的 DOM 树(包括插槽内容)已经**完全初始化并挂载就绪**,可以在 `setupFunc` 中直接使用。
### 4. 插槽 (Slot) 的渲染时序
* 组件框架在进入 setupFunc 之前就已经完成了插槽内容(`<div slot-id="...">`)的初始化注入。因此,在 setupFunc 中直接使用插槽内容是完全安全且符合预期的。
### 5. 高级状态管理与生命周期能力
* **隐式节点变量 (`thisNode`)**:
`$each` 循环或属性指令中,可以直接使用隐式变量 `thisNode` 获取当前执行上下文绑定的 DOM 节点对象自身。
## 四、 极简主义与高性能开发哲学
1. **拒绝过度工程 (No Over-engineering)**:严禁使用复杂的树结构或大段防御性代码。
2. **DOM 访问极小化**:优先通过 `this.state` 驱动 UI避免在 JS 中手动调用 `element.style.xxx`
3. **闭包与内存的权衡**:优先将逻辑挂载到 `container``container.state` 上。
4. **组件内聚**:能用指令解决的 UI 逻辑绝不写在 JS 里。
5. **思维重塑**:彻底抛弃 Vue/React 的生命周期崇拜,回归 DOM 本质。
6. **无分号运动**:除了必须的情况,代码结尾禁止使用分号 `;`
## 五、 开发范例
### 范例 1带插槽与 UI 的组件 (以 Modal 为例)
```javascript
Component.register('Modal', container => {
container.modal = new bootstrap.Modal(container)
container.addEventListener('bind', e => e.detail ? container.modal.show() : container.modal.hide())
container.addEventListener('hide.bs.modal', () => {
document.activeElement?.blur()
container.dispatchEvent(new CustomEvent('change', { bubbles: false, detail: false }))
})
Util.copyFunction(container, container.modal, 'show', 'hide')
}, Util.makeDom(/*html*/`
<div class="modal fade" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered">
<div $class="modal-content text-bg-\${this.state?.type || 'body'}">
<div slot-id="header" class="modal-header">
<h6 class="modal-title" $text="this.state?.title"></h6>
<button type="button" class="btn-close btn-sm ms-2" data-bs-dismiss="modal"></button>
</div>
<div slot-id="body" class="modal-body"></div>
<div slot-id="footer" class="modal-footer"></div>
</div>
</div>
</div>
`))
```
### 范例 2无模板纯逻辑组件 (以 API 为例)
```javascript
Component.register('API', container => {
container.request = NewState({ url: '', method: 'GET', headers: {}, data: null, timeout: 10000 })
container.response = NewState({ loading: false, result: null })
container.do = async (opt = {}) => {
const req = { ...container.request, ...opt }
container.response.loading = true
const resp = await fetch(req.url, req)
container.response.result = await resp.json()
container.response.loading = false
container.dispatchEvent(new CustomEvent('response', { detail: container.response }))
}
container.request.__watch(null, () => container.hasAttribute('auto') && container.request.url && container.do())
})
```
1. **禁止滥用同步刷新**`RefreshState()` 仅用于要求“同步等待 DOM 更新”的场景。知晓其会导致一次额外的渲染任务。
2. **数据流向**:所有状态变更必须通过对 `NewState` 代理对象的赋值完成。
3. **Key 的必要性**:在大规模数据(>100条或复杂交互列表中必须提供唯一 `key` 以激活节点复用逻辑。

1370
dist/state.js vendored

File diff suppressed because it is too large Load Diff

2
dist/state.min.js vendored

File diff suppressed because one or more lines are too long

1
dist/state.min.mjs vendored Normal file

File diff suppressed because one or more lines are too long

715
dist/state.mjs vendored Normal file
View File

@ -0,0 +1,715 @@
var _a;
let _activeBinding = null;
let _noWriteBack = null;
const setActiveBinding = (val) => _activeBinding = val;
const setNoWriteBack = (val) => _noWriteBack = val;
const _notifiers = /* @__PURE__ */ new Set();
const onNotifyUpdate = (fn) => _notifiers.add(fn);
function NewState(defaults = {}, getter = null, setter = null) {
const _defaults = {};
const _stateMappings = /* @__PURE__ */ new Map();
const _watchers = /* @__PURE__ */ new Map();
const _watchFunc = (k, cb) => {
if (!_watchers.has(k)) _watchers.set(k, /* @__PURE__ */ new Set());
!cb ? _watchers.get(k).clear() : _watchers.get(k).add(cb);
return () => _watchers.get(k).delete(cb);
};
const _unwatchFunc = (k, cb) => {
if (_watchers.has(k)) _watchers.get(k).delete(cb);
};
const __getter = getter || ((k) => _defaults[k]);
const __setter = setter || ((k, v) => _defaults[k] = v);
Object.assign(_defaults, defaults);
return new Proxy(_defaults, {
get(target, key) {
if (key === "__watch") return _watchFunc;
if (key === "__unwatch") return _unwatchFunc;
if (key === "__isProxy") return true;
if (_activeBinding) {
if (!_stateMappings.has(key)) _stateMappings.set(key, /* @__PURE__ */ new Set());
_stateMappings.get(key).add(_activeBinding);
if (!_activeBinding.node._states) _activeBinding.node._states = /* @__PURE__ */ new Set();
_activeBinding.node._states.add(_stateMappings);
}
return __getter(key);
},
set(target, key, value) {
if (__getter(key) !== value) {
__setter(key, value);
}
if (_watchers.has(key)) {
_watchers.get(key).forEach((cb) => {
const r = cb(value);
if (r !== void 0) {
value = r;
target[key] = value;
}
});
}
if (_watchers.has(null)) {
_watchers.get(null).forEach((cb) => cb(value));
}
if (_stateMappings.has(key)) {
const bindings = _stateMappings.get(key);
for (const binding of bindings) {
if (!binding.node.isConnected) {
bindings.delete(binding);
continue;
}
if (_noWriteBack !== binding.node) {
_notifiers.forEach((fn) => fn(binding));
}
}
}
return true;
}
});
}
const $ = (a, b) => b ? a.querySelector(b) : document.querySelector(a);
const $$ = (a, b) => b ? a.querySelectorAll(b) : document.querySelectorAll(a);
const _components = /* @__PURE__ */ new Map();
const _pendingTemplates = [];
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;
}
};
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 fromContent = from.tagName === "TEMPLATE" ? from.content : from;
const toContent = to.tagName === "TEMPLATE" ? to.content : to;
Array.from(fromContent.childNodes).forEach((child) => toContent.appendChild(child));
if (from.tagName && Component.exists(from.tagName)) _makeComponent(from.tagName, to, scanObj, exists);
}
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 = Array.from(tplnode.childNodes).find((n) => n.nodeType === Node.ELEMENT_NODE);
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);
}
let _disableRunCodeError = false;
function setDisableRunCodeError(value) {
_disableRunCodeError = value;
}
const _fnCache = /* @__PURE__ */ new Map();
function _runCode(code, vars, thisObj, extendVars) {
const allVars = { ...extendVars || {}, ...vars || {} };
const argKeys = Object.keys(allVars);
const argValues = Object.values(allVars);
const cacheKey = code + argKeys.join(",");
try {
let fn = _fnCache.get(cacheKey);
if (!fn) {
fn = new Function("Hash", "LocalStorage", "State", ...argKeys, code);
_fnCache.set(cacheKey, fn);
}
return fn.apply(thisObj, [globalThis.Hash, globalThis.LocalStorage, globalThis.State, ...argValues]);
} catch (e) {
if (!_disableRunCodeError) console.error(e, extendVars, [code, extendVars, vars, thisObj]);
return null;
}
}
function _returnCode(code, vars, thisObj, extendVars) {
if (code.includes("${")) return _runCode("return `" + code + "`", vars, thisObj, extendVars);
else return _runCode("return " + code, vars, thisObj, extendVars);
}
let _translator = (text, args) => {
if (!text || typeof text !== "string") return text;
return text.replace(/\{(.+?)\}/g, (match, key) => args.hasOwnProperty(key) ? args[key] : match);
};
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 (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);
const prefix = name.startsWith("$$") ? "st-st-" : "st-";
return originalSetAttribute.call(this, prefix + name.substring(name.startsWith("$$") ? 2 : 1), value);
};
}
}
onNotifyUpdate((binding) => _updateBinding(binding));
function _clearRenderedNodes(node) {
if (node._renderedNodes) node._renderedNodes.forEach((nodes) => nodes.forEach((child) => {
child.remove();
if (child._renderedNodes) _clearRenderedNodes(child);
}));
}
function _updateBinding(binding) {
const node = binding.node;
if (!node.isConnected && node.tagName !== "TEMPLATE") return;
setActiveBinding(binding);
if (window.__perfTrace) window.__perfTrace.evalCount++;
const evalStart = window.__perfTrace ? performance.now() : 0;
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) {
}
}
if (window.__perfTrace) window.__perfTrace.evalTotal += performance.now() - evalStart;
setActiveBinding(null);
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 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) => {
child._stManaged = true;
node.parentNode.insertBefore(child, node);
child._ref = { ...node._ref };
});
node._renderedNodes = [node._children];
} else {
node._renderedNodes[0].forEach((child) => _scanTree(child, { thisObj: node._thisObj, extendVars: child._ref }));
}
} 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 = /* @__PURE__ */ new Map();
const newKeyedNodes = /* @__PURE__ */ 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 === void 0 || rawKey === null || newKeyedNodes.has(rawKey) ? `st_key_fallback_${i}_${Math.random()}` : rawKey;
let existingNodes = node._keyedNodes.get(keyVal);
if (existingNodes) {
node._keyedNodes.delete(keyVal);
existingNodes.forEach((child) => {
if (window.__statePerformanceTelemetry) window.__statePerformanceTelemetry.reuseCount++;
let scopeChanged = false;
for (let key in node._ref) {
if (key === asName || key === indexName) continue;
if (child._ref[key] !== node._ref[key]) {
child._ref[key] = node._ref[key];
scopeChanged = true;
}
}
const indexChanged = child._ref[indexName] !== k;
if (indexChanged) child._ref[indexName] = k;
if (child._ref[asName] !== item || scopeChanged) {
child._ref[asName] = item;
if (window.__statePerformanceTelemetry) window.__statePerformanceTelemetry.scanCount++;
_scanTree(child, { thisObj: node._thisObj, extendVars: child._ref });
} else if (node.parentNode.lastChild !== child) {
if (window.__statePerformanceTelemetry) window.__statePerformanceTelemetry.moveCount++;
node.parentNode.insertBefore(child, node);
}
});
} else {
existingNodes = [];
node._children.forEach((child) => {
const cloned = child.cloneNode(true);
cloned._stManaged = 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);
existingNodes.forEach((child) => node.parentNode.insertBefore(child, node));
});
node._keyedNodes.forEach((nodes) => nodes.forEach((child) => {
_clearRenderedNodes(child);
child.remove();
}));
node._keyedNodes = newKeyedNodes;
node._renderedNodes = currentRenderedNodes;
} else {
_clearRenderedNodes(node);
if (node._keyedNodes) node._keyedNodes.forEach((nodes) => nodes.forEach((child) => child.remove()));
node._keyedNodes = /* @__PURE__ */ new Map();
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") {
setTimeout(() => {
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 !== void 0) {
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 ?? "");
}
}
}
}
const _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);
};
const _parseNode = (node, scanObj) => {
let hasBindings = false;
if (node._bindings) {
node._states = /* @__PURE__ */ new Set();
node._bindings.forEach((b) => _updateBinding({ node, ...b }));
if (node._hasOnUpdate) node.dispatchEvent(new Event("update", { bubbles: false }));
hasBindings = true;
}
if (Component.exists(node.tagName) && !node._componentInitialized) {
Array.from(node.attributes).forEach((attr) => {
var _a2;
if (attr.name.startsWith("$.")) {
const realAttrName = attr.name.slice(2);
let tpl = _translate(attr.value);
if (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[_a2 = prop[i]] ?? (o[_a2] = {});
}
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 (hasBindings) return;
let attrs = [];
const triggerAttrs = ["$if", "$each", "st-if", "st-each", "$$if", "$$each", "st-st-if", "st-st-each"];
if (node.tagName === "TEMPLATE") {
triggerAttrs.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-")) && !triggerAttrs.includes(a.name) || a.name.includes("."));
}
if (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 = /* @__PURE__ */ 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;
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") {
node.addEventListener(node.tagName === "TEXTAREA" || node.isContentEditable || node.type === "text" || node.type === "password" ? "input" : "change", (e) => {
let newVal = node.isContentEditable ? e.target.innerHTML : node.type === "checkbox" ? e.target.checked : e.target.files || e.target.value || e.detail;
setNoWriteBack(node);
setDisableRunCodeError(true);
if (node.type === "checkbox" && node._checkboxMultiMode) _runCode(`!!checked ? (!${tpl}.includes(val) && ${tpl}.push(val)) : (index = ${tpl}.indexOf(val), index > -1 && ${tpl}.splice(index, 1))`, { val: node.value, checked: newVal, thisNode: node }, scanObj.thisObj || node, node._ref || {});
else _runCode(`${tpl} = val`, { val: newVal, thisNode: node }, scanObj.thisObj || node, node._ref || {});
setDisableRunCodeError(false);
setNoWriteBack(null);
});
} else if (realAttrName === "text" && !tpl) {
tpl = node.textContent;
node.textContent = "";
}
if (tpl) {
tpl = _translate(tpl);
_initBinding({ node, 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;
};
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._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;
}
let resolvedThisObj = node._thisObj;
let resolvedRef = node._ref;
if (resolvedThisObj === void 0 || resolvedRef === void 0) {
let curr = node;
while (curr && (resolvedThisObj === void 0 || resolvedRef === void 0)) {
if (resolvedThisObj === void 0 && curr._thisObj !== void 0) resolvedThisObj = curr._thisObj;
if (resolvedRef === void 0 && curr._ref !== void 0) resolvedRef = { ...curr._ref };
curr = curr.parentNode;
}
}
if (resolvedThisObj === void 0) resolvedThisObj = scanObj.thisObj;
if (resolvedRef === void 0) resolvedRef = scanObj.extendVars;
const triggerAttrs = ["$if", "$each", "st-if", "st-each", "$$if", "$$each", "st-st-if", "st-st-each"];
const eachAttrs = ["$each", "st-each", "$$each", "st-st-each"];
if (node.tagName !== "TEMPLATE" && triggerAttrs.some((t) => node.hasAttribute(t))) {
const template = document.createElement("TEMPLATE");
const attrs = Array.from(node.attributes).filter((attr) => triggerAttrs.includes(attr.name) || eachAttrs.some((t) => node.hasAttribute(t)) && ["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 = resolvedRef;
template._thisObj = resolvedThisObj;
_scanTree(template, scanObj);
return;
}
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) => triggerAttrs.includes(attr2.name));
const attr = attrs[attrs.length - 1];
template.setAttribute(attr.name, attr.value);
node.removeAttribute(attr.name);
if (eachAttrs.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);
});
}
Array.from(node.content.childNodes).forEach((child) => template.content.appendChild(child));
node.content.appendChild(template);
template._ref = resolvedRef;
template._thisObj = resolvedThisObj;
}
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 !== void 0) scanObj.thisObj = node._thisObj || null;
else {
let curr = node;
while (curr && curr._thisObj === void 0) curr = curr.parentNode;
scanObj.thisObj = curr ? curr._thisObj : null;
}
if (node._ref === void 0) {
let curr = node;
while (curr && curr._ref === void 0) curr = curr.parentNode;
node._ref = curr ? { ...curr._ref } : {};
}
if (node._refExt !== void 0) {
Object.assign(node._ref, node._refExt);
}
if (scanObj.extendVars) Object.assign(node._ref, scanObj.extendVars);
_parseNode(node, { ...scanObj });
const nodes = [...node.childNodes || []];
const nextScanObj = { thisObj: scanObj.thisObj, extendVars: { ...node._ref } };
nodes.forEach((child) => {
if (!child._stManaged) _scanTree(child, nextScanObj);
});
};
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));
};
const RefreshState = _scanTree;
const Util = {
clone: window.structuredClone || ((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]),
unurlbase64: (str) => Util.unbase64(str.replace(/[-_.]/g, (m) => ({ "-": "+", "_": "/", ".": "=" })[m]).padEnd(Math.ceil(str.length / 4) * 4, "=")),
safeJson: (str) => {
try {
return JSON.parse(str);
} catch {
return null;
}
},
updateDefaults: (obj, defaults) => {
for (const k in defaults) if (obj[k] === void 0) obj[k] = defaults[k];
},
copyFunction: (toObj, fromObj, ...funcNames) => {
funcNames.forEach((name) => toObj[name] = fromObj[name].bind(fromObj));
},
getFunctionBody: (fn) => {
const code = fn.toString();
return code.slice(code.indexOf("{") + 1, code.lastIndexOf("}")).trim();
},
makeDom: (html) => {
if (html.includes(">\n")) html = html.replace(/>\s+</g, "><").trim();
const node = document.createElement("div");
node.innerHTML = html;
return node.children[0];
},
newAvg: () => {
let total = 0, count = 0, avg = 0;
return {
add: (v) => {
total += v;
count++;
return avg = total / count;
},
get: () => avg,
clear: () => {
total = 0, count = 0, avg = 0;
}
};
},
newTimeCount: () => {
let startTime = 0, total = 0, count = 0;
return {
start: () => startTime = (/* @__PURE__ */ new Date()).getTime(),
end: () => {
const endTime = (/* @__PURE__ */ new Date()).getTime();
const left = endTime - startTime;
startTime = endTime;
total += left;
count++;
return left;
},
avg: () => total / count
};
}
};
globalThis.Util = Util;
let _hashParams = new URLSearchParams(((_a = window.location.hash) == null ? void 0 : _a.substring(1)) || "");
const Hash = NewState({}, (k) => Util.safeJson(_hashParams.get(k)), (k, v) => {
const oldStr = _hashParams.get(k);
const newStr = v === void 0 ? void 0 : JSON.stringify(v);
if (oldStr === newStr || oldStr === null && newStr === void 0) return;
v === void 0 ? _hashParams.delete(k) : _hashParams.set(k, newStr);
window.location.hash = "#" + _hashParams.toString();
});
if (typeof window !== "undefined") {
window.addEventListener("hashchange", () => {
var _a2;
const oldHashParams = _hashParams;
_hashParams = new URLSearchParams(((_a2 = window.location.hash) == null ? void 0 : _a2.substring(1)) || "");
_hashParams.forEach((v, k) => {
if (oldHashParams.get(k) !== v) Hash[k] = Util.safeJson(v);
});
oldHashParams.forEach((v, k) => {
if (_hashParams.get(k) === void 0) Hash[k] = void 0;
});
});
}
const LocalStorage = NewState({}, (k) => Util.safeJson(localStorage.getItem(k)), (k, v) => {
const oldStr = localStorage.getItem(k);
const newStr = v === void 0 ? void 0 : JSON.stringify(v);
if (oldStr === newStr || oldStr === null && newStr === void 0) return;
v === void 0 ? localStorage.removeItem(k) : localStorage.setItem(k, newStr);
});
const State = NewState({
exitBlocks: 0
// 默认值
});
globalThis.Hash = Hash;
globalThis.LocalStorage = LocalStorage;
globalThis.State = State;
const ApigoState = {
NewState,
Component,
$,
$$,
RefreshState,
SetTranslator,
Util,
Hash,
LocalStorage,
State
};
if (typeof globalThis !== "undefined") {
Object.assign(globalThis, ApigoState);
globalThis.ApigoState = ApigoState;
}
if (typeof document !== "undefined") {
const init = () => {
Component._initPending();
new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((newNode) => {
if (newNode.isConnected) _scanTree(newNode);
});
mutation.removedNodes.forEach((oldNode) => _unbindTree(oldNode));
});
}).observe(document.documentElement, { childList: true, subtree: true });
_scanTree(document.documentElement);
};
if (document.readyState !== "loading") init();
else document.addEventListener("DOMContentLoaded", init, true);
}
export {
$,
$$,
Component,
Hash,
LocalStorage,
NewState,
RefreshState,
SetTranslator,
State,
Util,
_scanTree,
_unbindTree
};

View File

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

View File

@ -8,7 +8,7 @@ export default defineConfig({
},
webServer: {
command: 'npx vite --port 8081 --host 127.0.0.1',
url: 'http://127.0.0.1:8081',
url: 'http://127.0.0.1:8081/test/index.html',
timeout: 180000,
reuseExistingServer: !process.env.CI,
},

View File

@ -29,5 +29,11 @@ export const LocalStorage = NewState({}, k => Util.safeJson(localStorage.getItem
v === undefined ? localStorage.removeItem(k) : localStorage.setItem(k, newStr)
})
// 核心全局状态机
export const State = NewState({
exitBlocks: 0 // 默认值
});
globalThis.Hash = Hash;
globalThis.LocalStorage = LocalStorage;
globalThis.State = State;

View File

@ -3,11 +3,24 @@ export { NewState } from './observer.js';
export { Component } from './component.js';
export { $, $$, RefreshState, SetTranslator, _scanTree, _unbindTree } from './dom.js';
export { Util } from './utils.js';
export { Hash, LocalStorage } from './globals.js';
export { Hash, LocalStorage, State } from './globals.js';
import { NewState } from './observer.js';
import { Component } from './component.js';
import { $, $$, RefreshState, SetTranslator } from './dom.js';
import { Util } from './utils.js';
import { Hash, LocalStorage, State } from './globals.js';
import { _scanTree, _unbindTree } from './dom.js';
import { LocalStorage } from './globals.js';
const ApigoState = {
NewState, Component, $, $$, RefreshState, SetTranslator, Util, Hash, LocalStorage, State
};
// 挂载到全局,支持 UMD 直接访问
if (typeof globalThis !== 'undefined') {
Object.assign(globalThis, ApigoState);
globalThis.ApigoState = ApigoState;
}
if (typeof document !== 'undefined') {
const init = () => {

View File

@ -1,4 +1,4 @@
{
"status": "interrupted",
"status": "passed",
"failedTests": []
}

View File

@ -6,19 +6,29 @@ export default defineConfig({
build: {
lib: {
entry: resolve(__dirname, 'src/index.js'),
name: 'State',
formats: ['es']
name: 'ApigoState', // UMD 内部名称,逻辑主要靠 globalThis 挂载
formats: ['umd', 'es']
},
rollupOptions: {
output: [
{
format: 'es',
entryFileNames: 'state.js',
minifyInternalExports: false
format: 'umd',
name: 'ApigoState',
entryFileNames: 'state.js'
},
{
format: 'umd',
name: 'ApigoState',
entryFileNames: 'state.min.js',
plugins: [terser()]
},
{
format: 'es',
entryFileNames: 'state.min.js',
entryFileNames: 'state.mjs'
},
{
format: 'es',
entryFileNames: 'state.min.mjs',
plugins: [terser()]
}
]