@ape-egg/vibe 1.8.0 → 1.9.1

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/llms.txt CHANGED
@@ -9,9 +9,12 @@ Vibe is a lightweight reactive library that uses Proxy-based state and MutationO
9
9
  **Key characteristics:**
10
10
  - Proxy-based reactive state (`window.$`)
11
11
  - Deep reactivity (nested mutations automatically trigger updates)
12
- - Surgical DOM updates (only affected elements re-render)
12
+ - Surgical DOM updates (only affected elements re-render; idempotent writes skip no-op DOM mutations)
13
+ - State batching (multiple `$.x = y` writes in the same microtask flush as one update)
13
14
  - MutationObserver for dynamic element tracking
14
- - Works with vanilla HTML - no special file format
15
+ - Works with vanilla HTML no special file format
16
+ - Component-local state via `component({...})` + `this.X`
17
+ - Component composition via `<component src>` with reactive props (objects/arrays/primitives) and slots
15
18
 
16
19
  ## Installation
17
20
 
@@ -23,19 +26,21 @@ npm install @ape-egg/vibe
23
26
 
24
27
  ```html
25
28
  <script type="module">
26
- import state from "@ape-egg/vibe";
27
- window.$ = state({ name: "World", count: 0 });
29
+ import vibe from "@ape-egg/vibe";
30
+ window.$ = vibe({ name: "World", count: 0 });
28
31
  </script>
29
32
 
30
- <h1>Hello, @[name]!</h1>
31
- <button onclick="$.count++">Clicked @[count] times</button>
33
+ <body vibe-fouc>
34
+ <h1>Hello, @[name]!</h1>
35
+ <button onclick="$.count++">Clicked @[count] times</button>
36
+ </body>
32
37
  ```
33
38
 
34
39
  ## Core Syntax
35
40
 
36
41
  ### Reactive Bindings
37
42
 
38
- Use `@[property]` syntax anywhere in HTML or CSS:
43
+ Use `@[expression]` syntax anywhere in HTML or CSS:
39
44
 
40
45
  ```html
41
46
  <!-- Text content -->
@@ -44,11 +49,15 @@ Use `@[property]` syntax anywhere in HTML or CSS:
44
49
  <!-- Expressions -->
45
50
  <div>@[firstName + ' ' + lastName]</div>
46
51
  <div>@[count * 2]</div>
52
+ <div>@[items.filter(x => x.active).length]</div>
47
53
 
48
54
  <!-- Attributes -->
49
55
  <input value="@[inputValue]">
50
56
  <button disabled="@[isLoading]">Submit</button>
51
57
 
58
+ <!-- Attribute names (name bindings) -->
59
+ <icon @[iconName]></icon>
60
+
52
61
  <!-- CSS -->
53
62
  <style>
54
63
  .box { background: @[themeColor]; }
@@ -65,7 +74,7 @@ State is accessed globally via `window.$`:
65
74
  // Read
66
75
  console.log($.firstName);
67
76
 
68
- // Write (triggers re-render)
77
+ // Write (triggers re-render — batched per microtask)
69
78
  $.firstName = "John";
70
79
 
71
80
  // Increment
@@ -97,9 +106,17 @@ With index:
97
106
  <!-- /each -->
98
107
  ```
99
108
 
109
+ The expression after `each` is any JavaScript that returns an array or array-like:
110
+
111
+ ```html
112
+ <!-- each items.filter(x => x.active) as item -->
113
+ <!-- each Array.from({length: 10}, (_, i) => i) as n -->
114
+ <!-- each Object.values(users) as user, i -->
115
+ ```
116
+
100
117
  ### Nested Iteration
101
118
 
102
- Use dot paths for nested arrays:
119
+ Use dot paths or any expression:
103
120
 
