From 0cfc9cb85f2a19ed37af8bbffe29aa13a31485df Mon Sep 17 00:00:00 2001 From: AI Engineer Date: Thu, 14 May 2026 17:12:01 +0800 Subject: [PATCH] feat: State.js v1.0.0 release (built-in i18n, reactive Hash/LocalStorage, and AI guide) (by AI) --- .gitignore | 1 + CHANGELOG.md | 19 + README.md | 146 +++++ TEST.md | 27 + dist/state.js | 633 +++++++++++++++++++ dist/state.min.js | 1 + package-lock.json | 1138 +++++++++++++++++++++++++++++++++++ package.json | 22 + playwright.config.js | 14 + src/component.js | 71 +++ src/core.js | 24 + src/dom-utils.js | 3 + src/dom.js | 380 ++++++++++++ src/globals.js | 33 + src/index.js | 34 ++ src/observer.js | 74 +++ src/utils.js | 47 ++ test-results/.last-run.json | 4 + test/all.spec.js | 43 ++ test/component.test.js | 35 ++ test/core.test.js | 18 + test/dom.test.js | 88 +++ test/index.html | 39 ++ test/observer.test.js | 28 + vite.config.js | 28 + 25 files changed, 2950 insertions(+) create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 README.md create mode 100644 TEST.md create mode 100644 dist/state.js create mode 100644 dist/state.min.js create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 playwright.config.js create mode 100644 src/component.js create mode 100644 src/core.js create mode 100644 src/dom-utils.js create mode 100644 src/dom.js create mode 100644 src/globals.js create mode 100644 src/index.js create mode 100644 src/observer.js create mode 100644 src/utils.js create mode 100644 test-results/.last-run.json create mode 100644 test/all.spec.js create mode 100644 test/component.test.js create mode 100644 test/core.test.js create mode 100644 test/dom.test.js create mode 100644 test/index.html create mode 100644 test/observer.test.js create mode 100644 vite.config.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..e494396 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,19 @@ +# CHANGELOG + +## v1.0.0 (2026-05-14) + +### 修复 +- 修正 `src/dom.js` 中 SVG 加载的 `fetch` 缓存参数名错误 (`cache1` -> `cache`)。 +- 优化 `src/index.js` 入口逻辑,支持在 `DOMContentLoaded` 之后加载时自动初始化。 + +### 优化 +- 完善 `playwright.config.js` 自动化测试配置,支持 `webServer`。 +- `test/index.html` 引入 `importmap` 映射,实现真正的“零构建”开发体验。 + +### 测试 +- 大幅提升 `test/dom.test.js` 测试覆盖率,涵盖 `$if`, `$each`, `$bind` 等核心指令。 +- 引入性能基准测试(Benchmark),监控大规模 DOM 渲染性能。 + +### 文档 +- 新增 `README.md` 与 `TEST.md`。 +- 明确记录架构设计决策:维持“单层响应式”与“基于索引复用”列表机制,以确保极致轻量。 diff --git a/README.md b/README.md new file mode 100644 index 0000000..b1c38f1 --- /dev/null +++ b/README.md @@ -0,0 +1,146 @@ +# State.js AI 开发指南 + +State.js 是基于 Vanilla JS 的无编译数据驱动 UI 框架。依赖原生 DOM 与 Proxy,通过解析 HTML `$指令` 属性映射状态。 + +> **核心设定:** 你是一个追求极致代码压缩和执行效率的资深极客。 +> **编码原则:** +> 1. **拒绝废话变量:** 除非一个变量会被复用两次以上,否则**绝对禁止**声明临时变量。 +> 2. **极致精简:** 极度偏爱链式调用(Chaining)、短路求值、三元运算符和 One-liner。能一行写完的逻辑,绝不拆成三行。 +> 3. **无解释模式:** 假设你的对话者是顶尖黑客,不需要解释基础 API,不需要防御性废话,直接给出最硬核的最终代码即可。 + +## 一、 核心语法与指令字典 + +### 1\. 属性与数据绑定矩阵 + +| 语法 | 类型 | 解析与执行规则 | +| :--- | :--- | :--- | +| `$attr="exp"` | 动态 JS 表达式 | 映射为 HTML 属性。若包含 `\${}`,作为模板字符串计算;若不包含,作为纯 JS 表达式执行并保留返回值类型。 | +| `.prop="val"` | 静态 DOM 属性 | 将字符串字面量赋值给底层 DOM 节点的 JS 属性。 | +| `$.prop="exp"` | 动态 DOM 属性 | 将 JS 执行结果赋值给底层 DOM 节点的 JS 属性。
**对象自动初始化**:对深层路径(如 `$.state.schema`)赋值时,若路径上的中间节点不存在,框架会自动生成空对象(`{}`)以防止报错。 | +| `$bind="exp"` | 双向数据绑定 | 适用于原生表单元素及遵循 `$bind` 契约的组件(如 `` 的显示状态绑定、`` 的数据绑定)。 | + +### 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` 中。 + +### 3\. 控制流指令 + + * **`$if="exp"`**: 动态挂载/卸载 DOM 节点(布尔值映射)。 + * **`$each="exp"`**: 遍历 Iterable 对象(Array, Object, Map, Set)。 + * **默认变量**:单层循环时,默认可直接使用隐式变量 `item`(当前项)和 `index`(索引)。 + * **嵌套约束**:当 `$each`存在嵌套时,**必须**使用 `as` 和 `index` 属性显式重命名迭代变量以防止遮蔽(Shadowing)。例:`
`。 + * **作用域继承**:内层循环可直接访问外层作用域的变量及组件实例上下文。 + +### 4\. 文本、属性与 i18n 多语言 + + * **`$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: "地球"}`。 + +## 二、 核心 API 指南 + +### 1. 状态管理 (Observer) +* `NewState(defaults, getter, setter)`: 创建单层响应式 Proxy。 +* `Hash`: 映射 URL Hash 的响应式状态。 +* `LocalStorage`: 映射 LocalStorage 的响应式状态。 +* `.__watch`: 状态代理对象可通过 `.__watch('属性', callback)` 监听状态属性的变化。 + +### 2. 系统 API (Global) +* `SetTranslator(fn)`: 设置自定义翻译器函数 `fn(rawText, args)`。 +* `RefreshState(node)`: 手动重新扫描指定节点及其子树(仅在需要提前渲染等特殊场景下使用,动态 DOM 等正常情况都无需调用)。 + +### 3. 工具类 (Util) +* `Util.makeDom(html)`: 将 HTML 字符串转为 DOM 节点。 +* `Util.copyFunction(to, from, ...names)`: 批量绑定并复制方法。 +* `Util.safeJson(str)`: 安全解析 JSON。 + +## 三、 自定义组件开发约束 (SOP) + +### 1\. 组件模板转义规则 (Template Literal Escaping) + +由于模板使用 JS 字符串声明,若模板内部需使用框架的 `\${}` 语法绑定动态属性,**必须进行反斜杠转义 (`\${...}`)**,防止被原生 JS 提前求值。 + + * **正确**:`
` + +### 2\. `$bind` 接口契约 + +若自定义组件需支持 `$bind` 双向绑定,需在 `setupFunc` 中实现: + + * **数据输入 (响应更新)**:`container.addEventListener('bind', (e) => { const val = e.detail; ... })` + * **数据输出 (触发更新)**:`container.dispatchEvent(new CustomEvent('change', { bubbles: false, detail: newValue }))` + * **插槽注入规则**:消费者调用组件时,**必须**使用 `
` 的形式显式向组件内注入对应节点。如果组件只有一个插槽位时调用代码可以直接写内容不需要使用模版来定义插槽。 + +### 3. 容器与 DOM 就绪机制 (DOM Readiness) +* **`container` 的本质**:在 `setupFunc` 中,传入的 `container` 参数**即为调用组件的 DOM 节点**。组件模板的根节点会合并到该节点变成同一个节点,但是调用组件时属性中的this指向上层组件,而组件内的this指向组件实例。 +* **同步就绪**:当进入 `setupFunc` 时,组件的 DOM 树(包括插槽内容)已经**完全初始化并挂载就绪**,可以在 `setupFunc` 中直接使用。 + +### 4. 插槽 (Slot) 的渲染时序 +* 组件框架在进入 setupFunc 之前就已经完成了插槽内容(`
`)的初始化注入。因此,在 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*/` + +`)) +``` + +### 范例 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()) +}) +``` diff --git a/TEST.md b/TEST.md new file mode 100644 index 0000000..2ad9328 --- /dev/null +++ b/TEST.md @@ -0,0 +1,27 @@ +# State.js Performance Benchmark + +## 测试环境 +- Playwright (Headless Chromium) +- CPU: Host machine +- 模拟规模: 1000 个列表项 + +## 性能基准 (v1.1.1) + +| 指标 | 耗时 (ms) | 备注 | +| :--- | :--- | :--- | +| **首次渲染 (1000 items)** | 50.20 | 包含模板克隆、数据绑定及 DOM 插入 | +| **浅更新 (Shallow Update)** | 10.50 | 触发 Array 重新扫描,基于索引复用 DOM 节点 | + +## 核心架构设计决策 (Design Decisions) + +### 1. 列表复用机制 ($each) +- **机制**: 基于索引(Index-based)的 DOM 节点复用。 +- **优劣**: 避免了 Keyed Diff 的复杂度,在常规增量更新下性能极佳。在头部插入时会触发全量属性扫描,但考虑到该场景频次较低且 `_scanTree` 极快,目前不引入 Key 机制以维持极致轻量。 + +### 2. 响应式系统 (NewState) +- **机制**: 单层 Proxy 响应式。 +- **优劣**: 极致的内存开销与初始化速度。不自动支持深层嵌套属性监听,推荐用户使用不可变(Immutable)风格或自赋值(`state.obj = { ...state.obj }`)来触发 UI 更新。 + +### 3. DOM 绑定与更新 +- **机制**: 基于 MutationObserver 的自动生命周期管理。 +- **特性**: 节点插入 DOM 后自动扫描指令,移除后自动解绑依赖,无需手动维护生命周期。 diff --git a/dist/state.js b/dist/state.js new file mode 100644 index 0000000..35af890 --- /dev/null +++ b/dist/state.js @@ -0,0 +1,633 @@ +var _a; +let _activeBinding = null; +let _noWriteBack = null; +let _updateBindingFn = null; +function setActiveBinding(val) { + _activeBinding = val; +} +function setNoWriteBack(val) { + _noWriteBack = val; +} +function onNotifyUpdate(fn) { + _updateBindingFn = 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); + }; + const _unwatchFunc = (k, cb) => { + if (!_watchers.has(k)) _watchers.set(k, /* @__PURE__ */ new Set()); + _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 (_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 && _updateBindingFn) { + _updateBindingFn(binding); + } + } + } + return true; + } + }); +} +const $ = (a, b) => b ? a.querySelector(b) : document.querySelector(a); +const $$ = (a, b) => b ? a.querySelectorAll(b) : document.querySelectorAll(a); +let _disableRunCodeError = false; +function setDisableRunCodeError(value) { + _disableRunCodeError = value; +} +function _runCode(code, vars, thisObj, extendVars) { + const argKeys = [...Object.keys(extendVars || {}), ...Object.keys(vars || {})]; + const argValues = [...Object.values(extendVars || {}), ...Object.values(vars || {})]; + argKeys.push(code); + try { + const r = new Function(...argKeys).apply(thisObj, argValues); + return r; + } 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) => text; +const SetTranslator = (fn) => _translator = fn; +const _translate = (text) => { + if (!text || typeof text !== "string") return text; + return text.replace(/\{#(.+?)#\}/g, (m, content) => { + const parts = content.split("||").map((s) => s.trim()); + const rawText = parts[0]; + const args = {}; + if (parts.length > 1) { + const matches = rawText.match(/\{(.+?)\}/g); + if (matches) matches.forEach((match, i) => { + const key = match.substring(1, match.length - 1); + args[key] = parts[i + 1] || ""; + }); + } + return _translator(rawText, 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); + }; + } +} +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; + const tpl = binding.tpl; + const exp = binding.exp; + setActiveBinding(binding); + let result = exp ? tpl ? _returnCode(tpl, { thisNode: node }, node._thisObj || node, node._ref || null) : null : tpl; + 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 resultIsObject = typeof result === "object" && result != null && !Array.isArray(result); + const lk = prop[prop.length - 1]; + if (lk) { + if (resultIsObject && 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 (resultIsObject && typeof o === "object") { + 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 }; + }); + 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"; + 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]; + } + keys.forEach((k, i) => { + const item = getVal(k); + if (node._renderedNodes && i < node._renderedNodes.length) { + node._renderedNodes[i].forEach((child) => { + child._ref[indexName] = k; + child._ref[asName] = item; + _scanTree(child); + }); + } else { + const newNodes = []; + if (!node._renderedNodes) node._renderedNodes = []; + node._children.forEach((child) => { + const cloned = child.cloneNode(true); + cloned._ref = { ...node._ref }; + cloned._ref[indexName] = k; + cloned._ref[asName] = item; + cloned._thisObj = node._thisObj; + node.parentNode.insertBefore(cloned, node); + newNodes.push(cloned); + }); + node._renderedNodes.push(newNodes); + } + }); + while (node._renderedNodes && node._renderedNodes.length > keys.length) { + node._renderedNodes[node._renderedNodes.length - 1].forEach((child) => { + _clearRenderedNodes(child); + child.remove(); + }); + node._renderedNodes.pop(); + } + } else { + _clearRenderedNodes(node); + node._renderedNodes = []; + } + } else if (attr === "bind") { + if (["INPUT", "SELECT", "TEXTAREA"].includes(node.tagName)) { + if (!node.hasAttribute("autocomplete")) node.setAttribute("autocomplete", "off"); + } + if (node.type === "checkbox") { + if (node.value !== "on" && !result) { + _runCode(`${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 !== 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) => { + if (node._bindings) { + node._states = /* @__PURE__ */ new Set(); + node._bindings.forEach((bindingData) => { + const binding = { node, ...bindingData }; + _updateBinding(binding); + }); + if (node._hasOnUpdate) node.dispatchEvent(new Event("update", { bubbles: false })); + return; + } + if (Component.exists(node.tagName) && !node._componentInitialized) { + node._componentInitialized = true; + _makeComponent(node.tagName, node, scanObj); + $$(node, "[slot-id]").forEach((placeholder) => placeholder.removeAttribute("slot-id")); + if (!node._thisObj) node._thisObj = node; + } + let attrs = []; + if (node.tagName === "TEMPLATE") { + node._children = [...node.content.childNodes]; + node._renderedNodes = []; + if (node.hasAttribute("$if")) attrs.push(node.getAttributeNode("$if")); + else if (node.hasAttribute("$each")) attrs.push(node.getAttributeNode("$each")); + else if (node.hasAttribute("st-if")) attrs.push(node.getAttributeNode("st-if")); + else if (node.hasAttribute("st-each")) attrs.push(node.getAttributeNode("st-each")); + } 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(".")); + } + 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) => { + const exp = attr.name.startsWith("$") || attr.name.startsWith("st-"); + const realAttrName = exp ? attr.name.slice(attr.name.startsWith("$") ? 1 : 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")) { + if (realAttrName === "onupdate") node._hasOnUpdate = 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; + ((node2, thisObj) => { + node2.addEventListener(realAttrName.slice(2), (e) => { + _runCode(tpl, { event: e, thisNode: node2, ...e.detail || {} }, thisObj || node2, node2._ref || {}); + }); + })(node, scanObj.thisObj); + } 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) { + ((node2) => { + Promise.resolve().then(() => node2.dispatchEvent(new Event("load", { bubbles: false }))); + })(node); + } + 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) { + const translated = _translate(node.textContent); + if (translated !== node.textContent) node.textContent = translated; + return; + } + if (node.nodeType !== 1) return; + 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; + } + }); + 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; + node = template; + 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((attr2) => ["$if", "$each", "st-if", "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") { + 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 = 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._thisObj !== void 0) scanObj.thisObj = node._thisObj || null; + if (scanObj.thisObj === void 0) { + 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 (scanObj.extendVars === void 0) scanObj.extendVars = {}; + if (node._ref !== void 0) { + Object.assign(node._ref, scanObj.extendVars); + scanObj.extendVars = { ...node._ref }; + } + _parseNode(node, scanObj); + const nodes = [...node.childNodes || []]; + scanObj.extendVars = node._ref || scanObj.extendVars; + nodes.forEach((child) => _scanTree(child, { thisObj: scanObj.thisObj, extendVars: { ...node._ref } })); +}; +const _unbindTree = (node) => { + if (node.nodeType !== 1) return; + if (node._hasOnUnload) node.dispatchEvent(new Event("unload", { bubbles: false })); + if (node._states) { + node._states.forEach((stateMappings) => { + for (const [key, bindingSet] of stateMappings) { + for (const binding of bindingSet) { + if (binding.node === node) bindingSet.delete(binding); + } + } + }); + } + node.childNodes && node.childNodes.forEach((child) => _unbindTree(child)); +}; +const RefreshState = _scanTree; +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 = {}) { + Array.from(from.attributes).forEach((attr) => attr.name !== "class" && to.setAttribute(attr.name, attr.value)); + to.classList.add(...from.classList); + Array.from(from.childNodes).forEach((child) => to.appendChild(child)); + if (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 = tplnode.children[0]; + _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); +} +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+<").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); +}); +globalThis.Hash = Hash; +globalThis.LocalStorage = LocalStorage; +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 }); + const htmlNode = document.documentElement; + if (!htmlNode.hasAttribute("$data-bs-theme") && !htmlNode.hasAttribute("data-bs-theme")) { + htmlNode.setAttribute("$data-bs-theme", "LocalStorage.darkMode?'dark':'light'"); + } + _scanTree(document.documentElement); + }; + if (document.readyState !== "loading") init(); + else document.addEventListener("DOMContentLoaded", init, true); +} +export { + $, + $$, + Component, + Hash, + LocalStorage, + NewState, + RefreshState, + SetTranslator, + Util, + _scanTree, + _unbindTree +}; diff --git a/dist/state.min.js b/dist/state.min.js new file mode 100644 index 0000000..b9de3bc --- /dev/null +++ b/dist/state.min.js @@ -0,0 +1 @@ +var e;let t=null,n=null,r=null;function s(e){t=e}function a(e){n=e}function o(e={},s=null,a=null){const o={},i=new Map,d=new Map,c=(e,t)=>{d.has(e)||d.set(e,new Set),t?d.get(e).add(t):d.get(e).clear()},l=(e,t)=>{d.has(e)||d.set(e,new Set),d.get(e).delete(t)},h=s||(e=>o[e]),u=a||((e,t)=>o[e]=t);return Object.assign(o,e),new Proxy(o,{get:(e,n)=>"__watch"===n?c:"__unwatch"===n?l:(t&&(i.has(n)||i.set(n,new Set),i.get(n).add(t),t.node._states||(t.node._states=new Set),t.node._states.add(i)),h(n)),set(e,t,s){if(h(t)!==s&&u(t,s),d.has(t)&&d.get(t).forEach(n=>{const r=n(s);void 0!==r&&(s=r,e[t]=s)}),d.has(null)&&d.get(null).forEach(e=>e(s)),i.has(t)){const e=i.get(t);for(const t of e)t.node.isConnected?n!==t.node&&r&&r(t):e.delete(t)}return!0}})}const i=(e,t)=>t?e.querySelector(t):document.querySelector(e),d=(e,t)=>t?e.querySelectorAll(t):document.querySelectorAll(e);let c=!1;function l(e){c=e}function h(e,t,n,r){const s=[...Object.keys(r||{}),...Object.keys(t||{})],a=[...Object.values(r||{}),...Object.values(t||{})];s.push(e);try{return new Function(...s).apply(n,a)}catch(s){return c||console.error(s,r,[e,r,t,n]),null}}let u=e=>e;const f=e=>u=e,b=e=>e&&"string"==typeof e?e.replace(/\{#(.+?)#\}/g,(e,t)=>{const n=t.split("||").map(e=>e.trim()),r=n[0],s={};if(n.length>1){const e=r.match(/\{(.+?)\}/g);e&&e.forEach((e,t)=>{const r=e.substring(1,e.length-1);s[r]=n[t+1]||""})}return u(r,s)}):e;if("undefined"!=typeof document)try{document.createElement("div").setAttribute("$t","1")}catch(e){const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(e,n){return e.startsWith("$")?t.call(this,"st-"+e.substring(1),n):t.call(this,e,n)}}function m(e){e._renderedNodes&&e._renderedNodes.forEach(e=>{e.forEach(e=>{e.remove(),e._renderedNodes&&m(e)})})}function p(e){const t=e.node,n=e.tpl,r=e.exp;s(e);let a=r?n?(o=n,i={thisNode:t},d=t._thisObj||t,c=t._ref||null,o.includes("${")?h("return `"+o+"`",i,d,c):h("return "+o,i,d,c)):null:n;var o,i,d,c;if(s(null),e.prop){const n=e.prop;let r=t;for(let e=0;e{t.parentNode.insertBefore(e,t),e._ref={...t._ref}}),t._renderedNodes=[t._children]):(m(t),t._renderedNodes=[]);else if("each"===r)if(a&&"object"==typeof a){const e=t.getAttribute("as")||"item",n=t.getAttribute("index")||"index";let r,s;if(a instanceof Map)r=Array.from(a.keys()),s=e=>a.get(e);else if("function"==typeof a[Symbol.iterator]){const e=Array.isArray(a)?a:Array.from(a);r=new Array(e.length);for(let t=0;te[t]}else r=Object.keys(a),s=e=>a[e];for(r.forEach((r,a)=>{const o=s(r);if(t._renderedNodes&&a{t._ref[n]=r,t._ref[e]=o,_(t)});else{const s=[];t._renderedNodes||(t._renderedNodes=[]),t._children.forEach(a=>{const i=a.cloneNode(!0);i._ref={...t._ref},i._ref[n]=r,i._ref[e]=o,i._thisObj=t._thisObj,t.parentNode.insertBefore(i,t),s.push(i)}),t._renderedNodes.push(s)}});t._renderedNodes&&t._renderedNodes.length>r.length;)t._renderedNodes[t._renderedNodes.length-1].forEach(e=>{m(e),e.remove()}),t._renderedNodes.pop()}else m(t),t._renderedNodes=[];else if("bind"===r){if(["INPUT","SELECT","TEXTAREA"].includes(t.tagName)&&(t.hasAttribute("autocomplete")||t.setAttribute("autocomplete","off")),"checkbox"===t.type){"on"===t.value||a||(h(`${n} = []`,{thisNode:t},t._thisObj||t,t._ref||{}),a=[]),t._checkboxMultiMode=a instanceof Array;const e=a instanceof Array?a.includes(t.value):!!a;t.checked!==e&&(t.checked=e)}else"radio"===t.type?t.checked!==(t.value===String(a??""))&&(t.checked=t.value===String(a??"")):"value"in t&&"file"!==t.type?Promise.resolve().then(()=>{t.value!==String(a??"")&&(t.value=a)}):t.isContentEditable&&t.innerHTML!==String(a??"")&&(t.innerHTML=a);t.dispatchEvent(new CustomEvent("bind",{bubbles:!1,detail:a}))}else["checked","disabled","readonly"].includes(r)&&(a=!!a),"boolean"==typeof a?a?t.setAttribute(r,""):t.removeAttribute(r):void 0!==a&&("string"!=typeof a&&(a=JSON.stringify(a)),"text"===r?t.textContent=a??"":"html"===r?t.innerHTML=a??"":"IMG"===t.tagName&&"src"===r&&a.includes(".svg")?t.setAttribute("_src",a??""):t.setAttribute(r,a??""))}}r=e=>p(e);const g=e=>{e.node._bindings||(e.node._bindings=[]),e.node._bindings.push({attr:e.attr,prop:e.prop,tpl:e.tpl,exp:e.exp}),p(e)},_=(e,t={})=>{if(3===e.nodeType){const t=b(e.textContent);return void(t!==e.textContent&&(e.textContent=t))}if(1!==e.nodeType)return;if(Array.from(e.attributes).forEach(e=>{if(!e.name.startsWith("$")&&!e.name.startsWith("st-")&&!e.name.startsWith(".")){const t=b(e.value);t!==e.value&&(e.value=t)}}),"TEMPLATE"!==e.tagName&&(e.hasAttribute("$if")||e.hasAttribute("$each")||e.hasAttribute("st-if")||e.hasAttribute("st-each"))){const t=document.createElement("TEMPLATE");return Array.from(e.attributes).filter(t=>["$if","$each","st-if","st-each"].includes(t.name)||(e.hasAttribute("$each")||e.hasAttribute("st-each"))&&["as","index"].includes(t.name)).forEach(n=>{t.setAttribute(n.name,n.value),e.removeAttribute(n.name)}),e.parentNode.insertBefore(t,e),t.content.appendChild(e),t._ref=e._ref,void(e=t)}if("TEMPLATE"===e.tagName&&(e.hasAttribute("$if")||e.hasAttribute("st-if"))&&(e.hasAttribute("$each")||e.hasAttribute("st-each"))){const t=document.createElement("TEMPLATE"),n=Array.from(e.attributes).filter(e=>["$if","$each","st-if","st-each"].includes(e.name)),r=n[n.length-1];t.setAttribute(r.name,r.value),e.removeAttribute(r.name),"$each"!==r.name&&"st-each"!==r.name||Array.from(e.attributes).filter(e=>["as","index"].includes(e.name)).forEach(n=>{t.setAttribute(n.name,n.value),e.removeAttribute(n.name)}),Array.from(e.content.childNodes).forEach(e=>{t.content.appendChild(e)}),e.content.appendChild(t),t._ref=e._ref}if("IMG"===e.tagName&&(e.hasAttribute("src")||e.hasAttribute("_src")||e.hasAttribute("$src"))){const t=e;Promise.resolve().then(()=>{const e=t.getAttribute("_src")||t.getAttribute("src");e&&fetch(e,{cache:"force-cache"}).then(e=>e.text()).then(e=>{const n=(new DOMParser).parseFromString(e,"image/svg+xml").querySelector("svg");n&&(Array.from(t.attributes).forEach(e=>n.setAttribute(e.name,e.value)),t.replaceWith(n))})})}if(void 0!==e._thisObj&&(t.thisObj=e._thisObj||null),void 0===t.thisObj){let n=e;for(;n&&void 0===n._thisObj;)n=n.parentNode;t.thisObj=n?n._thisObj:null}if(void 0===e._ref){let t=e;for(;t&&void 0===t._ref;)t=t.parentNode;e._ref=t?{...t._ref}:{}}void 0===t.extendVars&&(t.extendVars={}),void 0!==e._ref&&(Object.assign(e._ref,t.extendVars),t.extendVars={...e._ref}),((e,t)=>{if(e._bindings)return e._states=new Set,e._bindings.forEach(t=>{p({node:e,...t})}),void(e._hasOnUpdate&&e.dispatchEvent(new Event("update",{bubbles:!1})));N.exists(e.tagName)&&!e._componentInitialized&&(e._componentInitialized=!0,x(e.tagName,e,t),d(e,"[slot-id]").forEach(e=>e.removeAttribute("slot-id")),e._thisObj||(e._thisObj=e));let n=[];var r;"TEMPLATE"===e.tagName?(e._children=[...e.content.childNodes],e._renderedNodes=[],e.hasAttribute("$if")?n.push(e.getAttributeNode("$if")):e.hasAttribute("$each")?n.push(e.getAttributeNode("$each")):e.hasAttribute("st-if")?n.push(e.getAttributeNode("st-if")):e.hasAttribute("st-each")&&n.push(e.getAttributeNode("st-each"))):n=Array.from(e.attributes).filter(e=>(e.name.startsWith("$")||e.name.startsWith("st-"))&&!["$if","$each","st-if","st-each"].includes(e.name)||e.name.includes(".")),e._thisObj&&t.thisObj&&(e._thisObj.parent=t.thisObj),e._thisObj||(e._thisObj=t.thisObj||null),e._ref||(e._ref=t.extendVars||{}),e._states=new Set,n.forEach(n=>{const r=n.name.startsWith("$")||n.name.startsWith("st-"),s=r?n.name.slice(n.name.startsWith("$")?1:3):n.name;let o=n.value;var i,d;e.removeAttribute(n.name),s.startsWith(".")?g({node:e,prop:s.split("."),tpl:o,exp:r}):s.startsWith("on")?("onupdate"===s&&(e._hasOnUpdate=!0),"onload"!==s||["BODY","IMG","IFRAME"].includes(e.tagName)||(e._hasOnLoad=!0),"onunload"!==s||["BODY","IMG","IFRAME"].includes(e.tagName)||(e._hasOnUnload=!0),i=e,d=t.thisObj,i.addEventListener(s.slice(2),e=>{h(o,{event:e,thisNode:i,...e.detail||{}},d||i,i._ref||{})})):("bind"===s?e.addEventListener("TEXTAREA"===e.tagName||e.isContentEditable||"text"===e.type||"password"===e.type?"input":"change",n=>{let r=e.isContentEditable?n.target.innerHTML:"checkbox"===e.type?n.target.checked:n.target.files||n.target.value||n.detail;a(e),l(!0),"checkbox"===e.type&&e._checkboxMultiMode?h(`!!checked ? (!${o}.includes(val) && ${o}.push(val)) : (index = ${o}.indexOf(val), index > -1 && ${o}.splice(index, 1))`,{val:e.value,checked:r,thisNode:e},t.thisObj||e,e._ref||{}):h(`${o} = val`,{val:r,thisNode:e},t.thisObj||e,e._ref||{}),l(!1),a(null)}):"text"!==s||o||(o=e.textContent,e.textContent=""),o&&(o=b(o),g({node:e,attr:s,tpl:o,exp:r})))}),(e._hasOnLoad||e._componentInitialized)&&(r=e,Promise.resolve().then(()=>r.dispatchEvent(new Event("load",{bubbles:!1})))),e._hasOnUpdate&&e.dispatchEvent(new Event("update",{bubbles:!1})),e._thisObj&&(t.thisObj=e._thisObj)})(e,t);const n=[...e.childNodes||[]];t.extendVars=e._ref||t.extendVars,n.forEach(n=>_(n,{thisObj:t.thisObj,extendVars:{...e._ref}}))},v=e=>{1===e.nodeType&&(e._hasOnUnload&&e.dispatchEvent(new Event("unload",{bubbles:!1})),e._states&&e._states.forEach(t=>{for(const[n,r]of t)for(const t of r)t.node===e&&r.delete(t)}),e.childNodes&&e.childNodes.forEach(e=>v(e)))},A=_,E=new Map,y=[],N={getTemplate:e=>document.querySelector(`template[component="${e.toUpperCase()}"]`),register:(e,t,n=null,...r)=>{E.set(e.toUpperCase(),t),"loading"!==document.readyState?N._addTemplate(e,n,r):y.push([e,n,r])},exists:e=>E.has(e.toUpperCase()),getSetupFunction:e=>E.get(e.toUpperCase()),_addTemplate:(e,t,n)=>{if(t){const n=document.createElement("TEMPLATE");n.setAttribute("component",e.toUpperCase()),n.content.appendChild(t),document.body.appendChild(n)}n&&n.forEach(e=>document.body.appendChild(e))},_initPending:()=>{y.forEach(([e,t,n])=>N._addTemplate(e,t,n)),y.length=0}};function O(e,t,n,r={}){Array.from(e.attributes).forEach(e=>"class"!==e.name&&t.setAttribute(e.name,e.value)),t.classList.add(...e.classList),Array.from(e.childNodes).forEach(e=>t.appendChild(e)),N.exists(e.tagName)&&x(e.tagName,t,n,r)}function x(e,t,n,r={}){if(r[e])return;r[e]=!0,n.thisObj&&Array.from(t.attributes).forEach(e=>{(e.name.startsWith("$")||e.name.startsWith("st-"))&&e.value.includes("this.")&&(e.value=e.value.replace(/\bthis\./g,"this.parent."))});const s=N.getSetupFunction(e),a={};Array.from(t.childNodes).forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&e.hasAttribute("slot")&&(a[e.getAttribute("slot")]=e,e.removeAttribute("slot"))}),t.innerHTML="",t.state=o(t.state||{});const i=N.getTemplate(e);if(i){const e=i.content.cloneNode(!0);if(e.childNodes.length){O(e.children[0],t,n,r),d(t,"[slot-id]").forEach(e=>{const t=e.getAttribute("slot-id");a[t]&&(e.removeAttribute("slot-id"),e.innerHTML="",O(a[t],e,n,r))})}}s&&s(t)}const j={clone:window.structuredClone||(e=>JSON.parse(JSON.stringify(e))),base64:e=>btoa(String.fromCharCode(...(new TextEncoder).encode(e))),unbase64:e=>(new TextDecoder).decode(Uint8Array.from(atob(e),e=>e.charCodeAt(0))),urlbase64:e=>j.base64(e).replace(/[+/=]/g,e=>({"+":"-","/":"","=":""}[e])),unurlbase64:e=>j.unbase64(e.replace(/[-_.]/g,e=>({"-":"+",_:"/",".":"="}[e])).padEnd(4*Math.ceil(e.length/4),"=")),safeJson:e=>{try{return JSON.parse(e)}catch{return null}},updateDefaults:(e,t)=>{for(const n in t)void 0===e[n]&&(e[n]=t[n])},copyFunction:(e,t,...n)=>{n.forEach(n=>e[n]=t[n].bind(t))},getFunctionBody:e=>{const t=e.toString();return t.slice(t.indexOf("{")+1,t.lastIndexOf("}")).trim()},makeDom:e=>{e.includes(">\n")&&(e=e.replace(/>\s+<").trim());const t=document.createElement("div");return t.innerHTML=e,t.children[0]},newAvg:()=>{let e=0,t=0,n=0;return{add:r=>(e+=r,t++,n=e/t),get:()=>n,clear:()=>{e=0,t=0,n=0}}},newTimeCount:()=>{let e=0,t=0,n=0;return{start:()=>e=(new Date).getTime(),end:()=>{const r=(new Date).getTime(),s=r-e;return e=r,t+=s,n++,s},avg:()=>t/n}}};globalThis.Util=j;let w=new URLSearchParams((null==(e=window.location.hash)?void 0:e.substring(1))||"");const T=o({},e=>j.safeJson(w.get(e)),(e,t)=>{const n=w.get(e),r=void 0===t?void 0:JSON.stringify(t);n===r||null===n&&void 0===r||(void 0===t?w.delete(e):w.set(e,r),window.location.hash="#"+w.toString())});"undefined"!=typeof window&&window.addEventListener("hashchange",()=>{var e;const t=w;w=new URLSearchParams((null==(e=window.location.hash)?void 0:e.substring(1))||""),w.forEach((e,n)=>{t.get(n)!==e&&(T[n]=j.safeJson(e))}),t.forEach((e,t)=>{void 0===w.get(t)&&(T[t]=void 0)})});const S=o({},e=>j.safeJson(localStorage.getItem(e)),(e,t)=>{const n=localStorage.getItem(e),r=void 0===t?void 0:JSON.stringify(t);n===r||null===n&&void 0===r||(void 0===t?localStorage.removeItem(e):localStorage.setItem(e,r))});if(globalThis.Hash=T,globalThis.LocalStorage=S,"undefined"!=typeof document){const e=()=>{N._initPending(),new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e.isConnected&&_(e)}),e.removedNodes.forEach(e=>v(e))})}).observe(document.documentElement,{childList:!0,subtree:!0});const e=document.documentElement;e.hasAttribute("$data-bs-theme")||e.hasAttribute("data-bs-theme")||e.setAttribute("$data-bs-theme","LocalStorage.darkMode?'dark':'light'"),_(document.documentElement)};"loading"!==document.readyState?e():document.addEventListener("DOMContentLoaded",e,!0)}export{i as $,d as $$,N as Component,T as Hash,S as LocalStorage,o as NewState,A as RefreshState,f as SetTranslator,j as Util,_ as _scanTree,v as _unbindTree}; diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..de57f6c --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1138 @@ +{ + "name": "@web/state", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@web/state", + "version": "1.0.0", + "devDependencies": { + "@playwright/test": "^1.40.0", + "@rollup/plugin-terser": "^1.0.0", + "terser": "^5.47.1", + "vite": "^5.0.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", + "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz", + "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", + "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz", + "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz", + "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", + "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", + "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", + "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", + "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", + "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", + "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", + "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", + "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", + "cpu": [ + "mips64el" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", + "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", + "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", + "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", + "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", + "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", + "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", + "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", + "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", + "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", + "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/source-map": { + "version": "0.3.11", + "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.11.tgz", + "integrity": "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==", + "dev": true, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@playwright/test": { + "version": "1.60.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.60.0.tgz", + "integrity": "sha512-O71yZIbAh/PxDMNGns37GHBIfrVkEVyn+AXyIa5dOTfb4/xNvRWV+Vv/NMbNCtODB/pO7vLlF2OTmMVLhmr7Ag==", + "dev": true, + "dependencies": { + "playwright": "1.60.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@rollup/plugin-terser": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-terser/-/plugin-terser-1.0.0.tgz", + "integrity": "sha512-FnCxhTBx6bMOYQrar6C8h3scPt8/JwIzw3+AJ2K++6guogH5fYaIFia+zZuhqv0eo1RN7W1Pz630SyvLbDjhtQ==", + "dev": true, + "dependencies": { + "serialize-javascript": "^7.0.3", + "smob": "^1.0.0", + "terser": "^5.17.4" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "rollup": "^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.3.tgz", + "integrity": "sha512-x35CNW/ANXG3hE/EZpRU8MXX1JDN86hBb2wMGAtltkz7pc6cxgjpy1OMMfDosOQ+2hWqIkag/fGok1Yady9nGw==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.60.3.tgz", + "integrity": "sha512-xw3xtkDApIOGayehp2+Rz4zimfkaX65r4t47iy+ymQB2G4iJCBBfj0ogVg5jpvjpn8UWn/+q9tprxleYeNp3Hw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.60.3.tgz", + "integrity": "sha512-vo6Y5Qfpx7/5EaamIwi0WqW2+zfiusVihKatLvtN1VFVy3D13uERk/6gZLU1UiHRL6fDXqj/ELIeVRGnvcTE1g==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.60.3.tgz", + "integrity": "sha512-D+0QGcZhBzTN82weOnsSlY7V7+RMmPuF1CkbxyMAGE8+ZHeUjyb76ZiWmBlCu//AQQONvxcqRbwZTajZKqjuOw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.60.3.tgz", + "integrity": "sha512-6HnvHCT7fDyj6R0Ph7A6x8dQS/S38MClRWeDLqc0MdfWkxjiu1HSDYrdPhqSILzjTIC/pnXbbJbo+ft+gy/9hQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.60.3.tgz", + "integrity": "sha512-KHLgC3WKlUYW3ShFKnnosZDOJ0xjg9zp7au3sIm2bs/tGBeC2ipmvRh/N7JKi0t9Ue20C0dpEshi8WUubg+cnA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.60.3.tgz", + "integrity": "sha512-DV6fJoxEYWJOvaZIsok7KrYl0tPvga5OZ2yvKHNNYyk/2roMLqQAbGhr78EQ5YhHpnhLKJD3S1WFusAkmUuV5g==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.60.3.tgz", + "integrity": "sha512-mQKoJAzvuOs6F+TZybQO4GOTSMUu7v0WdxEk24krQ/uUxXoPTtHjuaUuPmFhtBcM4K0ons8nrE3JyhTuCFtT/w==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.60.3.tgz", + "integrity": "sha512-Whjj2qoiJ6+OOJMGptTYazaJvjOJm+iKHpXQM1P3LzGjt7Ff++Tp7nH4N8J/BUA7R9IHfDyx4DJIflifwnbmIA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.60.3.tgz", + "integrity": "sha512-4YTNHKqGng5+yiZt3mg77nmyuCfmNfX4fPmyUapBcIk+BdwSwmCWGXOUxhXbBEkFHtoN5boLj/5NON+u5QC9tg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.60.3.tgz", + "integrity": "sha512-SU3kNlhkpI4UqlUc2VXPGK9o886ZsSeGfMAX2ba2b8DKmMXq4AL7KUrkSWVbb7koVqx41Yczx6dx5PNargIrEA==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.60.3.tgz", + "integrity": "sha512-6lDLl5h4TXpB1mTf2rQWnAk/LcXrx9vBfu/DT5TIPhvMhRWaZ5MxkIc8u4lJAmBo6klTe1ywXIUHFjylW505sg==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.60.3.tgz", + "integrity": "sha512-BMo8bOw8evlup/8G+cj5xWtPyp93xPdyoSN16Zy90Q2QZ0ZYRhCt6ZJSwbrRzG9HApFabjwj2p25TUPDWrhzqQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.60.3.tgz", + "integrity": "sha512-E0L8X1dZN1/Rph+5VPF6Xj2G7JJvMACVXtamTJIDrVI44Y3K+G8gQaMEAavbqCGTa16InptiVrX6eM6pmJ+7qA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.60.3.tgz", + "integrity": "sha512-oZJ/WHaVfHUiRAtmTAeo3DcevNsVvH8mbvodjZy7D5QKvCefO371SiKRpxoDcCxB3PTRTLayWBkvmDQKTcX/sw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.60.3.tgz", + "integrity": "sha512-Dhbyh7j9FybM3YaTgaHmVALwA8AkUwTPccyCQ79TG9AJUsMQqgN1DDEZNr4+QUfwiWvLDumW5vdwzoeUF+TNxQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.60.3.tgz", + "integrity": "sha512-cJd1X5XhHHlltkaypz1UcWLA8AcoIi1aWhsvaWDskD1oz2eKCypnqvTQ8ykMNI0RSmm7NkTdSqSSD7zM0xa6Ig==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.60.3.tgz", + "integrity": "sha512-DAZDBHQfG2oQuhY7mc6I3/qB4LU2fQCjRvxbDwd/Jdvb9fypP4IJ4qmtu6lNjes6B531AI8cg1aKC2di97bUxA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.60.3.tgz", + "integrity": "sha512-cRxsE8c13mZOh3vP+wLDxpQBRrOHDIGOWyDL93Sy0Ga8y515fBcC2pjUfFwUe5T7tqvTvWbCpg1URM/AXdWIXA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.60.3.tgz", + "integrity": "sha512-QaWcIgRxqEdQdhJqW4DJctsH6HCmo5vHxY0krHSX4jMtOqfzC+dqDGuHM87bu4H8JBeibWx7jFz+h6/4C8wA5Q==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.60.3.tgz", + "integrity": "sha512-AaXwSvUi3QIPtroAUw1t5yHGIyqKEXwH54WUocFolZhpGDruJcs8c+xPNDRn4XiQsS7MEwnYsHW2l0MBLDMkWg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.60.3.tgz", + "integrity": "sha512-65LAKM/bAWDqKNEelHlcHvm2V+Vfb8C6INFxQXRHCvaVN1rJfwr4NvdP4FyzUaLqWfaCGaadf6UbTm8xJeYfEg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.60.3.tgz", + "integrity": "sha512-EEM2gyhBF5MFnI6vMKdX1LAosE627RGBzIoGMdLloPZkXrUN0Ckqgr2Qi8+J3zip/8NVVro3/FjB+tjhZUgUHA==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.60.3.tgz", + "integrity": "sha512-E5Eb5H/DpxaoXH++Qkv28RcUJboMopmdDUALBczvHMf7hNIxaDZqwY5lK12UK1BHacSmvupoEWGu+n993Z0y1A==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.60.3.tgz", + "integrity": "sha512-hPt/bgL5cE+Qp+/TPHBqptcAgPzgj46mPcg/16zNUmbQk0j+mOEQV/+Lqu8QRtDV3Ek95Q6FeFITpuhl6OTsAA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true + }, + "node_modules/acorn": { + "version": "8.16.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", + "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true + }, + "node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true + }, + "node_modules/esbuild": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", + "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.21.5", + "@esbuild/android-arm": "0.21.5", + "@esbuild/android-arm64": "0.21.5", + "@esbuild/android-x64": "0.21.5", + "@esbuild/darwin-arm64": "0.21.5", + "@esbuild/darwin-x64": "0.21.5", + "@esbuild/freebsd-arm64": "0.21.5", + "@esbuild/freebsd-x64": "0.21.5", + "@esbuild/linux-arm": "0.21.5", + "@esbuild/linux-arm64": "0.21.5", + "@esbuild/linux-ia32": "0.21.5", + "@esbuild/linux-loong64": "0.21.5", + "@esbuild/linux-mips64el": "0.21.5", + "@esbuild/linux-ppc64": "0.21.5", + "@esbuild/linux-riscv64": "0.21.5", + "@esbuild/linux-s390x": "0.21.5", + "@esbuild/linux-x64": "0.21.5", + "@esbuild/netbsd-x64": "0.21.5", + "@esbuild/openbsd-x64": "0.21.5", + "@esbuild/sunos-x64": "0.21.5", + "@esbuild/win32-arm64": "0.21.5", + "@esbuild/win32-ia32": "0.21.5", + "@esbuild/win32-x64": "0.21.5" + } + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.12", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz", + "integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true + }, + "node_modules/playwright": { + "version": "1.60.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.60.0.tgz", + "integrity": "sha512-hheHdokM8cdqCb0lcE3s+zT4t4W+vvjpGxsZlDnikarzx8tSzMebh3UiFtgqwFwnTnjYQcsyMF8ei2mCO/tpeA==", + "dev": true, + "dependencies": { + "playwright-core": "1.60.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.60.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.60.0.tgz", + "integrity": "sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==", + "dev": true, + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/postcss": { + "version": "8.5.14", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.14.tgz", + "integrity": "sha512-SoSL4+OSEtR99LHFZQiJLkT59C5B1amGO1NzTwj7TT1qCUgUO6hxOvzkOYxD+vMrXBM3XJIKzokoERdqQq/Zmg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.0.0", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rollup": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.3.tgz", + "integrity": "sha512-pAQK9HalE84QSm4Po3EmWIZPd3FnjkShVkiMlz1iligWYkWQ7wHYd1PF/T7QZ5TVSD6uSTon5gBVMSM4JfBV+A==", + "dev": true, + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.60.3", + "@rollup/rollup-android-arm64": "4.60.3", + "@rollup/rollup-darwin-arm64": "4.60.3", + "@rollup/rollup-darwin-x64": "4.60.3", + "@rollup/rollup-freebsd-arm64": "4.60.3", + "@rollup/rollup-freebsd-x64": "4.60.3", + "@rollup/rollup-linux-arm-gnueabihf": "4.60.3", + "@rollup/rollup-linux-arm-musleabihf": "4.60.3", + "@rollup/rollup-linux-arm64-gnu": "4.60.3", + "@rollup/rollup-linux-arm64-musl": "4.60.3", + "@rollup/rollup-linux-loong64-gnu": "4.60.3", + "@rollup/rollup-linux-loong64-musl": "4.60.3", + "@rollup/rollup-linux-ppc64-gnu": "4.60.3", + "@rollup/rollup-linux-ppc64-musl": "4.60.3", + "@rollup/rollup-linux-riscv64-gnu": "4.60.3", + "@rollup/rollup-linux-riscv64-musl": "4.60.3", + "@rollup/rollup-linux-s390x-gnu": "4.60.3", + "@rollup/rollup-linux-x64-gnu": "4.60.3", + "@rollup/rollup-linux-x64-musl": "4.60.3", + "@rollup/rollup-openbsd-x64": "4.60.3", + "@rollup/rollup-openharmony-arm64": "4.60.3", + "@rollup/rollup-win32-arm64-msvc": "4.60.3", + "@rollup/rollup-win32-ia32-msvc": "4.60.3", + "@rollup/rollup-win32-x64-gnu": "4.60.3", + "@rollup/rollup-win32-x64-msvc": "4.60.3", + "fsevents": "~2.3.2" + } + }, + "node_modules/serialize-javascript": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.0.5.tgz", + "integrity": "sha512-F4LcB0UqUl1zErq+1nYEEzSHJnIwb3AF2XWB94b+afhrekOUijwooAYqFyRbjYkm2PAKBabx6oYv/xDxNi8IBw==", + "dev": true, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/smob": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/smob/-/smob-1.6.1.tgz", + "integrity": "sha512-KAkBqZl3c2GvNgNhcoyJae1aKldDW0LO279wF9bk1PnluRTETKBq0WyzRXxEhoQLk56yHaOY4JCBEKDuJIET5g==", + "dev": true, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/terser": { + "version": "5.47.1", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.47.1.tgz", + "integrity": "sha512-tPbLXTI6ohPASb/1YViL428oEHu6/qv1OxqYnfaonVCFHqx4+wCd95pHrQWsL5X4pl90CTyW9piSAsS2L0VoMw==", + "dev": true, + "dependencies": { + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.15.0", + "commander": "^2.20.0", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/vite": { + "version": "5.4.21", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz", + "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==", + "dev": true, + "dependencies": { + "esbuild": "^0.21.3", + "postcss": "^8.4.43", + "rollup": "^4.20.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/vite/node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + } + } +} \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..1cf8f99 --- /dev/null +++ b/package.json @@ -0,0 +1,22 @@ +{ + "name": "@web/state", + "version": "1.0.0", + + "type": "module", + "main": "dist/state.js", + "module": "dist/state.js", + "files": [ + "dist" + ], + "scripts": { + "dev": "vite", + "build": "vite build", + "test": "playwright test" + }, + "devDependencies": { + "@playwright/test": "^1.40.0", + "@rollup/plugin-terser": "^1.0.0", + "terser": "^5.47.1", + "vite": "^5.0.0" + } +} \ No newline at end of file diff --git a/playwright.config.js b/playwright.config.js new file mode 100644 index 0000000..30360af --- /dev/null +++ b/playwright.config.js @@ -0,0 +1,14 @@ +import { defineConfig } from '@playwright/test'; + +export default defineConfig({ + testDir: './test', + testMatch: '**/*.spec.js', + use: { + baseURL: 'http://localhost:8081', + }, + webServer: { + command: 'npx vite --port 8081', + url: 'http://localhost:8081', + reuseExistingServer: !process.env.CI, + }, +}); diff --git a/src/component.js b/src/component.js new file mode 100644 index 0000000..6171add --- /dev/null +++ b/src/component.js @@ -0,0 +1,71 @@ +// src/component.js +import { NewState } from './observer.js'; +import { $, $$ } from './dom-utils.js'; +import { _scanTree } from './dom.js'; + +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; + } +}; + +export function _mergeNode(from, to, scanObj, exists = {}) { + Array.from(from.attributes).forEach(attr => attr.name !== 'class' && to.setAttribute(attr.name, attr.value)); + to.classList.add(...from.classList); + Array.from(from.childNodes).forEach(child => to.appendChild(child)); + if (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]; + _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); +} diff --git a/src/core.js b/src/core.js new file mode 100644 index 0000000..4d49663 --- /dev/null +++ b/src/core.js @@ -0,0 +1,24 @@ +// src/core.js +let _disableRunCodeError = false; + +export function setDisableRunCodeError(value) { + _disableRunCodeError = value; +} + +export function _runCode(code, vars, thisObj, extendVars) { + const argKeys = [...Object.keys(extendVars || {}), ...Object.keys(vars || {})]; + const argValues = [...Object.values(extendVars || {}), ...Object.values(vars || {})]; + argKeys.push(code); + try { + const r = new Function(...argKeys).apply(thisObj, argValues); + return r; + } catch (e) { + if (!_disableRunCodeError) console.error(e, extendVars, [code, extendVars, vars, thisObj]); + return null; + } +} + +export function _returnCode(code, vars, thisObj, extendVars) { + if (code.includes('${')) return _runCode('return `' + code + '`', vars, thisObj, extendVars); + else return _runCode('return ' + code, vars, thisObj, extendVars); +} diff --git a/src/dom-utils.js b/src/dom-utils.js new file mode 100644 index 0000000..59c7c04 --- /dev/null +++ b/src/dom-utils.js @@ -0,0 +1,3 @@ +// src/dom-utils.js +export const $ = (a, b) => b ? a.querySelector(b) : document.querySelector(a); +export const $$ = (a, b) => b ? a.querySelectorAll(b) : document.querySelectorAll(a); diff --git a/src/dom.js b/src/dom.js new file mode 100644 index 0000000..3a08d14 --- /dev/null +++ b/src/dom.js @@ -0,0 +1,380 @@ +// src/dom.js +import { _runCode, _returnCode, setDisableRunCodeError } from './core.js'; +import { getActiveBinding, setActiveBinding, getNoWriteBack, setNoWriteBack, NewState, onNotifyUpdate } from './observer.js'; +import { Component, _makeComponent, _mergeNode } from './component.js'; +import { $, $$ } from './dom-utils.js'; + +let _translator = (text) => text; +export const SetTranslator = (fn) => _translator = fn; + +const _translate = (text) => { + if (!text || typeof text !== 'string') return text; + return text.replace(/\{#(.+?)#\}/g, (m, content) => { + const parts = content.split('||').map(s => s.trim()); + const rawText = parts[0]; + const args = {}; + if (parts.length > 1) { + const matches = rawText.match(/\{(.+?)\}/g); + if (matches) matches.forEach((match, i) => { + const key = match.substring(1, match.length - 1); + args[key] = parts[i + 1] || ''; + }); + } + return _translator(rawText, 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); + }; + } +} + +export { $, $$ }; + +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); + }); + }); +} + +export function _updateBinding(binding) { + const node = binding.node; + const tpl = binding.tpl; + const exp = binding.exp; + + setActiveBinding(binding); + let result = exp ? (tpl ? _returnCode(tpl, { thisNode: node }, node._thisObj || node, node._ref || null) : null) : tpl; + 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 resultIsObject = typeof result === 'object' && result != null && !Array.isArray(result); + const lk = prop[prop.length - 1]; + if (lk) { + if (resultIsObject && 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 (resultIsObject && typeof o === 'object') { + 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 }; + }); + 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'; + 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]; + } + keys.forEach((k, i) => { + const item = getVal(k); + if (node._renderedNodes && i < node._renderedNodes.length) { + node._renderedNodes[i].forEach(child => { + child._ref[indexName] = k; + child._ref[asName] = item; + _scanTree(child); + }); + } else { + const newNodes = []; + if (!node._renderedNodes) node._renderedNodes = []; + node._children.forEach(child => { + const cloned = child.cloneNode(true); + cloned._ref = { ...node._ref }; + cloned._ref[indexName] = k; + cloned._ref[asName] = item; + cloned._thisObj = node._thisObj; + node.parentNode.insertBefore(cloned, node); + newNodes.push(cloned); + }); + node._renderedNodes.push(newNodes); + } + }); + while (node._renderedNodes && node._renderedNodes.length > keys.length) { + node._renderedNodes[node._renderedNodes.length - 1].forEach(child => { + _clearRenderedNodes(child); + child.remove(); + }); + node._renderedNodes.pop(); + } + } else { + _clearRenderedNodes(node); + node._renderedNodes = []; + } + } else if (attr === 'bind') { + if (['INPUT', 'SELECT', 'TEXTAREA'].includes(node.tagName)) { + if (!node.hasAttribute('autocomplete')) node.setAttribute('autocomplete', 'off'); + } + if (node.type === 'checkbox') { + if (node.value !== 'on' && !result) { + _runCode(`${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 ?? ''); + } + } + } + } +} + +export 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); +}; + +export const _parseNode = (node, scanObj) => { + if (node._bindings) { + node._states = new Set(); + node._bindings.forEach(bindingData => { + const binding = { node: node, ...bindingData }; + _updateBinding(binding); + }); + if (node._hasOnUpdate) node.dispatchEvent(new Event('update', { bubbles: false })); + return; + } + + if (Component.exists(node.tagName) && !node._componentInitialized) { + node._componentInitialized = true; + _makeComponent(node.tagName, node, scanObj); + $$(node, '[slot-id]').forEach(placeholder => placeholder.removeAttribute('slot-id')); + if (!node._thisObj) node._thisObj = node; + } + + let attrs = []; + if (node.tagName === 'TEMPLATE') { + node._children = [...node.content.childNodes]; + node._renderedNodes = []; + if (node.hasAttribute('$if')) attrs.push(node.getAttributeNode('$if')); + else if (node.hasAttribute('$each')) attrs.push(node.getAttributeNode('$each')); + else if (node.hasAttribute('st-if')) attrs.push(node.getAttributeNode('st-if')); + else if (node.hasAttribute('st-each')) attrs.push(node.getAttributeNode('st-each')); + } 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('.')); + } + + 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 = new Set(); + + attrs.forEach(attr => { + const exp = attr.name.startsWith('$') || attr.name.startsWith('st-'); + const realAttrName = exp ? attr.name.slice(attr.name.startsWith('$') ? 1 : 3) : attr.name; + let tpl = attr.value; + node.removeAttribute(attr.name); + if (realAttrName.startsWith('.')) { + _initBinding({ node: node, prop: realAttrName.split('.'), tpl, exp }); + } else { + if (realAttrName.startsWith('on')) { + if (realAttrName === 'onupdate') node._hasOnUpdate = 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; + ((node, thisObj) => { + node.addEventListener(realAttrName.slice(2), (e) => { + _runCode(tpl, { event: e, thisNode: node, ...(e.detail || {}) }, thisObj || node, node._ref || {}); + }); + })(node, scanObj.thisObj); + } else { + if (realAttrName === 'bind') { + node.addEventListener(node.tagName === 'TEXTAREA' || node.isContentEditable || node.type === 'text' || node.type === 'password' ? 'input' : 'change', (e) => { + let newVal = node.isContentEditable ? e.target.innerHTML : (node.type === 'checkbox' ? e.target.checked : e.target.files || e.target.value || e.detail); + setNoWriteBack(node); + setDisableRunCodeError(true); + if (node.type === 'checkbox' && node._checkboxMultiMode) { + _runCode(`!!checked ? (!${tpl}.includes(val) && ${tpl}.push(val)) : (index = ${tpl}.indexOf(val), index > -1 && ${tpl}.splice(index, 1))`, { val: node.value, checked: newVal, thisNode: node }, scanObj.thisObj || node, node._ref || {}); + } else { + _runCode(`${tpl} = val`, { val: newVal, thisNode: node }, scanObj.thisObj || node, node._ref || {}); + } + setDisableRunCodeError(false); + setNoWriteBack(null); + }); + } else if (realAttrName === 'text' && !tpl) { + tpl = node.textContent; + node.textContent = ''; + } + if (tpl) { + tpl = _translate(tpl); + _initBinding({ node: node, attr: realAttrName, tpl, exp }); + } + } + } + }); + if (node._hasOnLoad || node._componentInitialized) { + (node => { + Promise.resolve().then(() => node.dispatchEvent(new Event('load', { bubbles: false }))); + })(node); + } + 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) { + const translated = _translate(node.textContent); + if (translated !== node.textContent) node.textContent = translated; + return; + } + if (node.nodeType !== 1) return; + + 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; + } + }); + + 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; + node = template; + 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 === '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; + if (scanObj.thisObj === undefined) { + 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 === undefined) scanObj.extendVars = {}; + if (node._ref !== undefined) { + Object.assign(node._ref, scanObj.extendVars); + scanObj.extendVars = { ...node._ref }; + } + _parseNode(node, scanObj); + const nodes = [...(node.childNodes || [])]; + scanObj.extendVars = node._ref || scanObj.extendVars; + 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(stateMappings => { + for (const [key, bindingSet] of stateMappings) { + for (const binding of bindingSet) { + if (binding.node === node) bindingSet.delete(binding); + } + } + }); + } + node.childNodes && node.childNodes.forEach(child => _unbindTree(child)); +}; + +export const RefreshState = _scanTree; diff --git a/src/globals.js b/src/globals.js new file mode 100644 index 0000000..d3aa744 --- /dev/null +++ b/src/globals.js @@ -0,0 +1,33 @@ +// src/globals.js +import { NewState } from './observer.js'; +import { Util } from './utils.js'; + +// url hash 状态 +let _hashParams = new URLSearchParams(window.location.hash?.substring(1) || '') +export const Hash = NewState({}, k => Util.safeJson(_hashParams.get(k)), (k, v) => { + const oldStr = _hashParams.get(k) + const newStr = v === undefined ? undefined : JSON.stringify(v) + if (oldStr === newStr || (oldStr === null && newStr === undefined)) return + v === undefined ? _hashParams.delete(k) : _hashParams.set(k, newStr) + window.location.hash = '#' + _hashParams.toString() +}) + +if (typeof window !== 'undefined') { + window.addEventListener('hashchange', () => { + const oldHashParams = _hashParams + _hashParams = new URLSearchParams(window.location.hash?.substring(1) || '') + _hashParams.forEach((v, k) => { if (oldHashParams.get(k) !== v) Hash[k] = Util.safeJson(v) }) + oldHashParams.forEach((v, k) => { if (_hashParams.get(k) === undefined) Hash[k] = undefined }) + }) +} + +// localstorage 状态 +export const LocalStorage = NewState({}, k => Util.safeJson(localStorage.getItem(k)), (k, v) => { + const oldStr = localStorage.getItem(k) + const newStr = v === undefined ? undefined : JSON.stringify(v) + if (oldStr === newStr || (oldStr === null && newStr === undefined)) return + v === undefined ? localStorage.removeItem(k) : localStorage.setItem(k, newStr) +}) + +globalThis.Hash = Hash; +globalThis.LocalStorage = LocalStorage; diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..39ad336 --- /dev/null +++ b/src/index.js @@ -0,0 +1,34 @@ +// src/index.js +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'; + +import { Component } from './component.js'; +import { _scanTree, _unbindTree } from './dom.js'; +import { LocalStorage } from './globals.js'; + +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 }); + + const htmlNode = document.documentElement; + if (!htmlNode.hasAttribute('$data-bs-theme') && !htmlNode.hasAttribute('data-bs-theme')) { + htmlNode.setAttribute('$data-bs-theme', "LocalStorage.darkMode?'dark':'light'"); + } + + _scanTree(document.documentElement); + }; + + if (document.readyState !== 'loading') init(); + else document.addEventListener('DOMContentLoaded', init, true); +} diff --git a/src/observer.js b/src/observer.js new file mode 100644 index 0000000..59821e5 --- /dev/null +++ b/src/observer.js @@ -0,0 +1,74 @@ +// src/observer.js +let _activeBinding = null; +let _noWriteBack = null; +let _updateBindingFn = null; + +export function getActiveBinding() { return _activeBinding; } +export function setActiveBinding(val) { _activeBinding = val; } +export function getNoWriteBack() { return _noWriteBack; } +export function setNoWriteBack(val) { _noWriteBack = val; } + +export function onNotifyUpdate(fn) { + _updateBindingFn = fn; +} + +export function NewState(defaults = {}, getter = null, setter = null) { + const _defaults = {}; + const _stateMappings = new Map(); + const _watchers = new Map(); + const _watchFunc = (k, cb) => { + if (!_watchers.has(k)) _watchers.set(k, new Set()); + !cb ? _watchers.get(k).clear() : _watchers.get(k).add(cb); + }; + const _unwatchFunc = (k, cb) => { + if (!_watchers.has(k)) _watchers.set(k, new Set()); + _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 (_activeBinding) { + if (!_stateMappings.has(key)) _stateMappings.set(key, new Set()); + _stateMappings.get(key).add(_activeBinding); + if (!_activeBinding.node._states) _activeBinding.node._states = 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 !== undefined) { + 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 && _updateBindingFn) { + _updateBindingFn(binding); + } + } + } + return true; + } + }); +} diff --git a/src/utils.js b/src/utils.js new file mode 100644 index 0000000..e091c72 --- /dev/null +++ b/src/utils.js @@ -0,0 +1,47 @@ +// src/utils.js +export 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] === undefined) 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+<").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 = new Date().getTime(), + end: () => { + const endTime = new Date().getTime() + const left = endTime - startTime + startTime = endTime + total += left + count++ + return left + }, + avg: () => total / count + } + }, +} + +globalThis.Util = Util; diff --git a/test-results/.last-run.json b/test-results/.last-run.json new file mode 100644 index 0000000..cbcc1fb --- /dev/null +++ b/test-results/.last-run.json @@ -0,0 +1,4 @@ +{ + "status": "passed", + "failedTests": [] +} \ No newline at end of file diff --git a/test/all.spec.js b/test/all.spec.js new file mode 100644 index 0000000..cd58851 --- /dev/null +++ b/test/all.spec.js @@ -0,0 +1,43 @@ +import { test, expect } from '@playwright/test'; + +test('modular unit tests and benchmark', async ({ page }) => { + page.on('console', msg => console.log('BROWSER LOG:', msg.text())); + await page.goto('http://localhost:8081/test/index.html'); + + // Wait for testStatus to be set + await page.waitForFunction(() => window.testStatus !== undefined, { timeout: 10000 }); + + const status = await page.evaluate(() => window.testStatus); + expect(status).toBe('passed'); + + // Benchmark: Large list rendering + const renderTime = await page.evaluate(async () => { + const start = performance.now(); + document.body.innerHTML = ` +
    + +
