uentropy 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +306 -0
- package/dist/entropy.min.js +2 -0
- package/dist/entropy.min.js.map +1 -0
- package/dist/index.cjs +961 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +187 -0
- package/dist/index.d.ts +187 -0
- package/dist/index.js +954 -0
- package/dist/index.js.map +1 -0
- package/package.json +53 -0
package/README.md
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
# entropy
|
|
2
|
+
|
|
3
|
+
A small reactive DOM library. No virtual DOM, no compiler, no JSX. You write plain HTML with a few extra attributes and plain JavaScript — entropy keeps them in sync.
|
|
4
|
+
|
|
5
|
+
The core idea is simple: wrap your data in `en.init()`, put `en-mark` on the elements that should display it, and that's most of what you need to know.
|
|
6
|
+
|
|
7
|
+
```html
|
|
8
|
+
<span en-mark="count">0</span>
|
|
9
|
+
<button onclick="data.count++">+</button>
|
|
10
|
+
|
|
11
|
+
<script src="dist/index.global.js"></script>
|
|
12
|
+
<script>
|
|
13
|
+
window.data = UEntropy.default.init();
|
|
14
|
+
data.count = 0;
|
|
15
|
+
</script>
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## Installation
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
npm install uentropy
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Or drop the IIFE build straight into your HTML — no bundler, no `node_modules`, no build step for consumers:
|
|
27
|
+
|
|
28
|
+
```html
|
|
29
|
+
<script src="https://cdn.jsdelivr.net/npm/uentropy/dist/index.global.js"></script>
|
|
30
|
+
<script>
|
|
31
|
+
const en = UEntropy.default;
|
|
32
|
+
window.data = en.init();
|
|
33
|
+
</script>
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
ESM import for bundled projects:
|
|
37
|
+
|
|
38
|
+
```js
|
|
39
|
+
import en from 'uentropy';
|
|
40
|
+
const data = en.init();
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## How it works
|
|
46
|
+
|
|
47
|
+
`en.init()` returns a `Proxy`. Setting a property on it triggers a DOM scan for elements whose directive attribute matches that key, then updates them. No diffing, no scheduling, no magic — just a `set` trap and `querySelectorAll`.
|
|
48
|
+
|
|
49
|
+
This makes entropy very fast for small-to-medium DOMs and straightforward to reason about. It also means the performance profile is different from virtual DOM frameworks: reads are free, writes are proportional to the size of the relevant DOM subtree.
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## Directives
|
|
54
|
+
|
|
55
|
+
Directives are HTML attributes that tell entropy what to do with a value.
|
|
56
|
+
|
|
57
|
+
### `en-mark`
|
|
58
|
+
|
|
59
|
+
Sets `textContent` to the value. For objects, serialises to JSON.
|
|
60
|
+
|
|
61
|
+
```html
|
|
62
|
+
<span en-mark="user.name"></span>
|
|
63
|
+
<pre en-mark="config"></pre>
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### `en-model`
|
|
67
|
+
|
|
68
|
+
Two-way binding. Keeps a reactive key and an input element in sync — DOM
|
|
69
|
+
updates when data changes, and data updates when the user interacts with the
|
|
70
|
+
element. No `oninput` handler needed.
|
|
71
|
+
|
|
72
|
+
```html
|
|
73
|
+
<input en-model="name" />
|
|
74
|
+
<input type="number" en-model="qty" />
|
|
75
|
+
<input type="checkbox" en-model="agreed" />
|
|
76
|
+
<input type="radio" en-model="size" value="M" />
|
|
77
|
+
<select en-model="country">…</select>
|
|
78
|
+
<textarea en-model="bio"></textarea>
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Works across all standard input types:
|
|
82
|
+
|
|
83
|
+
| Element | Event listened | Data type written |
|
|
84
|
+
|---|---|---|
|
|
85
|
+
| `input[type=text\|email\|…]` | `input` | string |
|
|
86
|
+
| `input[type=number]` | `input` | number |
|
|
87
|
+
| `input[type=checkbox]` | `change` | boolean |
|
|
88
|
+
| `input[type=radio]` | `change` | string (the `value` attr) |
|
|
89
|
+
| `select` | `change` | string |
|
|
90
|
+
| `textarea` | `input` | string |
|
|
91
|
+
|
|
92
|
+
Listeners are attached once per element and are garbage-collected with the
|
|
93
|
+
element — no manual cleanup required.
|
|
94
|
+
|
|
95
|
+
### `en-if` / `en-ifnot`
|
|
96
|
+
|
|
97
|
+
Must be on a `<template>` element. Entropy moves the template's content into the DOM when the condition is met, and puts it back when it isn't.
|
|
98
|
+
|
|
99
|
+
```html
|
|
100
|
+
<template en-if="isLoggedIn">
|
|
101
|
+
<nav>…</nav>
|
|
102
|
+
</template>
|
|
103
|
+
|
|
104
|
+
<template en-ifnot="isLoggedIn">
|
|
105
|
+
<a href="/login">Sign in</a>
|
|
106
|
+
</template>
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Lists
|
|
110
|
+
|
|
111
|
+
Use `#` as a wildcard key to mark the item template:
|
|
112
|
+
|
|
113
|
+
```html
|
|
114
|
+
<ul>
|
|
115
|
+
<li en-mark="items.#"></li>
|
|
116
|
+
</ul>
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
```js
|
|
120
|
+
data.items = ['one', 'two', 'three'];
|
|
121
|
+
data.items.push('four');
|
|
122
|
+
data.items.splice(1, 1);
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Object arrays work the same way — nest keys inside the template:
|
|
126
|
+
|
|
127
|
+
```html
|
|
128
|
+
<ul>
|
|
129
|
+
<li en-mark="users.#">
|
|
130
|
+
<strong en-mark="users.#.name"></strong>
|
|
131
|
+
<span en-mark="users.#.email"></span>
|
|
132
|
+
</li>
|
|
133
|
+
</ul>
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### Custom directives
|
|
137
|
+
|
|
138
|
+
Register your own with `en.directive(name, callback, isParametric?)`.
|
|
139
|
+
|
|
140
|
+
```js
|
|
141
|
+
en.directive('attr', ({ el, value, param }) => {
|
|
142
|
+
if (param) el.setAttribute(param, String(value));
|
|
143
|
+
}, true /* parametric */);
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
```html
|
|
147
|
+
<!-- en-attr="key:attribute-name" -->
|
|
148
|
+
<status-pill en-attr="card.status:status"></status-pill>
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
The callback receives:
|
|
152
|
+
- `el` — the DOM element
|
|
153
|
+
- `value` — current reactive value
|
|
154
|
+
- `param` — the part after the colon (parametric directives only)
|
|
155
|
+
- `key` — full key string
|
|
156
|
+
- `isDelete` — `true` when the key was deleted
|
|
157
|
+
|
|
158
|
+
---
|
|
159
|
+
|
|
160
|
+
## API
|
|
161
|
+
|
|
162
|
+
### `en.init()`
|
|
163
|
+
|
|
164
|
+
Returns the reactive data proxy. Idempotent — multiple calls return the same proxy.
|
|
165
|
+
|
|
166
|
+
### `en.computed(fn)`
|
|
167
|
+
|
|
168
|
+
Wraps a function so it re-runs automatically when its dependencies change. Assign the result to a reactive key.
|
|
169
|
+
|
|
170
|
+
```js
|
|
171
|
+
data.fullName = en.computed(() => `${data.first} ${data.last}`);
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Async functions work too. Stale results from rapid successive changes are automatically discarded — only the most recent resolved value is applied.
|
|
175
|
+
|
|
176
|
+
```js
|
|
177
|
+
data.results = en.computed(async () => {
|
|
178
|
+
const res = await fetch(`/api/search?q=${data.query}`);
|
|
179
|
+
return res.json();
|
|
180
|
+
});
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
### `en.watch(key, fn)`
|
|
184
|
+
|
|
185
|
+
Calls `fn(newValue)` whenever the value at `key` or any of its children changes.
|
|
186
|
+
|
|
187
|
+
```js
|
|
188
|
+
en.watch('cart', () => recalculateTotal());
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
### `en.unwatch(key?, fn?)`
|
|
192
|
+
|
|
193
|
+
Removes watchers. Accepts any combination:
|
|
194
|
+
|
|
195
|
+
```js
|
|
196
|
+
en.unwatch(); // remove everything
|
|
197
|
+
en.unwatch('cart'); // remove all watchers for this key
|
|
198
|
+
en.unwatch(undefined, handler); // remove this handler from all keys
|
|
199
|
+
en.unwatch('cart', handler); // remove this handler from this key
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
### `en.batch(fn)`
|
|
203
|
+
|
|
204
|
+
Queues all reactive writes inside `fn` and flushes the DOM exactly once when it returns. Essential for bulk updates.
|
|
205
|
+
|
|
206
|
+
```js
|
|
207
|
+
en.batch(() => {
|
|
208
|
+
data.loading = false;
|
|
209
|
+
data.results = response.items;
|
|
210
|
+
data.total = response.total;
|
|
211
|
+
});
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
### `en.prefix(value?)`
|
|
215
|
+
|
|
216
|
+
Changes the directive prefix. Call before `en.init()`. Useful when entropy shares a page with other attribute-based tools.
|
|
217
|
+
|
|
218
|
+
```js
|
|
219
|
+
en.prefix('data-x');
|
|
220
|
+
// Use data-x-mark, data-x-if, data-x-ifnot, etc.
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
### `en.directive(name, callback, isParametric?)`
|
|
224
|
+
|
|
225
|
+
Registers a custom directive. Has no effect if the name is already registered.
|
|
226
|
+
|
|
227
|
+
### `en.register(...)`
|
|
228
|
+
|
|
229
|
+
Registers `<template name="…">` elements as Web Components backed by Shadow DOM. Accepts no arguments (scans the document), an element, a string of HTML, or a tagged-template literal.
|
|
230
|
+
|
|
231
|
+
```js
|
|
232
|
+
en.register`
|
|
233
|
+
<template name="user-card">
|
|
234
|
+
<style>:host { border: 1px solid #ddd; }</style>
|
|
235
|
+
<slot name="name"></slot>
|
|
236
|
+
</template>
|
|
237
|
+
`;
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
### `en.load(files)`
|
|
241
|
+
|
|
242
|
+
Fetches external HTML files and registers any templates inside them.
|
|
243
|
+
|
|
244
|
+
```js
|
|
245
|
+
await en.load(['components/card.html', 'components/modal.html']);
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
### `en.destroy()`
|
|
249
|
+
|
|
250
|
+
Removes all event listeners, clears watchers, marks the instance as destroyed. Updates stop. Use for teardown in SPAs or when destroying a widget.
|
|
251
|
+
|
|
252
|
+
---
|
|
253
|
+
|
|
254
|
+
## Multiple instances
|
|
255
|
+
|
|
256
|
+
The default export is a singleton — fine for most pages. For isolated widgets or micro-frontends that need separate reactive scopes:
|
|
257
|
+
|
|
258
|
+
```js
|
|
259
|
+
import { createInstance } from 'uentropy';
|
|
260
|
+
|
|
261
|
+
const enA = createInstance();
|
|
262
|
+
const enB = createInstance();
|
|
263
|
+
enB.prefix('widget-b');
|
|
264
|
+
|
|
265
|
+
const dataA = enA.init();
|
|
266
|
+
const dataB = enB.init();
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
---
|
|
270
|
+
|
|
271
|
+
## Limits
|
|
272
|
+
|
|
273
|
+
These are not bugs — they are deliberate trade-offs given the no-build, no-VDOM approach.
|
|
274
|
+
|
|
275
|
+
**Scale.** `querySelectorAll` runs on every reactive write. With a small-to-medium DOM this is faster than virtual DOM diffing. Beyond ~2000–3000 active reactive elements the cost starts to compound, especially on replace-all operations. Use `en.batch()` for bulk writes.
|
|
276
|
+
|
|
277
|
+
**No key-based reconciliation.** When you reassign an array (`data.rows = newRows`), entropy removes all existing item elements and recreates them from the template. Preact and Vue can reuse DOM nodes by key — entropy cannot. For lists that update partially and frequently, mutate in place (`splice`, index assignment) rather than replacing the whole array.
|
|
278
|
+
|
|
279
|
+
**Reactive arrays are shallow.** `data.items.push(x)` works because entropy wraps the array in a Proxy. But methods that return a new array (`map`, `filter`, `reduce`) are not tracked — assign the result back to a reactive key to trigger updates.
|
|
280
|
+
|
|
281
|
+
```js
|
|
282
|
+
// won't update the DOM
|
|
283
|
+
data.items.filter(x => x.done);
|
|
284
|
+
|
|
285
|
+
// will
|
|
286
|
+
data.items = data.items.filter(x => x.done);
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
**No SSR.** Entropy reads and writes the live DOM. It has no concept of rendering to a string.
|
|
290
|
+
|
|
291
|
+
**Computed dependency tracking is key-based, not value-based.** A computed function re-runs when any key it accessed during its last execution is set — regardless of whether the new value actually differs. Avoid heavy work inside computed functions that depend on frequently-changing keys.
|
|
292
|
+
|
|
293
|
+
**`en-mark` on objects serialises to JSON.** There is no template syntax inside a mark value. If you need conditional rendering or structured output, use custom directives or nested elements with their own marks.
|
|
294
|
+
|
|
295
|
+
**`en-model` listens to a single event per element.** The event is chosen
|
|
296
|
+
based on the input type (`input` for text/number/textarea, `change` for
|
|
297
|
+
checkboxes, radios, and selects). If you need a different event for a custom
|
|
298
|
+
element, register a custom directive instead.
|
|
299
|
+
|
|
300
|
+
**Web Components require Shadow DOM support.** Named `<template>` registration uses `attachShadow`. This works in all modern browsers but has no fallback for older environments.
|
|
301
|
+
|
|
302
|
+
---
|
|
303
|
+
|
|
304
|
+
## License
|
|
305
|
+
|
|
306
|
+
MIT
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var UEntropy=(function(exports){'use strict';function F(){return {data:null,prefix:"en-",watchers:new Map,directives:new Map,deps:{isEvaluating:false,set:new Set,map:new Map,versions:new Map},computedResultFns:new WeakSet,batchQueue:null,destroyed:false,elementCache:new Map,observer:null}}var p=Symbol("@en/prefix");function E(t,e){return e===""?t:`${e}.${t}`}function P(t,e,n){if(!n)return;let r=t.getAttribute(e);if(r)return r.slice(r.indexOf(":")+1)}function A(t){return typeof t=="object"&&t!==null&&p in t}function g(t){if(t===null||typeof t!="object")return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp)return new RegExp(t.source,t.flags);if(t instanceof Map)return new Map([...t].map(([n,r])=>[g(n),g(r)]));if(t instanceof Set)return new Set([...t].map(n=>g(n)));if(Array.isArray(t))return t.map(n=>g(n));let e=Object.create(Object.getPrototypeOf(t));for(let n of Object.keys(t))e[n]=g(t[n]);return e}var ie=Symbol("@en/computed");function D(t){return Object.defineProperty(t,ie,{value:true,enumerable:false,configurable:true,writable:false}),t}function se(t,e){for(let[n,r]of t.deps.map){let o=r.filter(i=>i.key!==e);o.length===0?t.deps.map.delete(n):t.deps.map.set(n,o);}}function ce(t,e,n,r,o){let i={key:e,computed:n,parent:r,prop:o};for(let s of t.deps.set){let c=t.deps.map.get(s)??[];c.push(i),t.deps.map.set(s,c);}}function R(t,e,n,r,o){se(t,n),t.deps.isEvaluating=true,t.deps.set.clear();try{e();}catch{}finally{t.deps.isEvaluating=false;}ce(t,n,e,r,o),t.deps.set.clear();}function O(t,e){let n=[...t.deps.map.entries()].filter(([o])=>o===e||o.startsWith(e+".")||e.startsWith(o+".")).flatMap(([,o])=>o),r=new Set;return n.filter(o=>r.has(o.computed)?false:(r.add(o.computed),true))}function W(t,e){t.deps.map.delete(e);for(let[n,r]of t.deps.map){let o=r.filter(i=>i.key!==e);o.length===0?t.deps.map.delete(n):t.deps.map.set(n,o);}}function M(t,e){let n=(t.deps.versions.get(e)??0)+1;return t.deps.versions.set(e,n),n}function S(t,e,n){return t.deps.versions.get(e)===n}function $(t,e,n){let r=t.watchers.get(e)??[];r.push(n),t.watchers.set(e,r);}function I(t,e,n){if(!e&&!n){t.watchers.clear();return}if(e&&!n){t.watchers.delete(e);return}let r=e?[[e,t.watchers.get(e)??[]]]:[...t.watchers.entries()];for(let[o,i]of r){let s=i.filter(c=>c!==n);s.length===0?t.watchers.delete(o):t.watchers.set(o,s);}}function N(t,e,n,r){for(let[o,i]of t.watchers)if(e===o)i.forEach(s=>s(n));else if(e.startsWith(o+".")){let s=r(o);i.forEach(c=>c(s));}}function x(t,e){let n=t.data,r,o="";if(n===null)return {parent:n,value:r,prop:o};let i=e.split(".");for(let s=0;s<i.length;s++)if(o=i[s],r=Reflect.get(n,o),s<i.length-1){if(typeof r!="object"||r===null)return {parent:n,value:void 0,prop:o};n=r;}return {parent:n,value:r,prop:o}}function ae({el:t,value:e,isDelete:n}){if(n){ue(t);return}t instanceof HTMLElement&&(typeof e=="object"&&e!==null&&(e=JSON.stringify(e)),t.textContent=typeof e=="string"?e:String(e));}var V=new WeakMap;function fe(t){return ({el:e,value:n,key:r})=>{if(!(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement))return;if(e instanceof HTMLInputElement&&e.type==="checkbox")e.checked=!!n;else if(e instanceof HTMLInputElement&&e.type==="radio")e.checked=e.value===String(n);else {let a=n==null?"":String(n);e.value!==a&&(e.value=a);}if(V.has(e))return;let o=e instanceof HTMLInputElement&&e.type==="checkbox",i=e instanceof HTMLInputElement&&e.type==="radio",s=e instanceof HTMLInputElement&&e.type==="number",c=e instanceof HTMLSelectElement,f=o||i||c?"change":"input",l=()=>{let{parent:a,prop:u}=x(t,r);if(!a)return;let d;o?d=e.checked:s?d=e.valueAsNumber:d=e.value,Reflect.set(a,u,d);};e.addEventListener(f,l),V.set(e,l);}}function q(t){return {if:{cb:({el:e,value:n,key:r})=>t(e,n,r,"if")},ifnot:{cb:({el:e,value:n,key:r})=>t(e,n,r,"ifnot")}}}function ue(t){let e=t.parentElement;if(!(t instanceof HTMLElement)||!e)return t.remove();let n=t.getAttribute("data-en-mark")??t.getAttribute("en-mark"),r=e.getAttribute("data-en-mark")??e.getAttribute("en-mark");if(n&&n===r)return e.remove();t.remove();}var Q={cb:ae};function U(t){return {cb:fe(t)}}function B(t){t.directives.set("mark",Q),t.directives.set("model",U(t));}function G(t,e,n,r=false){t.directives.has(e)||t.directives.set(e,{cb:n,isParametric:r});}function J(t){B(t);let e=q((n,r,o,i)=>Ee(t,n,r,o,i));t.directives.set("if",e.if),t.directives.set("ifnot",e.ifnot);}function X(t){t.observer||typeof MutationObserver>"u"||(t.observer=new MutationObserver(()=>t.elementCache.clear()),t.observer.observe(document,{childList:true,subtree:true}));}function Y(t,e,n){if(!(e instanceof Document))return Array.from(e.querySelectorAll(n));let r=t.elementCache.get(n);if(r)return r;let o=Array.from(e.querySelectorAll(n));return t.elementCache.set(n,o),o}function w(t,e,n,r,o){if(e===null)return e;let i=typeof e=="object",s=typeof e=="function";if(s&&r&&(e=e.bind(r)),(i||s)&&Object.defineProperty(e,p,{value:n,enumerable:false,writable:true,configurable:true}),s&&o&&r)return R(t,e,n,r,o),e;if(!i)return e;let c=new Proxy(e,le(t));for(let f of Object.keys(e)){let l=E(f,n),a=e[f];e[f]=w(t,a,l,c,f);}return c}function le(t){return {get(e,n,r){t.deps.isEvaluating&&typeof n=="string"&&Object.getOwnPropertyDescriptor(e,n)?.enumerable&&t.deps.set.add(E(n,e[p]));let o=Reflect.get(e,n,r);if(typeof o=="function"&&p in o&&!t.computedResultFns.has(o)){let i=o();return i instanceof Promise?i.then(s=>k(t,s)):k(t,i)}return o},set(e,n,r,o){if(typeof n=="symbol")return Reflect.set(e,n,r,o);let i=E(n,e[p]),s=w(t,r,i,o,n),c=Reflect.set(e,n,s,o);return _(t,()=>h(t,s,i,false,o,n)),_(t,()=>de(t,i)),c},deleteProperty(e,n){if(typeof n=="symbol")return Reflect.deleteProperty(e,n);let r=E(n,e[p]),o=Reflect.deleteProperty(e,n);return h(t,void 0,r,true,e,n),W(t,r),o},defineProperty(e,n,r){return n===p&&p in e&&typeof r.value=="string"&&/\.\d+$/.test(r.value)?Reflect.set(e,n,r.value):Reflect.defineProperty(e,n,r)}}}function _(t,e){t.batchQueue!==null?t.batchQueue.push(e):e();}function de(t,e){let n=O(t,e);for(let r of n)h(t,r.computed,r.key,false,r.parent,r.prop);}function h(t,e,n,r,o,i,s){if(!t.destroyed&&!(typeof e=="function"&&!t.computedResultFns.has(e)&&(e=me(t,e,n,o,i),e===void 0))){if(e instanceof Promise){let c=M(t,n);e.then(f=>{S(t,n,c)&&h(t,f,n,false,o,i,s);});return}s||N(t,n,e,c=>x(t,c).value),j(t,e,n,r,o,i,void 0,void 0,s);}}function me(t,e,n,r,o){let i=M(t,n),s=e();if(s instanceof Promise){s.then(c=>{if(!S(t,n,i))return;let f=k(t,c,n,r,o);h(t,f,n,false,r,o);}).catch(c=>console.error(`[entropy] Async computed error at "${n}":`,c));return}return k(t,s,n,r,o)}function k(t,e,n,r,o){return typeof e=="function"?(t.computedResultFns.add(e),e):n===void 0||r===void 0||o===void 0?g(e):w(t,g(e),n,r,o)}function j(t,e,n,r,o,i,s,c,f){let l=Array.isArray(o);if(l&&/^\d+$/.test(i)&&!c&&f?.skipMark!==true?ge(t,n,i,e,o):l&&i==="length"&&be(t,o),A(e)){Array.isArray(e)&&f?.skipMark!==true?pe(t,e,n,r,o,i,s,f):ye(t,e,n,r,o,i,s),Array.isArray(e)||L(t,e,n,r,o,i,s,f);return}L(t,e,n,r,o,i,s,f);}function pe(t,e,n,r,o,i,s,c){let f=`${n}.#`,a=`[${t.prefix+"mark"}="${f}"]`,u=document;c?.el.parentElement&&(u=c.el.parentElement);let d=[];Y(t,u,a).forEach(y=>{let m=ve(t,y,f,e);d.push(m);});for(let y of d)for(let m in e)j(t,e[m],E(m,n),r,e,m,y[m]??void 0,true);L(t,e.length,E("length",n),r,e,"length",s);}function ye(t,e,n,r,o,i,s){for(let c in e)j(t,e[c],E(c,n),r,e,c,s);}function L(t,e,n,r,o,i,s,c){if(c){let{el:l,directive:a,skipConditionals:u,skipMark:d}=c;if(d&&a==="mark"||u&&(a==="if"||a==="ifnot"))return;let y=t.directives.get(a);if(!y)return;let{cb:m,isParametric:v}=y,oe=P(l,t.prefix+a,!!v);m({el:l,value:e,key:n,isDelete:r,parent:o,prop:i,param:oe});return}let f=s??document;for(let[l,{cb:a,isParametric:u}]of t.directives){let d=t.prefix+l,y=u?`[${d}^='${n}:']`:`[${d}='${n}']`;if(Y(t,f,y).forEach(m=>{let v=P(m,d,!!u);a({el:m,value:e,key:n,isDelete:r,parent:o,prop:i,param:v});}),f instanceof Element&&f.getAttribute(d)===n){let m=P(f,d,!!u);a({el:f,value:e,key:n,isDelete:r,parent:o,prop:i,param:m});}}}function Ee(t,e,n,r,o){let i=o==="if"?!!n:!n,s=e instanceof HTMLTemplateElement,c=t.prefix+o,f=t.prefix+"mark";if(i&&s){let l=e.content.firstElementChild;if(!l)return;l.setAttribute(c,r),Z(t,l,true),e.replaceWith(l);}if(!i&&!s){let l=document.createElement("template");l.content.appendChild(e.cloneNode(true)),l.setAttribute(c,r);let a=e.getAttribute(f);a&&l.setAttribute(f,a),e.replaceWith(l);}}function Z(t,e,n){Array.from(e.children).forEach(r=>Z(t,r,false)),K(t,e,n,false);}function T(t,e){Array.from(e.children).forEach(n=>T(t,n)),K(t,e,false,true);}function K(t,e,n,r){for(let[o]of t.directives){if(r&&o==="mark"||n&&(o==="if"||o==="ifnot"))continue;let{isParametric:i}=t.directives.get(o),s=t.prefix+o,c=e.getAttribute(s);if(i&&(c=c?.split(":")[0]??null),c?.endsWith(".#")&&(c=c.slice(0,-2)),c===null)continue;let{value:f,parent:l,prop:a}=x(t,c);l&&h(t,f,c,false,l,a,{directive:o,el:e,...n!==void 0?{skipConditionals:n}:{},...r!==void 0?{skipMark:r}:{}});}}function ge(t,e,n,r,o){let i=t.prefix+"mark",s=document.querySelectorAll(`[${i}="${e}"]`);if(s.length&&!A(r))return;let c=o[p]??"",f=e.replace(/\d+$/,"#"),l=false;Array.from(s).forEach(a=>{let u=he(t,a,f,i);u&&(H(t,n,c,f,u),a.replaceWith(u),T(t,u),l=true);}),!l&&Array.from(document.querySelectorAll(`[${i}="${f}"]`)).forEach(a=>{if(!(a instanceof HTMLTemplateElement))return;let u=a.content.firstElementChild?.cloneNode(true);u instanceof Element&&(H(t,n,c,f,u),a.before(u),T(t,u));});}function he(t,e,n,r){let o=e.nextElementSibling;for(;o&&o.getAttribute(r)!==n;)o=o.nextElementSibling;if(o instanceof HTMLTemplateElement){let i=o.content.firstElementChild?.cloneNode(true);return i instanceof Element?i:null}return o?.getAttribute(r)===n?o.cloneNode(true):null}function be(t,e){let n=t.prefix+"mark",r=E("#",e[p]??"");Array.from(document.querySelectorAll(`[${n}="${r}"]`)).forEach(o=>{let i=[],s=o.previousElementSibling,c=true,f=-1;for(;s;){let a=s;s=a.previousElementSibling;let u=a.getAttribute(n);if(u){if(u===r)break;if(u.replace(/\d+$/,"#")===r&&(i.push(a),c)){let d=Number(u.slice(u.lastIndexOf(".")+1)??-1);f!==-1&&f!==d+1&&(c=false),f=d;}}}if(c)return;[...i].sort((a,u)=>{let d=a.getAttribute(n)??"",y=u.getAttribute(n)??"",m=+(d.split(".").pop()??0),v=+(y.split(".").pop()??0);return m-v}).forEach(a=>o.before(a));});}function ve(t,e,n,r){let o=t.prefix+"mark",i=e.previousElementSibling;for(;i;){let a=i;i=a.previousElementSibling;let u=a.getAttribute(o);if(u)if(u!==n&&u.replace(/\d+$/,"#")===n)a.remove();else break}let s,c;if(e instanceof HTMLTemplateElement?(s=e,c=e.content.firstElementChild,c?.setAttribute(o,n)):(c=e,s=document.createElement("template"),s.content.appendChild(e.cloneNode(true)),s.setAttribute(o,n),e.replaceWith(s)),!c)return console.warn(`[entropy] Empty template for key "${n}"`),[];let f=n.slice(0,-2),l=[];for(let a in r){if(Number.isNaN(+a))continue;let u=c.cloneNode(true);u instanceof Element&&(H(t,a,f,n,u),s.before(u),T(t,u),l.push(u));}return l}function H(t,e,n,r,o){let i=E(e,n);for(let s of t.directives.keys()){let c=t.prefix+s;z(o,c,i,r),o.querySelectorAll(`[${c}]`).forEach(f=>{z(f,c,i,r);});}}function z(t,e,n,r){let o=t.getAttribute(e);o?.startsWith(r)&&t.setAttribute(e,n+o.slice(r.length));}function ee(t,e){t.batchQueue=[];try{e();}finally{let n=t.batchQueue??[];t.batchQueue=null;for(let r of n)r();}}function C(t){Array.from((t??document).querySelectorAll("template[name]")).forEach(n=>xe(n));}function xe(t){let e=t.getAttribute("name")?.toLowerCase();if(!e||customElements.get(e))return;let n=class extends HTMLElement{constructor(){super();let r=this.attachShadow({mode:"open"});Array.from(document.getElementsByTagName("style")).forEach(o=>{r.appendChild(o.cloneNode(true));}),Array.from(document.querySelectorAll('link[rel="stylesheet"]')).forEach(o=>r.appendChild(o.cloneNode(true))),Array.from(t.content.childNodes).forEach(o=>{r.appendChild(o.cloneNode(true));});}};customElements.define(e,n);}async function te(t){try{let e=await fetch(t).then(r=>{if(!r.ok)throw new Error(`HTTP ${r.status}`);return r.text()}),n=document.createElement("div");n.innerHTML=e,C(n);}catch(e){console.error(`[entropy] Failed to load template file "${t}":`,e);}}function ne(t,...e){return t.reduce((n,r,o)=>n+(e[o-1]??"")+r)}function re(t){let e=document.createElement("div");return e.innerHTML=t,e}var b=class{constructor(){this.readyStateHandler=null;this.computed=D;this.ctx=F(),J(this.ctx);}init(){return this.ctx.data||(this.ctx.data=w(this.ctx,{},"")),C(),X(this.ctx),this.readyStateHandler||(this.readyStateHandler=()=>{document.readyState==="interactive"&&C();},document.addEventListener("readystatechange",this.readyStateHandler)),this.ctx.data}watch(e,n){$(this.ctx,e,n);}unwatch(e,n){I(this.ctx,e,n);}directive(e,n,r=false){G(this.ctx,e,n,r);}prefix(e="en"){this.ctx.prefix=e.endsWith("-")?e:e+"-";}batch(e){ee(this.ctx,e);}async load(e){let n=Array.isArray(e)?e:[e];await Promise.all(n.map(r=>te(r)));}register(e,...n){Array.isArray(e)&&(e=ne(e,...n)),typeof e=="string"&&(e=re(e)),C(e);}destroy(){this.ctx.destroyed=true,this.readyStateHandler&&(document.removeEventListener("readystatechange",this.readyStateHandler),this.readyStateHandler=null),this.ctx.watchers.clear(),this.ctx.deps.map.clear(),this.ctx.deps.versions.clear(),this.ctx.elementCache.clear(),this.ctx.observer?.disconnect(),this.ctx.observer=null,this.ctx.data=null;}};function we(){return new b}var Ce=new b,nt=Ce;exports.EntropyInstance=b;exports.computed=D;exports.createInstance=we;exports.default=nt;Object.defineProperty(exports,'__esModule',{value:true});return exports;})({});//# sourceMappingURL=entropy.min.js.map
|
|
2
|
+
//# sourceMappingURL=entropy.min.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/context.ts","../src/symbols.ts","../src/utils.ts","../src/computed.ts","../src/watchers.ts","../src/dom/queries.ts","../src/directives/builtins.ts","../src/directives/index.ts","../src/core.ts","../src/dom/components.ts","../src/instance.ts","../src/index.ts"],"names":["createContext","enPrefix","getKey","prop","prefix","getParam","el","attrName","isParametric","value","isPrefixedObject","clone","target","k","v","result","key","IS_COMPUTED","computed","fn","clearDepsForKey","ctx","depKey","list","filtered","d","registerTrackedDeps","computedFn","parent","dependent","dep","setDependents","getDependentsOf","changedKey","matched","seen","removeDependentsFor","deletedKey","bumpVersion","isCurrentVersion","version","watch","watcher","unwatch","targets","w","callWatchers","changedValue","getValue","watchedKey","watchers","cb","parentValue","parts","i","markDirective","isDelete","removeElement","modelListeners","modelDirective","strVal","isCheckbox","isRadio","isNumber","isSelect","eventName","handler","incoming","createConditionalDirectives","ifOrIfNotFn","elMark","parentMark","markEntry","createModelEntry","registerBuiltins","registerDirective","name","bootstrapDirectives","conditionals","type","ifOrIfNot","setupObserver","queryAll","root","query","cached","reactive","obj","isObject","isFunction","proxied","makeHandler","p","childPrefix","receiver","proxyComputed","reactiveValue","success","scheduleUpdate","update","updateComputed","descriptor","deps","syncConfig","runComputed","callDirectives","err","searchRoot","skipUpdateArrayElements","isParentArray","updateArrayItemElement","sortArrayItemElements","callDirectivesForArray","callDirectivesForObject","callDirectivesForLeaf","placeholderKey","elsArrays","plc","els","initializeArrayElements","attrSuffix","skipConditionals","skipMark","entry","param","isShow","isTemplate","attrType","attrMark","child","syncNode","temp","mark","isSyncRoot","syncDirectives","syncClone","attrFull","idx","item","array","arrayItems","itemReplaced","existingEl","cl","cloneFromPlaceholder","initializeClone","template","placeholder","c","templateKey","items","prev","isSorted","lastIdx","curr","b","am","bm","ai","bi","elements","rewriteKey","current","batch","queue","task","registerTemplates","rootElement","registerComponent","ctor","shadow","style","link","loadTemplateFile","file","html","wrapper","stitchTagTemplate","strings","values","acc","s","wrapInDiv","EntropyInstance","files","f","args","createInstance","en","src_default"],"mappings":"6CAmDO,SAASA,CAAAA,EAAgC,CAC9C,OAAO,CACL,KAAM,IAAA,CACN,MAAA,CAAQ,KAAA,CACR,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AAM,CACxB,IAAA,CAAK,GAAA,CAAI,IAAA,CAAK,IAAI,KAAA,EAAM,CACxB,IAAA,CAAK,GAAA,CAAI,IAAA,CAAK,QAAA,CAAS,OAAM,CAC7B,IAAA,CAAK,GAAA,CAAI,YAAA,CAAa,KAAA,EAAM,CAC5B,KAAK,GAAA,CAAI,QAAA,EAAU,UAAA,EAAW,CAC9B,IAAA,CAAK,GAAA,CAAI,SAAW,IAAA,CACpB,IAAA,CAAK,GAAA,CAAI,IAAA,CAAO,KAClB,CACF,EAQO,SAASwG,EAAAA,EAAkC,CAChD,OAAO,IAAIJ,CACb,CChMA,IAAMK,EAAAA,CAAK,IAAIL,CAAAA,CACRM,EAAAA,CAAQD","file":"entropy.min.js","sourcesContent":["import type { Watcher, DirectiveEntry, ComputedList } from './types';\n\n// ─── Sub-state shapes ─────────────────────────────────────────────────────────\n\nexport interface DepsState {\n /** True while a computed function is being evaluated for dep-tracking */\n isEvaluating: boolean;\n /** Keys accessed during the current dep-tracking evaluation */\n set: Set<string>;\n /** Map from dependency key → list of computed values that depend on it */\n map: Map<string, ComputedList>;\n /**\n * Monotonically increasing version number per computed key.\n * Used to discard stale async computed results.\n */\n versions: Map<string, number>;\n}\n\n// ─── Main context ─────────────────────────────────────────────────────────────\n\nexport interface EntropyContext {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data: any | null;\n prefix: string;\n watchers: Map<string, Watcher[]>;\n directives: Map<string, DirectiveEntry>;\n deps: DepsState;\n /**\n * Tracks functions that are *results* of computed calls (not computed\n * definitions). These must not be invoked again by the proxy get-trap.\n */\n computedResultFns: WeakSet<Function>;\n /**\n * When non-null, DOM updates are queued here instead of applied\n * immediately. Call `flushBatch` to apply them.\n */\n batchQueue: Array<() => void> | null;\n /** Set to true after destroy() is called – ignores further updates */\n destroyed: boolean;\n /**\n * Cache of querySelectorAll results keyed by query string.\n * Populated lazily, cleared automatically by the MutationObserver\n * whenever the DOM changes.\n */\n elementCache: Map<string, Element[]>;\n /** Watches the document for DOM mutations to invalidate elementCache. */\n observer: MutationObserver | null;\n}\n\n// ─── Factory ──────────────────────────────────────────────────────────────────\n\nexport function createContext(): EntropyContext {\n return {\n data: null,\n prefix: 'en-',\n watchers: new Map(),\n directives: new Map(),\n deps: {\n isEvaluating: false,\n set: new Set(),\n map: new Map(),\n versions: new Map(),\n },\n computedResultFns: new WeakSet(),\n batchQueue: null,\n destroyed: false,\n elementCache: new Map(),\n observer: null,\n };\n}\n","/** Stores the reactive key-path prefix on reactive objects and functions */\nexport const enPrefix = Symbol('@en/prefix');\n\n/**\n * Set on functions returned as the *result* of a computed call.\n * Prevents the proxy get-trap from calling them a second time.\n * Replaces the original DONT_CALL symbol hack – kept in a WeakSet on the\n * context so there is no property mutation on arbitrary user functions.\n */\nexport const COMPUTED_RESULT_TAG = Symbol('@en/computed-result');\n","import { enPrefix } from './symbols';\nimport type { Prefixed } from './types';\n\n// ─── Key helpers ──────────────────────────────────────────────────────────────\n\nexport function getKey(prop: string, prefix: string): string {\n return prefix === '' ? prop : `${prefix}.${prop}`;\n}\n\nexport function getParam(\n el: Element,\n attrName: string,\n isParametric: boolean,\n): string | undefined {\n if (!isParametric) return undefined;\n const value = el.getAttribute(attrName);\n if (!value) return undefined;\n return value.slice(value.indexOf(':') + 1);\n}\n\n// ─── Type guards ──────────────────────────────────────────────────────────────\n\nexport function isPrefixedObject(value: unknown): value is Prefixed<object> {\n return typeof value === 'object' && value !== null && enPrefix in value;\n}\n\n// ─── Deep clone ───────────────────────────────────────────────────────────────\n\n/**\n * Deep clones a value.\n * Handles: primitives, Date, RegExp, Map, Set, Arrays, plain objects.\n * Unknown exotic types fall back to a plain-object shallow copy.\n */\nexport function clone<T>(target: T): T {\n if (target === null || typeof target !== 'object') return target;\n\n if (target instanceof Date) {\n return new Date(target.getTime()) as unknown as T;\n }\n if (target instanceof RegExp) {\n return new RegExp(target.source, target.flags) as unknown as T;\n }\n if (target instanceof Map) {\n return new Map(\n [...target].map(([k, v]) => [clone(k), clone(v)]),\n ) as unknown as T;\n }\n if (target instanceof Set) {\n return new Set([...target].map(v => clone(v))) as unknown as T;\n }\n if (Array.isArray(target)) {\n return target.map(v => clone(v)) as unknown as T;\n }\n\n const result: Record<string, unknown> = Object.create(\n Object.getPrototypeOf(target),\n );\n for (const key of Object.keys(target as object)) {\n result[key] = clone((target as Record<string, unknown>)[key]);\n }\n return result as T;\n}\n","import type { EntropyContext } from './context';\nimport type { Prefixed, ComputedDep } from './types';\n\n// ─── Public computed() wrapper ────────────────────────────────────────────────\n\nconst IS_COMPUTED = Symbol('@en/computed');\n\n/**\n * Marks a function as a computed value so entropy knows to call it\n * reactively instead of treating it as a plain function reference.\n *\n * @example\n * ```ts\n * const data = en.init();\n * data.fullName = en.computed(() => `${data.firstName} ${data.lastName}`);\n * ```\n */\nexport function computed<T extends (...args: unknown[]) => unknown>(fn: T): T {\n Object.defineProperty(fn, IS_COMPUTED, {\n value: true,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n return fn;\n}\n\nexport function isUserComputed(fn: unknown): fn is Function {\n return typeof fn === 'function' && IS_COMPUTED in fn;\n}\n\n// ─── Dep graph helpers ────────────────────────────────────────────────────────\n\n/**\n * Removes all dep-graph entries whose output key matches `key`.\n * Called before re-registering deps so the graph never accumulates stale edges.\n */\nexport function clearDepsForKey(ctx: EntropyContext, key: string): void {\n for (const [depKey, list] of ctx.deps.map) {\n const filtered = list.filter(d => d.key !== key);\n if (filtered.length === 0) {\n ctx.deps.map.delete(depKey);\n } else {\n ctx.deps.map.set(depKey, filtered);\n }\n }\n}\n\n/**\n * Reads `ctx.deps.set` (populated during a tracked evaluation) and writes\n * edges into `ctx.deps.map` for each accessed key.\n */\nexport function registerTrackedDeps(\n ctx: EntropyContext,\n key: string,\n computedFn: Prefixed<Function>,\n parent: Prefixed<object>,\n prop: string,\n): void {\n const dependent: ComputedDep = { key, computed: computedFn, parent, prop };\n for (const dep of ctx.deps.set) {\n const list = ctx.deps.map.get(dep) ?? [];\n list.push(dependent);\n ctx.deps.map.set(dep, list);\n }\n}\n\n// ─── Dependency tracking ──────────────────────────────────────────────────────\n\n/**\n * Evaluates `value` to discover which reactive keys it reads, then stores\n * those dependencies in `ctx.deps.map` so the computed can be re-evaluated\n * when any dependency changes.\n *\n * Used on *initial assignment* only. Re-evaluations go through `runComputed`\n * in core.ts which tracks deps inline during the actual execution.\n */\nexport function setDependents(\n ctx: EntropyContext,\n value: Prefixed<Function>,\n key: string,\n parent: Prefixed<object>,\n prop: string,\n): void {\n clearDepsForKey(ctx, key);\n\n ctx.deps.isEvaluating = true;\n ctx.deps.set.clear();\n try {\n value();\n } catch {\n // Errors during dep-capture are intentionally swallowed; the computed\n // may reference data not yet initialised.\n } finally {\n ctx.deps.isEvaluating = false;\n }\n\n registerTrackedDeps(ctx, key, value, parent, prop);\n ctx.deps.set.clear();\n}\n\n// ─── Computed update propagation ──────────────────────────────────────────────\n\n/**\n * Returns all ComputedDeps that transitively depend on `changedKey`,\n * deduplicating by the computed function reference.\n */\nexport function getDependentsOf(\n ctx: EntropyContext,\n changedKey: string,\n): ComputedDep[] {\n const matched: ComputedDep[] = [...ctx.deps.map.entries()]\n .filter(\n ([k]) =>\n k === changedKey ||\n k.startsWith(changedKey + '.') ||\n changedKey.startsWith(k + '.'),\n )\n .flatMap(([, list]) => list);\n\n // Deduplicate by computed function reference\n const seen = new Set<Function>();\n return matched.filter(dep => {\n if (seen.has(dep.computed)) return false;\n seen.add(dep.computed);\n return true;\n });\n}\n\n/**\n * Removes all dependency entries for a given key (called on deleteProperty).\n */\nexport function removeDependentsFor(\n ctx: EntropyContext,\n deletedKey: string,\n): void {\n ctx.deps.map.delete(deletedKey);\n for (const [k, list] of ctx.deps.map) {\n const filtered = list.filter(d => d.key !== deletedKey);\n if (filtered.length === 0) {\n ctx.deps.map.delete(k);\n } else {\n ctx.deps.map.set(k, filtered);\n }\n }\n}\n\n// ─── Async version tracking ───────────────────────────────────────────────────\n\nexport function bumpVersion(ctx: EntropyContext, key: string): number {\n const v = (ctx.deps.versions.get(key) ?? 0) + 1;\n ctx.deps.versions.set(key, v);\n return v;\n}\n\nexport function isCurrentVersion(\n ctx: EntropyContext,\n key: string,\n version: number,\n): boolean {\n return ctx.deps.versions.get(key) === version;\n}\n","import type { EntropyContext } from './context';\nimport type { Watcher } from './types';\n\n/**\n * Registers a watcher for `key`. The watcher is called with the new value\n * whenever `key` or any child key changes.\n */\nexport function watch(\n ctx: EntropyContext,\n key: string,\n watcher: Watcher,\n): void {\n const list = ctx.watchers.get(key) ?? [];\n list.push(watcher);\n // Always set to handle the case where the list was freshly created\n ctx.watchers.set(key, list);\n}\n\n/**\n * Removes watchers. All combinations are supported:\n * - `unwatch()` – clears everything\n * - `unwatch(key)` – clears all watchers for a key\n * - `unwatch(undefined, fn)` – removes one fn from all keys\n * - `unwatch(key, fn)` – removes one fn from a specific key\n */\nexport function unwatch(\n ctx: EntropyContext,\n key?: string,\n watcher?: Watcher,\n): void {\n if (!key && !watcher) {\n ctx.watchers.clear();\n return;\n }\n\n if (key && !watcher) {\n ctx.watchers.delete(key);\n return;\n }\n\n const targets: [string, Watcher[]][] = key\n ? [[key, ctx.watchers.get(key) ?? []]]\n : [...ctx.watchers.entries()];\n\n for (const [k, list] of targets) {\n const filtered = list.filter(w => w !== watcher);\n if (filtered.length === 0) {\n ctx.watchers.delete(k);\n } else {\n ctx.watchers.set(k, filtered);\n }\n }\n}\n\n/**\n * Invokes all watchers whose key matches or is an ancestor of `changedKey`.\n */\nexport function callWatchers(\n ctx: EntropyContext,\n changedKey: string,\n changedValue: unknown,\n getValue: (k: string) => unknown,\n): void {\n for (const [watchedKey, watchers] of ctx.watchers) {\n if (changedKey === watchedKey) {\n watchers.forEach(cb => cb(changedValue));\n } else if (changedKey.startsWith(watchedKey + '.')) {\n // A child changed – call the watcher with the whole sub-tree value\n const parentValue = getValue(watchedKey);\n watchers.forEach(cb => cb(parentValue));\n }\n }\n}\n","import type { EntropyContext } from '../context';\nimport type { Prefixed } from '../types';\n\nexport type GetValueResult = {\n value: unknown;\n parent: Prefixed<object> | null;\n prop: string;\n};\n\n/**\n * Resolves a period-separated key against the reactive data tree.\n * Returns the value, its immediate parent object, and the property name.\n *\n * @example\n * // data = { user: { name: 'Alice' } }\n * getValue(ctx, 'user.name') // → { value: 'Alice', parent: data.user, prop: 'name' }\n */\nexport function getValue(ctx: EntropyContext, key: string): GetValueResult {\n let parent = ctx.data as Prefixed<object> | null;\n let value: unknown = undefined;\n let prop = '';\n\n if (parent === null) {\n return { parent, value, prop };\n }\n\n const parts = key.split('.');\n for (let i = 0; i < parts.length; i++) {\n prop = parts[i]!;\n value = Reflect.get(parent, prop);\n\n if (i < parts.length - 1) {\n if (typeof value !== 'object' || value === null) {\n // Path doesn't exist – return what we have\n return { parent, value: undefined, prop };\n }\n parent = value as Prefixed<object>;\n }\n }\n\n return { parent, value, prop };\n}\n","import type { DirectiveEntry, DirectiveParams } from '../types';\nimport type { EntropyContext } from '../context';\nimport { getValue } from '../dom/queries';\n\n// ─── mark ─────────────────────────────────────────────────────────────────────\n\nfunction markDirective({ el, value, isDelete }: DirectiveParams): void {\n if (isDelete) {\n removeElement(el);\n return;\n }\n\n if (!(el instanceof HTMLElement)) return;\n\n if (typeof value === 'object' && value !== null) {\n value = JSON.stringify(value);\n }\n\n el.textContent = typeof value === 'string' ? value : String(value);\n}\n\n// ─── model ────────────────────────────────────────────────────────────────────\n\n/**\n * Two-way binding directive. Syncs a reactive key with an input element:\n *\n * - DOM → data: listens to `input` (text, number, textarea), `change`\n * (select, checkbox, radio), keeping data in sync as the user types.\n * - data → DOM: sets the element value / checked state when the reactive\n * key changes, exactly like `en-mark` does for textContent.\n *\n * Supported elements: input[type=text|number|email|password|range|date|…],\n * input[type=checkbox], input[type=radio], textarea, select.\n *\n * Usage: `<input en-model=\"key\" />`\n */\n\n// WeakSet so listeners are GC-able with their elements\nconst modelListeners = new WeakMap<Element, () => void>();\n\nfunction modelDirective(ctx: EntropyContext): (params: DirectiveParams) => void {\n return ({ el, value, key }: DirectiveParams) => {\n if (!(el instanceof HTMLInputElement ||\n el instanceof HTMLTextAreaElement ||\n el instanceof HTMLSelectElement)) return;\n\n // ── data → DOM ──────────────────────────────────────────────────────────\n if (el instanceof HTMLInputElement && el.type === 'checkbox') {\n el.checked = !!value;\n } else if (el instanceof HTMLInputElement && el.type === 'radio') {\n el.checked = el.value === String(value);\n } else {\n // text, number, email, password, range, date, textarea, select\n const strVal = value === null || value === undefined ? '' : String(value);\n if (el.value !== strVal) el.value = strVal;\n }\n\n // ── DOM → data (attach listener once per element) ───────────────────────\n if (modelListeners.has(el)) return;\n\n const isCheckbox = el instanceof HTMLInputElement && el.type === 'checkbox';\n const isRadio = el instanceof HTMLInputElement && el.type === 'radio';\n const isNumber = el instanceof HTMLInputElement && el.type === 'number';\n const isSelect = el instanceof HTMLSelectElement;\n const eventName = (isCheckbox || isRadio || isSelect) ? 'change' : 'input';\n\n const handler = () => {\n const { parent, prop } = getValue(ctx, key);\n if (!parent) return;\n\n let incoming: unknown;\n if (isCheckbox) incoming = (el as HTMLInputElement).checked;\n else if (isNumber) incoming = (el as HTMLInputElement).valueAsNumber;\n else incoming = (el as HTMLElement & { value: string }).value;\n\n Reflect.set(parent, prop, incoming);\n };\n\n el.addEventListener(eventName, handler);\n modelListeners.set(el, handler);\n };\n}\n\n// ─── if / ifnot ──────────────────────────────────────────────────────────────\n\n/**\n * Factory: returns directive entries for `if` and `ifnot` that delegate to\n * `ifOrIfNotFn`. The function is injected to avoid a circular import between\n * this module and core.ts.\n */\nexport function createConditionalDirectives(\n ifOrIfNotFn: (\n el: Element,\n value: unknown,\n key: string,\n type: 'if' | 'ifnot',\n ) => void,\n): { if: DirectiveEntry; ifnot: DirectiveEntry } {\n return {\n if: {\n cb: ({ el, value, key }: DirectiveParams) =>\n ifOrIfNotFn(el, value, key, 'if'),\n },\n ifnot: {\n cb: ({ el, value, key }: DirectiveParams) =>\n ifOrIfNotFn(el, value, key, 'ifnot'),\n },\n };\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────────────\n\nfunction removeElement(el: Element): void {\n const parent = el.parentElement;\n\n if (!(el instanceof HTMLElement) || !parent) {\n return el.remove();\n }\n\n const elMark = el.getAttribute('data-en-mark') ?? el.getAttribute('en-mark');\n const parentMark =\n parent.getAttribute('data-en-mark') ?? parent.getAttribute('en-mark');\n\n if (elMark && elMark === parentMark) {\n return parent.remove();\n }\n\n el.remove();\n}\n\n// ─── Exports ──────────────────────────────────────────────────────────────────\n\nexport const markEntry: DirectiveEntry = { cb: markDirective };\n\nexport function createModelEntry(ctx: EntropyContext): DirectiveEntry {\n return { cb: modelDirective(ctx) };\n}\n","import type { EntropyContext } from '../context';\nimport type { Directive, DirectiveEntry } from '../types';\nimport { markEntry, createModelEntry } from './builtins';\n\n/**\n * Seeds the directive map with built-in directives.\n * Conditional directives (if / ifnot) are registered later from core.ts\n * once the `ifOrIfNot` implementation is available.\n */\nexport function registerBuiltins(ctx: EntropyContext): void {\n ctx.directives.set('mark', markEntry);\n ctx.directives.set('model', createModelEntry(ctx));\n}\n\n/**\n * Registers a custom directive. No-ops if the name is already taken to\n * prevent accidental overrides during hot-reload scenarios.\n */\nexport function registerDirective(\n ctx: EntropyContext,\n name: string,\n cb: Directive,\n isParametric = false,\n): void {\n if (ctx.directives.has(name)) return;\n ctx.directives.set(name, { cb, isParametric });\n}\n\nexport function getDirective(\n ctx: EntropyContext,\n name: string,\n): DirectiveEntry | undefined {\n return ctx.directives.get(name);\n}\n\nexport function allDirectives(\n ctx: EntropyContext,\n): IterableIterator<[string, DirectiveEntry]> {\n return ctx.directives.entries();\n}\n","/**\n * core.ts – Reactive engine\n *\n * Contains the tightly-coupled pieces that cannot be cleanly separated\n * without introducing circular imports:\n *\n * • reactive() – wraps a value in a Proxy\n * • Proxy handler – traps get / set / deleteProperty / defineProperty\n * • update() – propagates a change to watchers + directives\n * • callDirectives() – split into focused helpers (array / object / primitive)\n * • DOM array helpers – updateArrayItemElement, sortArrayItemElements, …\n * • syncNode / Conditional (if/ifnot) handlers\n */\n\nimport { enPrefix } from './symbols';\nimport { getKey, getParam, isPrefixedObject, clone } from './utils';\nimport type { EntropyContext } from './context';\nimport type { Prefixed, SyncConfig, DirectiveEntry } from './types';\nimport {\n setDependents,\n getDependentsOf,\n removeDependentsFor,\n bumpVersion,\n isCurrentVersion,\n clearDepsForKey,\n registerTrackedDeps,\n} from './computed';\nimport { callWatchers } from './watchers';\nimport { getValue } from './dom/queries';\nimport { registerBuiltins } from './directives/index';\nimport { createConditionalDirectives } from './directives/builtins';\n\n// ─── Bootstrap ────────────────────────────────────────────────────────────────\n\n/**\n * Seeds built-in directives on the context.\n * Must be called once after `createContext()` and before `init()`.\n */\nexport function bootstrapDirectives(ctx: EntropyContext): void {\n registerBuiltins(ctx);\n\n const conditionals = createConditionalDirectives(\n (el, value, key, type) => ifOrIfNot(ctx, el, value, key, type),\n );\n ctx.directives.set('if', conditionals.if);\n ctx.directives.set('ifnot', conditionals.ifnot);\n}\n\n// ─── Element cache ────────────────────────────────────────────────────────────\n\n/**\n * Attaches a MutationObserver that clears ctx.elementCache whenever the DOM\n * changes. Without this, cached querySelectorAll results would become stale\n * after nodes are inserted or removed (e.g. en-if, array updates).\n *\n * Safe to call multiple times – a second call is a no-op.\n */\nexport function setupObserver(ctx: EntropyContext): void {\n if (ctx.observer || typeof MutationObserver === 'undefined') return;\n ctx.observer = new MutationObserver(() => ctx.elementCache.clear());\n ctx.observer.observe(document, { childList: true, subtree: true });\n}\n\n/**\n * Runs querySelectorAll with a per-context result cache.\n * Results are only cached when the search root is the whole document —\n * scoped searches (e.g. inside a single array item) are never cached because\n * their root element may itself be transient.\n */\nfunction queryAll(\n ctx: EntropyContext,\n root: Document | Element,\n query: string,\n): Element[] {\n if (!(root instanceof Document)) {\n return Array.from(root.querySelectorAll(query));\n }\n const cached = ctx.elementCache.get(query);\n if (cached) return cached;\n const result = Array.from(root.querySelectorAll(query));\n ctx.elementCache.set(query, result);\n return result;\n}\n\n// ─── reactive() ───────────────────────────────────────────────────────────────\n\n/**\n * Makes a value reactive by wrapping objects/arrays in a Proxy and attaching\n * the `enPrefix` key-path marker. Functions become computed values and have\n * their dependencies tracked.\n */\nexport function reactive<T>(\n ctx: EntropyContext,\n obj: T,\n prefix: string,\n parent?: Prefixed<object>,\n prop?: string,\n): T | Prefixed<T> {\n if (obj === null) return obj;\n\n const isObject = typeof obj === 'object';\n const isFunction = typeof obj === 'function';\n\n if (isFunction && parent) {\n obj = (obj as unknown as Function).bind(parent) as unknown as T;\n }\n\n if (isObject || isFunction) {\n Object.defineProperty(obj, enPrefix, {\n value: prefix,\n enumerable: false,\n writable: true,\n configurable: true,\n });\n }\n\n // Functions are computed values – track their deps and return early\n // (functions are NOT further wrapped in a Proxy)\n if (isFunction && prop && parent) {\n setDependents(ctx, obj as unknown as Prefixed<Function>, prefix, parent, prop);\n return obj;\n }\n\n if (!isObject) return obj;\n\n type K = keyof T;\n const proxied = new Proxy(\n obj as unknown as Prefixed<object>,\n makeHandler(ctx),\n ) as Prefixed<T>;\n\n for (const p of Object.keys(obj as object)) {\n const childPrefix = getKey(p, prefix);\n const value = (obj as Record<string, unknown>)[p];\n (obj as Record<string, unknown>)[p] = reactive(\n ctx,\n value,\n childPrefix,\n proxied,\n p,\n );\n }\n\n return proxied;\n}\n\n// ─── Proxy handler factory ────────────────────────────────────────────────────\n\nfunction makeHandler(ctx: EntropyContext): ProxyHandler<Prefixed<object>> {\n return {\n // ── get ───────────────────────────────────────────────────────────────────\n get(\n target: Prefixed<object>,\n prop: string | symbol,\n receiver: Prefixed<object>,\n ): unknown {\n // Track dependencies during computed evaluation\n if (\n ctx.deps.isEvaluating &&\n typeof prop === 'string' &&\n Object.getOwnPropertyDescriptor(target, prop)?.enumerable\n ) {\n ctx.deps.set.add(getKey(prop, target[enPrefix]));\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n // Call computed functions, but not if they are a computed *result*\n if (\n typeof value === 'function' &&\n enPrefix in value &&\n !ctx.computedResultFns.has(value)\n ) {\n const result = value();\n if (result instanceof Promise) {\n return result.then(v => proxyComputed(ctx, v));\n }\n return proxyComputed(ctx, result);\n }\n\n return value;\n },\n\n // ── set ───────────────────────────────────────────────────────────────────\n set(\n target: Prefixed<object>,\n prop: string | symbol,\n value: unknown,\n receiver: Prefixed<object>,\n ): boolean {\n if (typeof prop === 'symbol') {\n return Reflect.set(target, prop, value, receiver);\n }\n\n const key = getKey(prop, target[enPrefix]);\n const reactiveValue = reactive(ctx, value, key, receiver, prop);\n const success = Reflect.set(target, prop, reactiveValue, receiver);\n\n scheduleUpdate(ctx, () =>\n update(ctx, reactiveValue, key, false, receiver, prop),\n );\n scheduleUpdate(ctx, () => updateComputed(ctx, key));\n\n return success;\n },\n\n // ── deleteProperty ────────────────────────────────────────────────────────\n deleteProperty(target: Prefixed<object>, prop: string | symbol): boolean {\n if (typeof prop === 'symbol') {\n return Reflect.deleteProperty(target, prop);\n }\n\n const key = getKey(prop, target[enPrefix]);\n const success = Reflect.deleteProperty(target, prop);\n\n update(ctx, undefined, key, true, target, prop);\n removeDependentsFor(ctx, key);\n\n return success;\n },\n\n // ── defineProperty ────────────────────────────────────────────────────────\n defineProperty(\n target: Prefixed<object>,\n prop: string | symbol,\n descriptor: PropertyDescriptor,\n ): boolean {\n // Allow array index re-keying (e.g. when an array element is moved)\n if (\n prop === enPrefix &&\n enPrefix in target &&\n typeof descriptor.value === 'string' &&\n /\\.\\d+$/.test(descriptor.value)\n ) {\n return Reflect.set(target, prop, descriptor.value);\n }\n return Reflect.defineProperty(target, prop, descriptor);\n },\n };\n}\n\n// ─── Batch scheduling ─────────────────────────────────────────────────────────\n\nfunction scheduleUpdate(ctx: EntropyContext, fn: () => void): void {\n if (ctx.batchQueue !== null) {\n ctx.batchQueue.push(fn);\n } else {\n fn();\n }\n}\n\n// ─── Computed propagation ─────────────────────────────────────────────────────\n\nfunction updateComputed(ctx: EntropyContext, changedKey: string): void {\n const deps = getDependentsOf(ctx, changedKey);\n for (const dep of deps) {\n update(ctx, dep.computed, dep.key, false, dep.parent, dep.prop);\n }\n}\n\n// ─── Core update ─────────────────────────────────────────────────────────────\n\n/**\n * The central propagation function. Called whenever a reactive value changes.\n * Resolves computed functions, handles async Promises, then notifies watchers\n * and directives.\n */\nexport function update(\n ctx: EntropyContext,\n value: unknown,\n key: string,\n isDelete: boolean,\n parent: Prefixed<object>,\n prop: string,\n syncConfig?: SyncConfig,\n): void {\n if (ctx.destroyed) return;\n\n // If value is a computed function, run it\n if (\n typeof value === 'function' &&\n !ctx.computedResultFns.has(value as Function)\n ) {\n value = runComputed(ctx, value as Function, key, parent, prop);\n if (value === undefined) return; // async – will re-enter when resolved\n }\n\n // Async value: re-enter when the Promise resolves\n if (value instanceof Promise) {\n const version = bumpVersion(ctx, key);\n (value as Promise<unknown>).then((v: unknown) => {\n if (!isCurrentVersion(ctx, key, version)) return;\n update(ctx, v, key, false, parent, prop, syncConfig);\n });\n return;\n }\n\n if (!syncConfig) {\n callWatchers(ctx, key, value, (k) => getValue(ctx, k).value);\n }\n\n callDirectives(ctx, value, key, isDelete, parent, prop, undefined, undefined, syncConfig);\n}\n\n// ─── Computed helpers ─────────────────────────────────────────────────────────\n\nfunction runComputed(\n ctx: EntropyContext,\n computedFn: Function,\n key: string,\n parent: Prefixed<object>,\n prop: string,\n): unknown {\n const version = bumpVersion(ctx, key);\n const result = computedFn();\n\n if (result instanceof Promise) {\n result\n .then(v => {\n if (!isCurrentVersion(ctx, key, version)) return;\n const proxied = proxyComputed(ctx, v, key, parent, prop);\n update(ctx, proxied, key, false, parent, prop);\n })\n .catch(err =>\n console.error(`[entropy] Async computed error at \"${key}\":`, err),\n );\n return undefined;\n }\n\n return proxyComputed(ctx, result, key, parent, prop);\n}\n\nfunction proxyComputed(\n ctx: EntropyContext,\n value: unknown,\n key?: string,\n parent?: Prefixed<object>,\n prop?: string,\n): unknown {\n if (typeof value === 'function') {\n // Tag function as a computed result so the get-trap won't call it again\n ctx.computedResultFns.add(value as Function);\n return value;\n }\n\n if (key === undefined || parent === undefined || prop === undefined) {\n return clone(value);\n }\n\n return reactive(ctx, clone(value), key, parent, prop);\n}\n\n// ─── callDirectives (split into focused sub-functions) ────────────────────────\n\nfunction callDirectives(\n ctx: EntropyContext,\n value: unknown,\n key: string,\n isDelete: boolean,\n parent: Prefixed<object>,\n prop: string,\n searchRoot?: Element | Document,\n skipUpdateArrayElements?: boolean,\n syncConfig?: SyncConfig,\n): void {\n const isParentArray = Array.isArray(parent);\n\n // Handle array item updates / length changes\n if (isParentArray && /^\\d+$/.test(prop) && !skipUpdateArrayElements && syncConfig?.skipMark !== true) {\n updateArrayItemElement(ctx, key, prop, value, parent as Prefixed<unknown[]>);\n } else if (isParentArray && prop === 'length') {\n sortArrayItemElements(ctx, parent as Prefixed<unknown[]>);\n }\n\n // Recurse into reactive objects / arrays\n if (isPrefixedObject(value)) {\n if (Array.isArray(value) && syncConfig?.skipMark !== true) {\n callDirectivesForArray(ctx, value, key, isDelete, parent, prop, searchRoot, syncConfig);\n } else {\n callDirectivesForObject(ctx, value, key, isDelete, parent, prop, searchRoot);\n }\n // Also fire directives bound directly to this key (e.g. en-mark=\"obj\" → JSON).\n // Arrays are handled separately via their placeholder mechanism.\n if (!Array.isArray(value)) {\n callDirectivesForLeaf(ctx, value, key, isDelete, parent, prop, searchRoot, syncConfig);\n }\n return;\n }\n\n // Primitive / non-reactive value – call matching directive callbacks\n callDirectivesForLeaf(ctx, value, key, isDelete, parent, prop, searchRoot, syncConfig);\n}\n\nfunction callDirectivesForArray(\n ctx: EntropyContext,\n value: Prefixed<unknown[]>,\n key: string,\n isDelete: boolean,\n parent: Prefixed<object>,\n prop: string,\n searchRoot?: Element | Document,\n syncConfig?: SyncConfig,\n): void {\n const placeholderKey = `${key}.#`;\n const attrMark = ctx.prefix + 'mark';\n const query = `[${attrMark}=\"${placeholderKey}\"]`;\n\n let target: Document | Element = document;\n if (syncConfig?.el.parentElement) {\n target = syncConfig.el.parentElement;\n }\n\n const elsArrays: Element[][] = [];\n queryAll(ctx, target, query).forEach(plc => {\n const els = initializeArrayElements(ctx, plc, placeholderKey, value);\n elsArrays.push(els);\n });\n\n for (const els of elsArrays) {\n for (const i in value) {\n callDirectives(\n ctx,\n value[i as unknown as number],\n getKey(i, key),\n isDelete,\n value,\n i,\n els[i as unknown as number] ?? undefined,\n true,\n );\n }\n }\n\n // Propagate to directives watching `key.length` (e.g. en-ifnot=\"items.length\")\n callDirectivesForLeaf(\n ctx,\n value.length,\n getKey('length', key),\n isDelete,\n value as unknown as Prefixed<object>,\n 'length',\n searchRoot,\n );\n}\n\nfunction callDirectivesForObject(\n ctx: EntropyContext,\n value: Prefixed<object>,\n key: string,\n isDelete: boolean,\n parent: Prefixed<object>,\n prop: string,\n searchRoot?: Element | Document,\n): void {\n for (const k in value) {\n callDirectives(\n ctx,\n (value as Record<string, unknown>)[k],\n getKey(k, key),\n isDelete,\n value,\n k,\n searchRoot,\n );\n }\n}\n\nfunction callDirectivesForLeaf(\n ctx: EntropyContext,\n value: unknown,\n key: string,\n isDelete: boolean,\n parent: Prefixed<object>,\n prop: string,\n searchRoot?: Element | Document,\n syncConfig?: SyncConfig,\n): void {\n if (syncConfig) {\n const { el, directive: attrSuffix, skipConditionals, skipMark } = syncConfig;\n if (\n (skipMark && attrSuffix === 'mark') ||\n (skipConditionals && (attrSuffix === 'if' || attrSuffix === 'ifnot'))\n ) {\n return;\n }\n const entry = ctx.directives.get(attrSuffix);\n if (!entry) return;\n const { cb, isParametric } = entry;\n const param = getParam(el, ctx.prefix + attrSuffix, !!isParametric);\n cb({ el, value, key, isDelete, parent, prop, param });\n return;\n }\n\n const root = searchRoot ?? document;\n\n for (const [attrSuffix, { cb, isParametric }] of ctx.directives) {\n const attrName = ctx.prefix + attrSuffix;\n const query = isParametric\n ? `[${attrName}^='${key}:']`\n : `[${attrName}='${key}']`;\n\n queryAll(ctx, root, query).forEach(el => {\n const param = getParam(el, attrName, !!isParametric);\n cb({ el, value, key, isDelete, parent, prop, param });\n });\n\n // Also check the search root itself when it is a concrete element\n if (root instanceof Element && root.getAttribute(attrName) === key) {\n const param = getParam(root, attrName, !!isParametric);\n cb({ el: root, value, key, isDelete, parent, prop, param });\n }\n }\n}\n\n// ─── Conditional directives (if / ifnot) ─────────────────────────────────────\n\nfunction ifOrIfNot(\n ctx: EntropyContext,\n el: Element,\n value: unknown,\n key: string,\n type: 'if' | 'ifnot',\n): void {\n const isShow = type === 'if' ? !!value : !value;\n const isTemplate = el instanceof HTMLTemplateElement;\n const attrType = ctx.prefix + type;\n const attrMark = ctx.prefix + 'mark';\n\n if (isShow && isTemplate) {\n const child = el.content.firstElementChild;\n if (!child) return;\n\n child.setAttribute(attrType, key);\n syncNode(ctx, child, true);\n el.replaceWith(child);\n }\n\n if (!isShow && !isTemplate) {\n const temp = document.createElement('template');\n temp.content.appendChild(el.cloneNode(true));\n temp.setAttribute(attrType, key);\n\n const mark = el.getAttribute(attrMark);\n if (mark) temp.setAttribute(attrMark, mark);\n\n el.replaceWith(temp);\n }\n}\n\n// ─── Sync helpers ─────────────────────────────────────────────────────────────\n\n/**\n * Recursively syncs an element tree that is about to be inserted into the DOM\n * (called from `if`/`ifnot` before insertion). Evaluates conditionals on the\n * way down but skips `mark` – actual values are filled in by `syncClone`.\n */\nfunction syncNode(\n ctx: EntropyContext,\n el: Element,\n isSyncRoot: boolean,\n): void {\n Array.from(el.children).forEach(child => syncNode(ctx, child, false));\n syncDirectives(ctx, el, isSyncRoot, false);\n}\n\n/**\n * Recursively syncs a clone that has already been inserted. Skips\n * conditionals (already evaluated during `syncNode`) and processes `mark`.\n */\nfunction syncClone(ctx: EntropyContext, clone: Element): void {\n Array.from(clone.children).forEach(child => syncClone(ctx, child));\n syncDirectives(ctx, clone, false, true);\n}\n\nfunction syncDirectives(\n ctx: EntropyContext,\n el: Element,\n skipConditionals?: boolean,\n skipMark?: boolean,\n): void {\n for (const [name] of ctx.directives) {\n if (skipMark && name === 'mark') continue;\n if (skipConditionals && (name === 'if' || name === 'ifnot')) continue;\n\n const { isParametric } = ctx.directives.get(name)!;\n const attrFull = ctx.prefix + name;\n let key = el.getAttribute(attrFull);\n\n if (isParametric) key = key?.split(':')[0] ?? null;\n if (key?.endsWith('.#')) key = key.slice(0, -2);\n if (key === null) continue;\n\n const { value, parent, prop } = getValue(ctx, key);\n if (!parent) continue;\n\n update(ctx, value, key, false, parent, prop, {\n directive: name,\n el,\n ...(skipConditionals !== undefined ? { skipConditionals } : {}),\n ...(skipMark !== undefined ? { skipMark } : {}),\n });\n }\n}\n\n// ─── Array DOM management ─────────────────────────────────────────────────────\n\nfunction updateArrayItemElement(\n ctx: EntropyContext,\n key: string,\n idx: string,\n item: unknown,\n array: Prefixed<unknown[]>,\n): void {\n const attrMark = ctx.prefix + 'mark';\n const arrayItems = document.querySelectorAll(`[${attrMark}=\"${key}\"]`);\n\n if (arrayItems.length && !isPrefixedObject(item)) {\n // Primitives: innerText update is sufficient, no DOM replacement needed\n return;\n }\n\n const prefix = ((array as unknown as Record<symbol, string>)[enPrefix]) ?? '';\n const placeholderKey = key.replace(/\\d+$/, '#');\n let itemReplaced = false;\n\n // Replace existing DOM items that map to this array index\n Array.from(arrayItems).forEach(existingEl => {\n const cl = cloneFromPlaceholder(ctx, existingEl, placeholderKey, attrMark);\n if (!cl) return;\n\n initializeClone(ctx, idx, prefix, placeholderKey, cl);\n existingEl.replaceWith(cl);\n syncClone(ctx, cl);\n itemReplaced = true;\n });\n\n if (itemReplaced) return;\n\n // No existing item – insert before the template placeholder\n Array.from(document.querySelectorAll(`[${attrMark}=\"${placeholderKey}\"]`)).forEach(template => {\n if (!(template instanceof HTMLTemplateElement)) return;\n const clone = template.content.firstElementChild?.cloneNode(true);\n if (!(clone instanceof Element)) return;\n\n initializeClone(ctx, idx, prefix, placeholderKey, clone);\n template.before(clone);\n syncClone(ctx, clone);\n });\n}\n\nfunction cloneFromPlaceholder(\n ctx: EntropyContext,\n item: Element,\n placeholderKey: string,\n attrMark: string,\n): Element | null {\n let placeholder = item.nextElementSibling;\n while (placeholder) {\n if (placeholder.getAttribute(attrMark) === placeholderKey) break;\n placeholder = placeholder.nextElementSibling;\n }\n\n if (placeholder instanceof HTMLTemplateElement) {\n const c = placeholder.content.firstElementChild?.cloneNode(true);\n return c instanceof Element ? c : null;\n }\n if (placeholder?.getAttribute(attrMark) === placeholderKey) {\n return placeholder.cloneNode(true) as Element;\n }\n return null;\n}\n\nfunction sortArrayItemElements(\n ctx: EntropyContext,\n array: Prefixed<unknown[]>,\n): void {\n const attrMark = ctx.prefix + 'mark';\n const templateKey = getKey('#', ((array as unknown as Record<symbol, string>)[enPrefix]) ?? '');\n Array.from(document.querySelectorAll(`[${attrMark}=\"${templateKey}\"]`)).forEach(template => {\n const items: Element[] = [];\n let prev = template.previousElementSibling;\n let isSorted = true;\n let lastIdx = -1;\n\n while (prev) {\n const curr = prev;\n prev = curr.previousElementSibling;\n\n const k = curr.getAttribute(attrMark);\n if (!k) continue;\n if (k === templateKey) break;\n\n if (k.replace(/\\d+$/, '#') === templateKey) {\n items.push(curr);\n if (isSorted) {\n const idx = Number(k.slice(k.lastIndexOf('.') + 1) ?? -1);\n if (lastIdx !== -1 && lastIdx !== idx + 1) isSorted = false;\n lastIdx = idx;\n }\n }\n }\n\n if (isSorted) return;\n\n const sorted = [...items].sort((a, b) => {\n const am = a.getAttribute(attrMark) ?? '';\n const bm = b.getAttribute(attrMark) ?? '';\n const ai = +(am.split('.').pop() ?? 0);\n const bi = +(bm.split('.').pop() ?? 0);\n return ai - bi;\n });\n\n sorted.forEach(el => template.before(el));\n });\n}\n\nfunction initializeArrayElements(\n ctx: EntropyContext,\n plc: Element,\n placeholderKey: string,\n array: unknown[],\n): Element[] {\n const attrMark = ctx.prefix + 'mark';\n\n // ── 1. Remove previous item elements ────────────────────────────────────\n let prev = plc.previousElementSibling;\n while (prev) {\n const curr = prev;\n prev = curr.previousElementSibling;\n const k = curr.getAttribute(attrMark);\n if (!k) continue;\n if (k !== placeholderKey && k.replace(/\\d+$/, '#') === placeholderKey) {\n curr.remove();\n } else {\n break;\n }\n }\n\n // ── 2. Resolve template and placeholder ──────────────────────────────────\n let template: HTMLTemplateElement;\n let placeholder: Element | null;\n\n if (plc instanceof HTMLTemplateElement) {\n template = plc;\n placeholder = plc.content.firstElementChild;\n placeholder?.setAttribute(attrMark, placeholderKey);\n } else {\n placeholder = plc;\n template = document.createElement('template');\n template.content.appendChild(plc.cloneNode(true));\n template.setAttribute(attrMark, placeholderKey);\n plc.replaceWith(template);\n }\n\n if (!placeholder) {\n console.warn(`[entropy] Empty template for key \"${placeholderKey}\"`);\n return [];\n }\n\n // ── 3. Create one element per array item ─────────────────────────────────\n const prefix = placeholderKey.slice(0, -2); // strip \".#\"\n const elements: Element[] = [];\n\n for (const idx in array) {\n if (Number.isNaN(+idx)) continue;\n\n const clone = placeholder.cloneNode(true);\n if (!(clone instanceof Element)) continue;\n\n initializeClone(ctx, idx, prefix, placeholderKey, clone);\n template.before(clone);\n syncClone(ctx, clone);\n elements.push(clone);\n }\n\n return elements;\n}\n\nfunction initializeClone(\n ctx: EntropyContext,\n idx: string,\n prefix: string,\n placeholderKey: string,\n clone: Element,\n): void {\n const key = getKey(idx, prefix);\n\n for (const attrSuffix of ctx.directives.keys()) {\n const attrName = ctx.prefix + attrSuffix;\n rewriteKey(clone, attrName, key, placeholderKey);\n clone.querySelectorAll(`[${attrName}]`).forEach(child => {\n rewriteKey(child, attrName, key, placeholderKey);\n });\n }\n}\n\nfunction rewriteKey(\n el: Element,\n attrName: string,\n key: string,\n placeholderKey: string,\n): void {\n const current = el.getAttribute(attrName);\n if (current?.startsWith(placeholderKey)) {\n el.setAttribute(attrName, key + current.slice(placeholderKey.length));\n }\n}\n\n// ─── Batch API ────────────────────────────────────────────────────────────────\n\n/**\n * Runs `fn` synchronously while collecting all DOM updates into a queue,\n * then flushes the queue in one pass. Useful when multiple properties are\n * changed at once.\n *\n * @example\n * ```ts\n * en.batch(() => {\n * data.firstName = 'John';\n * data.lastName = 'Doe';\n * });\n * ```\n */\nexport function batch(ctx: EntropyContext, fn: () => void): void {\n ctx.batchQueue = [];\n try {\n fn();\n } finally {\n const queue = ctx.batchQueue ?? [];\n ctx.batchQueue = null;\n for (const task of queue) task();\n }\n}\n","/**\n * Registers named `<template>` elements as custom Web Components using\n * Shadow DOM. Fully independent of the reactive core – no context needed.\n */\n\nexport function registerTemplates(rootElement?: Element | Document): void {\n const root = rootElement ?? document;\n Array.from(root.querySelectorAll<HTMLTemplateElement>('template[name]')).forEach(\n template => registerComponent(template),\n );\n}\n\nexport function registerComponent(template: HTMLTemplateElement): void {\n const name = template.getAttribute('name')?.toLowerCase();\n if (!name || customElements.get(name)) return;\n\n const ctor = class extends HTMLElement {\n constructor() {\n super();\n const shadow = this.attachShadow({ mode: 'open' });\n\n // Inherit top-level stylesheets so components look consistent\n Array.from(document.getElementsByTagName('style')).forEach(style => {\n shadow.appendChild(style.cloneNode(true));\n });\n Array.from(document.querySelectorAll<HTMLLinkElement>('link[rel=\"stylesheet\"]')).forEach(\n link => shadow.appendChild(link.cloneNode(true)),\n );\n\n // Clone template content into shadow root\n Array.from(template.content.childNodes).forEach(child => {\n shadow.appendChild(child.cloneNode(true));\n });\n }\n };\n\n customElements.define(name, ctor);\n}\n\nexport async function loadTemplateFile(file: string): Promise<void> {\n try {\n const html = await fetch(file).then(r => {\n if (!r.ok) throw new Error(`HTTP ${r.status}`);\n return r.text();\n });\n const wrapper = document.createElement('div');\n wrapper.innerHTML = html;\n registerTemplates(wrapper);\n } catch (err) {\n console.error(`[entropy] Failed to load template file \"${file}\":`, err);\n }\n}\n\nexport function stitchTagTemplate(\n strings: string[],\n ...values: unknown[]\n): string {\n return strings.reduce(\n (acc, s, i) => acc + (values[i - 1] ?? '') + s,\n );\n}\n\nexport function wrapInDiv(html: string): HTMLElement {\n const el = document.createElement('div');\n el.innerHTML = html;\n return el;\n}\n","import { createContext } from './context';\nimport type { EntropyContext } from './context';\nimport type { Prefixed } from './types';\nimport type { Directive, Watcher } from './types';\nimport { enPrefix } from './symbols';\nimport { reactive, bootstrapDirectives, setupObserver, update, batch } from './core';\nimport { watch, unwatch } from './watchers';\nimport { registerDirective } from './directives/index';\nimport { computed } from './computed';\nimport {\n registerTemplates,\n loadTemplateFile,\n stitchTagTemplate,\n wrapInDiv,\n} from './dom/components';\nimport { getValue } from './dom/queries';\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\nexport type Meta = Record<string, unknown>; // opaque marker type for the reactive root\n\n// ─── EntropyInstance ───────────────────────────────────────────────────────\n\nexport class EntropyInstance {\n private readonly ctx: EntropyContext;\n private readyStateHandler: (() => void) | null = null;\n\n constructor() {\n this.ctx = createContext();\n bootstrapDirectives(this.ctx);\n }\n\n // ─── init ──────────────────────────────────────────────────────────────────\n\n /**\n * Initialises the reactive data object and begins listening for DOM changes.\n * Returns the reactive data proxy – assign properties directly on it.\n *\n * @example\n * ```ts\n * const data = en.init();\n * data.count = 0;\n * ```\n */\n init(): Record<string, unknown> & Meta {\n if (!this.ctx.data) {\n this.ctx.data = reactive(this.ctx, {}, '') as Prefixed<{}>;\n }\n\n registerTemplates();\n setupObserver(this.ctx);\n\n if (!this.readyStateHandler) {\n this.readyStateHandler = () => {\n if (document.readyState === 'interactive') {\n registerTemplates();\n }\n };\n document.addEventListener('readystatechange', this.readyStateHandler);\n }\n\n return this.ctx.data;\n }\n\n // ─── computed ──────────────────────────────────────────────────────────────\n\n /**\n * Marks a function as a computed value so entropy calls it reactively.\n *\n * @example\n * ```ts\n * data.fullName = en.computed(() => `${data.first} ${data.last}`);\n * ```\n */\n computed = computed;\n\n // ─── watch ─────────────────────────────────────────────────────────────────\n\n /**\n * Registers a watcher for `key`. Called with the new value whenever `key`\n * or any of its children changes.\n *\n * @example\n * ```ts\n * en.watch('user.name', newName => console.log('Name changed:', newName));\n * ```\n */\n watch(key: string, watcher: Watcher): void {\n watch(this.ctx, key, watcher);\n }\n\n /**\n * Removes watchers. See parameter combinations in the source for details.\n */\n unwatch(key?: string, watcher?: Watcher): void {\n unwatch(this.ctx, key, watcher);\n }\n\n // ─── directive ─────────────────────────────────────────────────────────────\n\n /**\n * Registers a custom directive.\n *\n * @example\n * ```ts\n * en.directive('color', ({ el, value }) => {\n * (el as HTMLElement).style.color = String(value);\n * });\n * ```\n */\n directive(name: string, cb: Directive, isParametric = false): void {\n registerDirective(this.ctx, name, cb, isParametric);\n }\n\n // ─── prefix ────────────────────────────────────────────────────────────────\n\n /**\n * Overrides the default attribute prefix (`en-`).\n * Must be called before `init()`.\n *\n * @example\n * ```ts\n * en.prefix('data-en');\n * const data = en.init();\n * // now use data-en-mark=\"...\" in your HTML\n * ```\n */\n prefix(value = 'en'): void {\n this.ctx.prefix = value.endsWith('-') ? value : value + '-';\n }\n\n // ─── batch ─────────────────────────────────────────────────────────────────\n\n /**\n * Batches multiple reactive changes into a single DOM update pass.\n *\n * @example\n * ```ts\n * en.batch(() => {\n * data.firstName = 'Jane';\n * data.lastName = 'Doe';\n * });\n * ```\n */\n batch(fn: () => void): void {\n batch(this.ctx, fn);\n }\n\n // ─── load ──────────────────────────────────────────────────────────────────\n\n /**\n * Fetches one or more HTML files and registers any `<template name=\"...\">` \n * elements found inside them as custom components.\n *\n * @example\n * ```ts\n * await en.load(['components/card.html', 'components/modal.html']);\n * ```\n */\n async load(files: string | string[]): Promise<void> {\n const list = Array.isArray(files) ? files : [files];\n await Promise.all(list.map(f => loadTemplateFile(f)));\n }\n\n // ─── register ──────────────────────────────────────────────────────────────\n\n /**\n * Registers component templates at runtime.\n *\n * Accepts:\n * - No args → scans the whole document\n * - An `HTMLElement` root\n * - A template string\n * - A tagged-template literal\n *\n * @example\n * ```ts\n * en.register`<template name=\"my-btn\"><button><slot /></button></template>`;\n * ```\n */\n register(root: TemplateStringsArray, ...args: unknown[]): void;\n register(root: HTMLElement): void;\n register(template: string): void;\n register(): void;\n register(\n root?: TemplateStringsArray | HTMLElement | string,\n ...args: unknown[]\n ): void {\n if (Array.isArray(root)) {\n root = stitchTagTemplate(root as string[], ...args);\n }\n if (typeof root === 'string') {\n root = wrapInDiv(root);\n }\n registerTemplates(root as HTMLElement | undefined);\n }\n\n // ─── destroy ───────────────────────────────────────────────────────────────\n\n /**\n * Tears down the instance: removes event listeners, clears watchers,\n * and prevents further DOM updates.\n */\n destroy(): void {\n this.ctx.destroyed = true;\n\n if (this.readyStateHandler) {\n document.removeEventListener(\n 'readystatechange',\n this.readyStateHandler,\n );\n this.readyStateHandler = null;\n }\n\n this.ctx.watchers.clear();\n this.ctx.deps.map.clear();\n this.ctx.deps.versions.clear();\n this.ctx.elementCache.clear();\n this.ctx.observer?.disconnect();\n this.ctx.observer = null;\n this.ctx.data = null;\n }\n}\n\n// ─── Default singleton factory ────────────────────────────────────────────────\n\n/**\n * Creates a new isolated entropy instance.\n * Most applications only need the default export.\n */\nexport function createInstance(): EntropyInstance {\n return new EntropyInstance();\n}\n","/**\n * entropy – Lightweight reactive DOM library\n *\n * @example Quick start\n * ```html\n * <script type=\"module\">\n * import en from 'entropy-js';\n * const data = en.init();\n * data.count = 0;\n * </script>\n *\n * <span en-mark=\"count\"></span>\n * <button onclick=\"data.count++\">+1</button>\n * ```\n */\n\nexport { EntropyInstance, createInstance } from './instance';\nexport type { Meta } from './instance';\nexport { computed } from './computed';\n\n// Public types\nexport type {\n Directive,\n DirectiveParams,\n DirectiveEntry,\n Watcher,\n Prefixed,\n SyncConfig,\n} from './types';\n\n// ─── Default singleton instance ───────────────────────────────────────────────\n\nimport { EntropyInstance } from './instance';\n\n/**\n * The default entropy instance.\n *\n * For single-page applications this is all you need.\n * For micro-frontends or isolated widgets, use `createInstance()` instead.\n */\nconst en = new EntropyInstance();\nexport default en;\n"]}
|