104
121
  ```html
105
122
  <!-- each categories as category -->
@@ -122,71 +139,103 @@ Use dot paths for nested arrays:
122
139
 
123
140
  Conditionals can be nested inside iterations and vice versa.
124
141
 
125
- ## Special Attributes
142
+ ## Components
126
143
 
127
- ### Dehydrate
144
+ ```html
145
+ <component src="/components/card.html" title="@[pageTitle]" theme="dark">
146
+ <p>This content replaces &lt;slot&gt;&lt;/slot&gt;</p>
147
+ </component>
148
+ ```
128
149
 
129
- Skip reactive processing for an element and its children:
150
+ **Behavior:**
151
+ 1. Vibe finds `<component src="...">` elements (also `<div class="component" src="...">`)
152
+ 2. Fetches the source HTML
153
+ 3. Substitutes props (`@[title]` in the template becomes `@[pageTitle]`)
154
+ 4. Inserts slot content (between the tags) into `<slot></slot>`
155
+ 5. Removes `src`; the `<component>` wrapper remains as a boundary marker
156
+
157
+ **Reactive props** (`title="@[pageTitle]"`) keep tracking the parent's state. **Static props** (`theme="dark"`) inline as literals. **Object/array props** through iteration scope (`<component card="@[card]">` inside `<!-- each cards as card -->`) are stashed in an internal registry so child templates can `@[card.name]` or `<!-- each card.abilities as a -->`.
158
+
159
+ **Two-way binding** falls out for free: a child component that writes `$.value = x` in an event handler has that `$.value` rewritten to the parent's bound path, so the parent's state actually updates.
160
+
161
+ **Slot content** that itself contains `<component src>` is also processed recursively.
162
+
163
+ ## Component-Local State
164
+
165
+ For state scoped to a single component (form drafts, toggles, derived view-state) instead of global `$`:
130
166
 
131
167
  ```html
132
- <code vibe-dehydrate>@[this] displays literally, not parsed</code>
168
+ <!-- /components/Counter.html -->
169
+ <script type="module">
170
+ import component from '@ape-egg/vibe/component';
171
+ component({ count: 0, increment() { this.count++; } });
172
+ </script>
173
+
174
+ <button onclick="this.increment()">Clicked @[this.count] times</button>
133
175
  ```
134
176
 
135
- Use cases:
136
- - Displaying `@[...]` syntax in documentation
137
- - Static content that shouldn't be reactive
138
- - Performance optimization for large static sections
177
+ How it works:
139
178
 
140
- ### Boolean Attributes
179
+ 1. `component({...})` generates a unique id (e.g. `_c0`) and stores state at `$[id]`
180
+ 2. The `<script>` and every following sibling get `data-vibe-component-id="<id>"`
181
+ 3. Inside that subtree, `@[this.X.Y]` is rewritten to `@[_c0.X.Y]`; `onclick="this.fn()"` becomes `onclick="$['_c0'].fn()"`; `$.this.x = v` (in event handlers) becomes `$['_c0'].x = v`
182
+ 4. When the component leaves the DOM, its bucket is freed automatically
141
183
 
142
- Attributes not in the value whitelist are removed when falsy:
184
+ Multi-segment paths, conditionals (`<!-- if this.editing -->`), and iterations (`<!-- each this.items as item -->`) all work. Global `$` and component-local `this.X` coexist within the same template.
143
185
 
144
- ```html
145
- <button disabled="@[isLoading]">Submit</button>
146
- <!-- When isLoading is false, disabled attribute is removed entirely -->
186
+ ## Lifecycle Hooks
187
+
188
+ ```javascript
189
+ $.on('ready', () => {}); // once, after initial parse + hydrate + components mounted
190
+ $.on('afterUpdate', (cur, prev) => {}); // every state change (batched per microtask)
191
+ $.on('afterDomMutation', () => {}); // after every MutationObserver batch
147
192
  ```
148
193
 
149
- ## Events
194
+ Also: `await $.ready` resolves after boot, useful when calling code captured `window.$` before vibe finished initializing.
195
+
196
+ ## Special Attributes
197
+
198
+ ### vibe-fouc
150
199
 
151
- Use standard inline event handlers:
200
+ Add to an element (typically `<body>`) to hide it until Vibe's first hydration completes. Vibe removes the attribute when ready.
152
201
 