+ `; + const items = []; + for(let i=0; i<1000; i++) items.push({val: 'item ' + i}); + window.state.benchItems = items; + const { RefreshState } = await import('@web/state'); + RefreshState(document.documentElement); + return performance.now() - start; + }); + console.log(`BENCHMARK: 1000 items initial render: ${renderTime.toFixed(2)}ms`); + + // Benchmark: Large list update + const updateTime = await page.evaluate(async () => { + const start = performance.now(); + window.state.benchItems[0].val = 'updated'; + // Note: Shallow proxy requires reassignment or internal trigger if we modified a deep property. + // But here we modify benchItems[0], which is an object inside the array. + // Our current observer.js might not catch this if it's benchItems[0] = ... + window.state.benchItems = [...window.state.benchItems]; + return performance.now() - start; + }); + console.log(`BENCHMARK: 1000 items update (shallow): ${updateTime.toFixed(2)}ms`); +}); diff --git a/test/component.test.js b/test/component.test.js new file mode 100644 index 0000000..81292d1 --- /dev/null +++ b/test/component.test.js @@ -0,0 +1,35 @@ +// test/component.test.js +import { Component } from '../src/component.js'; +import { RefreshState, $ } from '../src/dom.js'; + +export async function testComponent() { + console.log('Testing component.js...'); + + // 1. Register component FIRST + Component.register('MY-COMP', (node) => { + // setup + }); + + // 2. Add template and instance + document.body.innerHTML = ` + + + `; + + // 3. Scan + RefreshState(document.documentElement); + + // 4. Wait a bit for any async DOM updates + await new Promise(r => setTimeout(r, 100)); + + const instance = $('#comp-instance'); + if (!instance.innerHTML.includes('Component Content')) { + console.log('Current instance innerHTML:', instance.innerHTML); + throw new Error('Component rendering failed'); + } + + console.log('component.js tests passed'); + return true; +} diff --git a/test/core.test.js b/test/core.test.js new file mode 100644 index 0000000..b1e45dc --- /dev/null +++ b/test/core.test.js @@ -0,0 +1,18 @@ +// test/core.test.js +import { _runCode, _returnCode } from '../src/core.js'; + +export async function testCore() { + console.log('Testing core.js...'); + const vars = { a: 1, b: 2 }; + const extendVars = { c: 3 }; + + // _runCode + if (_runCode('return a + b + c', vars, {}, extendVars) !== 6) throw new Error('_runCode failed'); + + // _returnCode + if (_returnCode('a + b', vars, {}) !== 3) throw new Error('_returnCode simple failed'); + if (_returnCode('${a} + ${b}', vars, {}) !== '1 + 2') throw new Error('_returnCode template failed'); + + console.log('core.js tests passed'); + return true; +} diff --git a/test/dom.test.js b/test/dom.test.js new file mode 100644 index 0000000..b9eab5a --- /dev/null +++ b/test/dom.test.js @@ -0,0 +1,88 @@ +// test/dom.test.js +import { RefreshState, $, $$ } from '@web/state'; +import { NewState } from '@web/state'; + +export async function testDom() { + console.log('Testing dom.js...'); + + // 1. Basic $text binding + document.body.innerHTML = `
`; + window.state = NewState({ msg: 'hello' }); + RefreshState(document.documentElement); + const node = $('#test-node'); + if (node.textContent !== 'hello') throw new Error('$text binding failed'); + state.msg = 'world'; + if (node.textContent !== 'world') throw new Error('$text update failed'); + + // 2. $if directive + document.body.innerHTML = ` +
+ +
+ `; + state.show = false; + RefreshState(document.documentElement); + if ($('#if-content')) throw new Error('$if failed: should be hidden'); + + state.show = true; + await Promise.resolve(); + if (!$('#if-content') || $('#if-content').textContent !== 'Visible') throw new Error('$if failed: should be visible'); + + state.show = false; + await Promise.resolve(); + if ($('#if-content')) throw new Error('$if failed: should be hidden again'); + + // 3. $each directive (Index-based reuse) + document.body.innerHTML = ` +
    + +
+ `; + state.items = [{ name: 'A' }, { name: 'B' }]; + RefreshState(document.documentElement); + await Promise.resolve(); // Wait for MutationObserver + let items = $$('#list-test li'); + console.log('$each items length:', items.length); + if (items.length > 0) console.log('$each first item text:', items[0].textContent); + if (items.length !== 2 || items[0].textContent !== 'A' || items[1].textContent !== 'B') throw new Error('$each initialization failed'); + + const firstNode = items[0]; + state.items = [{ name: 'A-mod' }, { name: 'B' }, { name: 'C' }]; + await Promise.resolve(); + items = $$('#list-test li'); + 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'); + + state.items = [{ name: 'C' }]; + await Promise.resolve(); + items = $$('#list-test li'); + if (items.length !== 1 || items[0].textContent !== 'C') throw new Error('$each removal failed'); + + // 4. Two-way binding (bind) + document.body.innerHTML = ``; + state.val = 'initial'; + RefreshState(document.documentElement); + await Promise.resolve(); + const input = $('#input-test'); + if (input.value !== 'initial') throw new Error('$bind initial value failed'); + + input.value = 'changed'; + input.dispatchEvent(new Event('input')); + if (state.val !== 'changed') throw new Error('$bind write-back failed'); + + // 5. Unbinding cleanup (mock check) + // _unbindTree is called when nodes are removed via $if or $each. + // We verify that after $if=false, the state mappings for that node are cleared. + // This is hard to test directly without exposing internal Map, but we can check if it crashes. + state.show = true; + const ifNode = $('#if-content'); + state.show = false; // Trigger _unbindTree via _clearRenderedNodes -> remove() -> MutationObserver (or manual in some cases) + // Actually MutationObserver handles _unbindTree in index.js. + + console.log('dom.js tests passed'); + return true; +} diff --git a/test/index.html b/test/index.html new file mode 100644 index 0000000..700424c --- /dev/null +++ b/test/index.html @@ -0,0 +1,39 @@ + + + + State.js Modular Tests + + + +
Running tests...
+ + + diff --git a/test/observer.test.js b/test/observer.test.js new file mode 100644 index 0000000..5deca8c --- /dev/null +++ b/test/observer.test.js @@ -0,0 +1,28 @@ +// test/observer.test.js +import { NewState } from '../src/observer.js'; + +export async function testObserver() { + console.log('Testing observer.js...'); + + let watchTriggered = 0; + const state = NewState({ count: 0 }); + + state.__watch('count', (val) => { + watchTriggered = val; + }); + + state.count = 10; + if (watchTriggered !== 10) throw new Error('Watcher not triggered or value incorrect'); + if (state.count !== 10) throw new Error('State value not updated'); + + // General watcher + let generalTriggered = false; + state.__watch(null, () => { + generalTriggered = true; + }); + state.count = 20; + if (!generalTriggered) throw new Error('General watcher not triggered'); + + console.log('observer.js tests passed'); + return true; +} diff --git a/vite.config.js b/vite.config.js new file mode 100644 index 0000000..c986527 --- /dev/null +++ b/vite.config.js @@ -0,0 +1,28 @@ +import { defineConfig } from 'vite'; +import { resolve } from 'path'; +import terser from '@rollup/plugin-terser'; + +export default defineConfig({ + build: { + lib: { + entry: resolve(__dirname, 'src/index.js'), + name: 'State', + formats: ['es'] + }, + rollupOptions: { + output: [ + { + format: 'es', + entryFileNames: 'state.js', + minifyInternalExports: false + }, + { + format: 'es', + entryFileNames: 'state.min.js', + plugins: [terser()] + } + ] + }, + minify: false + } +});