153
202
  ```html
154
- <button onclick="$.count++">Increment</button>
155
- <input oninput="$.text = this.value">
156
- <form onsubmit="event.preventDefault(); handleSubmit()">
203
+ <body vibe-fouc>
157
204
  ```
158
205
 
159
- ## Styling
206
+ Pair with `vibe.css` (`<link rel="stylesheet" href="@ape-egg/vibe/vibe.css">`) which targets `[vibe-fouc]` with `visibility: hidden`.
160
207
 
161
- ### CSS Bindings
208
+ ### vibe-dehydrate
162
209
 
163
- Reactive values work inside `<style>` tags:
210
+ Skip reactive processing for an element and its children:
164
211
 
165
212
  ```html
166
- <style>
167
- .box {
168
- background: @[backgroundColor];
169
- color: @[textColor];
170
- width: @[width]px;
171
- }
172
- </style>
213
+ <code vibe-dehydrate>@[this] displays literally, not parsed</code>
173
214
  ```
174
215
 
175
- ### Preventing FOUC
216
+ Use cases: documenting `@[...]` syntax, large static sections, content that must not be evaluated.
217
+
218
+ ### Boolean Attributes
176
219
 
177
- Hide content until hydration completes:
220
+ Pure-binding attributes that aren't in the value whitelist (e.g. `disabled`, `checked`, `active`) are added when truthy and removed when falsy:
178
221
 
179
222
  ```html
180
- <body style="visibility: hidden;">
223
+ <button disabled="@[isLoading]">Submit</button>
224
+ <!-- isLoading=false → attribute removed entirely -->
181
225
  ```
182
226
 
183
- Or use the included CSS:
227
+ ## Events
228
+
229
+ Use standard inline event handlers — they execute against `$` directly:
184
230
 
185
231
  ```html
186
- <link rel="stylesheet" href="@ape-egg/vibe/vibe.css">
187
- <body vibe-fouc>
232
+ <button onclick="$.count++">Increment</button>
233
+ <input oninput="$.text = this.value">
234
+ <form onsubmit="event.preventDefault(); handleSubmit()">
188
235
  ```
189
236
 
237
+ Inside a component, `this.X` references the component's bucket (rewritten at parse time); `this.value`, `this.checked`, `this.dataset` etc. still reach the DOM element since DOM properties are preserved.
238
+
190
239
  ## Dynamic Elements
191
240
 
192
241
  Elements added via JavaScript are automatically hydrated through MutationObserver:
@@ -200,33 +249,47 @@ document.body.appendChild(div);
200
249
 
201
250
  ## API Reference
202
251
 
203
- ### `state(initialState, afterUpdate?)`
252
+ ### `vibe(initialState, config?)`
204
253
 
205
- Creates reactive state and initializes the framework.
254
+ Initializes the framework and returns the reactive state proxy.
206
255
 
207
256
  ```javascript
208
- import state from "@ape-egg/vibe";
257
+ import vibe from "@ape-egg/vibe";
209
258
 
210
- window.$ = state(
259
+ window.$ = vibe(
211
260
  { count: 0, user: { name: "Alice" } },
212
- (newState, oldState) => {
213
- console.log("State updated:", newState);
214
- }
261
+ { debug: false }
215
262
  );
216
263
  ```
217
264
 
218
265
  **Parameters:**
219
- - `initialState` - Object containing initial state values
220
- - `afterUpdate` - Optional callback after each state change (receives read-only snapshots)
266
+ - `initialState` object containing initial state values
267
+ - `config` optional object. Currently supports `{ debug: boolean }`. A third positional argument can pass a target selector (defaults to `body`).
268
+
269
+ **Returns:** Reactive proxy. Assign it to `window.$` so inline event handlers and bindings can find it.
270
+
271
+ ### `component(initialState)`
272
+
273
+ Imported from `@ape-egg/vibe/component`. Registers a component-local state bucket; called from inside a `<script type="module">` in a component file. See [Component-Local State](#component-local-state).
221
274
 
222
- **Returns:** Proxy object for reactive state access
275
+ ### `$.on(event, callback)`
223
276
 
224
- ## Scoped Variables
277
+ Register a lifecycle listener. Events: `'ready'`, `'afterUpdate'`, `'afterDomMutation'`. Listeners registered before boot are queued and replayed once vibe is ready.
278
+
279
+ ### `$.ready`
280
+
281
+ A Promise that resolves once vibe has finished initial parse + hydrate + component loading.
282
+
283
+ ### `$.reconcile(el, html)` and `$.renderComponent(rawHtml, props, slot, opts)` (advanced)
284
+
285
+ Subtree reconciliation primitives used by `@ape-egg/vite-plugin-vibe` for surgical HMR. `$.reconcile` diffs `el`'s children against fresh `html` while preserving DOM identity, focus, and selection; vibe-managed regions (iterations, conditionals, components, slot pairs) are treated as opaque. Treat these as plumbing — shape may evolve.
286
+
287
+ ## Scoped Variables in Iterations
225
288
 
226
289
  Inside `<!-- each -->` blocks, these variables are available:
227
- - `item` (or custom name) - current array element
228
- - `index` (or custom name) - current index
229
- - Parent state remains accessible via `$`
290
+ - `item` (or custom name) current array element
291
+ - `index` (or custom name) current index
292
+ - Parent state remains accessible via `$` and via free identifiers (e.g. `tutorialProgress`)
230
293
 
231
294
  ```html
232
295
  <!-- each users as user, i -->
@@ -236,7 +299,7 @@ Inside `<!-- each -->` blocks, these variables are available:
236
299
 
237
300
  ### Scoped State (Internal)
238
301
 
239
- Each iteration instance stores a `scopedState` - a Proxy wrapper that provides access to both local variables (`item`, `index`) and global state. This enables reactive updates inside iterations:
302
+ Each iteration instance stores a `scopedState` Proxy that combines local variables (`item`, `index`) with global state. This lets bindings inside iterations react to global state changes:
240
303
 
241
304
  ```html
242
305
  <!-- each menuItems as item -->
@@ -246,50 +309,50 @@ Each iteration instance stores a `scopedState` - a Proxy wrapper that provides a
246
309
  <!-- /each -->
247
310
  ```
248
311
 
249
- When `tutorialProgress` changes, Vibe:
250
- 1. Finds affected elements inside iteration instances
251
- 2. Uses that instance's `scopedState` for evaluation
252
- 3. Can access both `item` (local) and `tutorialProgress` (global)
253
- 4. Updates only the affected elements without re-rendering the entire iteration
312
+ When `tutorialProgress` changes, vibe finds affected elements inside iteration instances, evaluates against that instance's `scopedState`, and updates only the changed elements without re-rendering the whole list.
254
313
 
255
314
  ## Architecture
256
315
 
257
- Vibe consists of these core modules:
316
+ Vibe consists of these core runtime modules (in `runtime/`):
258
317
 
259
- - **state.js** - Proxy-based reactive state container with recursive proxies for deep reactivity
260
- - **parse.js** - DOM parser that finds `@[...]` bindings
261
- - **link.js** - Maps elements to parsed tree nodes
262
- - **hydrate.js** - Updates DOM with current state values (supports scoped state for iterations)
263
- - **affected.js** - Determines which elements need updating (walks iteration instances with scoped state)
264
- - **iterate.js** - Array rendering with efficient diffing (stores scoped state per instance)
265
- - **conditionals.js** - Conditional block rendering
318
+ - **state.js** Proxy-based reactive state, recursive proxies for deep reactivity, batched flush via `queueMicrotask`
319
+ - **parse.js** DOM parser that finds `@[...]` bindings, iteration/conditional comments, and `<component src>` elements
320
+ - **manifest.js** Maps DOM elements to parsed-tree nodes (was `link.js` in older versions)
321
+ - **hydrate.js** Updates DOM with current state values; idempotent (skips no-op writes)
322
+ - **affected.js** Determines which bindings need re-evaluation when state changes
323
+ - **iterate.js** Array rendering with diffing; bulk-replacement fast path; iteration-prop registry for non-primitive component props
324
+ - **conditionals.js** Conditional block rendering; preserves both branches in the manifest for reactive switching
325
+ - **component.js** — `<component src>` fetching, prop substitution, slot inlining, component-local state setup, `this.X` rewriting
326
+ - **reconcile.js** — Subtree reconciliation primitive (`$.reconcile`)
327
+ - **cleanup.js** — `vibe-fouc` release once a subtree is fully processed
266
328
 
267
329
  ## How It Works
268
330
 
269
331
  ```
270
- 1. state() initializes the Proxy and framework
271
- 2. parse.js scans DOM for @[...], <!-- each -->, <!-- if -->
272
- 3. link.js maps elements to the parsed tree
332
+ 1. vibe(initialState) creates the Proxy and starts the runtime
333
+ 2. parse.js scans DOM for @[...], <!-- each -->, <!-- if -->, <component src>
334
+ 3. manifest.js maps elements parsed tree
273
335
  4. hydrate.js replaces bindings with values
274
336
  5. iterate.js renders <!-- each --> loops
275
337
  6. conditionals.js renders <!-- if --> blocks
276
- 7. MutationObserver watches for new elements
277
- 8. On state change: affected.js finds changed elements → hydrate.js updates them
338
+ 7. component.js fetches <component src> templates, substitutes props, inlines slots
339
+ 8. MutationObserver watches for new/removed elements; affected.js + hydrate.js handle state changes
278
340
  ```
279
341
 
280
342
  ## Current Limitations
281
343
 
282
- - **No computed values**: Derived state must be calculated manually
283
- - **No two-way binding sugar**: Must wire input events manually
284
- - **Expression security**: `new Function()` evaluation - don't bind untrusted input
344
+ - **No computed values primitive**: derived state can be done with `Object.defineProperty($, 'x', { get })` or with `afterUpdate` listeners; a first-class `computed` API isn't shipped
345
+ - **Expression security**: `new Function()` evaluation don't bind untrusted input
346
+ - **HTML binding**: `@[expr]` always sets `textContent` (escape-safe). A first-class opt-in for trusted HTML is planned but not finalized
285
347
 
286
348
  ## Best Practices
287
349
 
288
- 1. **Initialize state before DOM**: Place `<script>` in `<head>` or before reactive elements
289
- 2. **Use dehydrate for docs**: When showing `@[...]` syntax examples
290
- 3. **Prevent FOUC**: Use `visibility: hidden` on body until hydration
291
- 4. **Keep expressions simple**: Complex logic belongs in JavaScript, not templates
292
- 5. **Mutate freely**: Deep reactivity means `$.user.name = "New"` just works - no spread operators needed
350
+ 1. **Initialize state in `<head>`** before reactive elements; pair with `vibe-fouc` on `<body>`
351
+ 2. **Mutate freely** deep reactivity means `$.user.name = "New"` just works; no spread operators needed
352
+ 3. **Use lifecycle hooks instead of `setTimeout` / `requestAnimationFrame`** when you need to wait for vibe to finish work
353
+ 4. **Use `component({...})` for state that's local to one piece of UI** (form draft, toggle); keep cross-cutting state on global `$`
354
+ 5. **Use `vibe-dehydrate` when you need to display `@[...]` literally** (docs, code examples)
355
+ 6. **Keep expressions simple** — complex logic belongs in JavaScript; templates should read like HTML
293
356
 
294
357
  ## Browser Support
295
358
 
@@ -298,6 +361,10 @@ Modern browsers with:
298
361
  - MutationObserver
299
362
  - ES Modules
300
363
 
364
+ ## Related Packages
365
+
366
+ - **`@ape-egg/vite-plugin-vibe`** — Vite plugin with surgical component HMR (template-only edits reconcile in place; script edits re-mount)
367
+
301
368
  ## Resources
302
369
 
303
370
  - **Homepage**: https://vibe.korte.kim
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@ape-egg/vibe",
3
- "version": "1.8.0",
3
+ "version": "1.9.1",
4
4
  "type": "module",
5
5
  "description": "Runtime-first reactivity with optional compiler",
6
6
  "main": "index.js",
7
7
  "homepage": "https://vibe.korte.kim",
8
8
  "exports": {
9
9
  ".": "./index.js",
10
+ "./boot": "./boot.js",
10
11
  "./component": "./component.js",
11
12
  "./runtime": "./runtime/index.js",
12
13
  "./compiler": "./compiler/bin/vibe-compile.js"
@@ -27,7 +28,7 @@
27
28
  "scripts": {
28
29
  "test": "echo \"Error: no test specified\" && exit 1"
29
30
  },
30
- "author": "Kim Korte",
31
+ "author": "kkortes",
31
32
  "license": "ISC",
32
33
  "publishConfig": {
33
34
  "access": "public"
@@ -28,6 +28,15 @@
28
28
 
29
29
  import { BINDING_REGEX } from './constants.js';
30
30
 
31
+ // innerHTML serialization encodes <, >, &, ", ' inside attribute values.
32
+ // Decode them back before wrapping @[expr] in ${...} for the template literal.
33
+ const decodeEntities = (s) => s
34
+ .replace(/&lt;/g, '<')
35
+ .replace(/&gt;/g, '>')
36
+ .replace(/&quot;/g, '"')
37
+ .replace(/&#39;/g, "'")
38
+ .replace(/&amp;/g, '&');
39
+
31
40
  // Reusable template element for HTML parsing
32
41
  const parseTemplate = document.createElement('template');
33
42
 
@@ -59,20 +68,20 @@ const hasNestedStructures = (tree) => {
59
68
  export const compileBatchFn = (template, itemAlias, indexAlias, stateKeys) => {
60
69
  const templateHtml = template.element.innerHTML.trim();
61
70
  const escaped = templateHtml.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$\{/g, '\\${');
62
- const code = escaped.replace(BINDING_REGEX, (_, expr) => '${' + expr + '}');
71
+ const code = escaped.replace(BINDING_REGEX, (_, expr) => '${' + decodeEntities(expr) + '}');
63
72
 
64
73
  return new Function(
65
74
  'arr',
66
75
  ...stateKeys,
67
76
  `
68
- let html = '';
69
- const len = arr.length;
70
- for (let ${indexAlias} = 0; ${indexAlias} < len; ${indexAlias}++) {
71
- const ${itemAlias} = arr[${indexAlias}];
72
- html += \`${code}\`;
73
- }
74
- return html;
75
- `,
77
+ let html = '';
78
+ const len = arr.length;
79
+ for (let ${indexAlias} = 0; ${indexAlias} < len; ${indexAlias}++) {
80
+ const ${itemAlias} = arr[${indexAlias}];
81
+ html += \`${code}\`;
82
+ }
83
+ return html;
84
+ `,
76
85
  );
77
86
  };
78
87
 
@@ -6,20 +6,33 @@ import { evalInScope, resolveThisPath } from './utils.js';
6
6
  // Evaluate conditional expression
7
7
  const evaluateCondition = (expression, state, element = null) => !!evalInScope(expression, state, element);
8
8
 
9
- // Helper function to check if a match references a specific key
10
- const matchesKey = (matchStr, key) =>
11
- matchStr === key ||
12
- matchStr.startsWith(key + '.') ||
13
- matchStr.startsWith(key + '[');
9
+ // Helper function to check if a match references a specific key.
10
+ // Fast path: exact match or property access (`user.name` matches `user`).
11
+ // Slow path: word-boundary search for complex expressions like `Math.floor(coins / 100)`
12
+ // where the key appears as an identifier anywhere in the expression.
13
+ const isIdentChar = (c) => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c === '_' || c === '$';
14
+
15
+ const matchesKey = (matchStr, key) => {
16
+ if (matchStr === key || matchStr.startsWith(key + '.') || matchStr.startsWith(key + '[')) return true;
17
+
18
+ // Search for key as a standalone identifier (word boundaries on both sides)
19
+ let i = 0;
20
+ while ((i = matchStr.indexOf(key, i)) !== -1) {
21
+ const before = i === 0 ? '' : matchStr[i - 1];
22
+ const after = i + key.length >= matchStr.length ? '' : matchStr[i + key.length];
23
+ if (!isIdentChar(before) && !isIdentChar(after)) return true;
24
+ i += key.length;
25
+ }
26
+ return false;
27
+ };
14
28
 
15
29
  const recursive = (tree, state, newState, affected, scopedStateForHydration = null, depth = 0) => {
16
30
  // Handle iteration nodes specially
17
31
  if (tree.type === 'iteration') {
18
- // Handle this.property for component-scoped arrays
19
- const arrayPath = resolveThisPath(tree.meta.arrayPath, tree.meta.startComment?.parentElement);
32
+ const resolvedExpr = resolveThisPath(tree.meta.arrayPath, tree.meta.startComment?.parentElement);
20
33
 
21
- const oldArray = resolvePath(state, arrayPath);
22
- const newArray = resolvePath(newState, arrayPath);
34
+ const oldArray = evalInScope(resolvedExpr, state, tree.meta.startComment?.parentElement) ?? resolvePath(state, resolvedExpr);
35
+ const newArray = evalInScope(resolvedExpr, newState, tree.meta.startComment?.parentElement) ?? resolvePath(newState, resolvedExpr);
23
36
 
24
37
  // Fast path: reference comparison (arrays are typically replaced, not mutated)
25
38
  // This avoids expensive O(n) deepEqual for large arrays
@@ -55,11 +68,15 @@ const recursive = (tree, state, newState, affected, scopedStateForHydration = nu
55
68
 
56
69
  for (const instance of tree.runtime.instances) {
57
70
  if (instance.tree && instance.scopedState) {
58
- // Use the instance's scoped state (includes item, index, etc.)
59
- // Merge newState into scopedState to get updated global values
71
+ // Build plain-object snapshots for comparison. scopedState is a live Proxy
72
+ // that reflects current global state spreading it gives us the local vars
73
+ // (cat, index) plus current global values. We then override globals with the
74
+ // actual old (state) / new (newState) values so binding comparisons can detect
75
+ // which state keys changed.
76
+ const mergedOldState = { ...instance.scopedState, ...state };
60
77
  const mergedNewState = { ...instance.scopedState, ...newState };
61
- // Pass the Proxy as scopedState so evalInScope can access iteration variables
62
- recursive(instance.tree, instance.scopedState, mergedNewState, affected, instance.scopedState, depth + 1);
78
+ // Pass scopedState as scopedStateForHydration so evalInScope can access iteration variables
79
+ recursive(instance.tree, mergedOldState, mergedNewState, affected, instance.scopedState, depth + 1);
63
80
  }
64
81
  }
65
82
  }
@@ -220,17 +237,20 @@ const recursive = (tree, state, newState, affected, scopedStateForHydration = nu
220
237
  for (const m of nameMatches) {
221
238
  // Resolve this.property to componentId.property
222
239
  const resolvedInner = resolveThisPath(m.inner, tree.element);
240
+ // HTML lowercases attribute names, so expression may be lowercase while state
241
+ // keys are camelCase. Match case-insensitively by trying both direct and lowercased.
242
+ const matchKey = (key) => matchesKey(resolvedInner, key) || matchesKey(resolvedInner, key.toLowerCase());
223
243
 
224
- const noMatch = !shallowState.some((key) => matchesKey(resolvedInner, key));
244
+ const noMatch = !shallowState.some(matchKey);
225
245
 
226
246
  let shouldAffect = false;
227
247
 
228
248
  if (isInitialHydration) {
229
- const newMatches = shallowNewState.filter((key) => matchesKey(resolvedInner, key));
249
+ const newMatches = shallowNewState.filter(matchKey);
230
250
  shouldAffect = noMatch || newMatches.length > 0;
231
251
  } else {
232
252
  const changedKeys = shallowNewState.filter((key) =>
233
- matchesKey(resolvedInner, key) && state[key] !== newState[key]
253
+ matchKey(key) && state[key] !== newState[key]
234
254
  );
235
255
  shouldAffect = noMatch || changedKeys.length > 0;
236
256
  }