@estjs/template 0.0.15 → 0.0.16-beta.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.
@@ -3,21 +3,20 @@
3
3
  var shared = require('@estjs/shared');
4
4
  var signals = require('@estjs/signals');
5
5
 
6
- var __defProp = Object.defineProperty;
7
6
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
8
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
- var __spreadValues = (a, b) => {
12
- for (var prop in b || (b = {}))
13
- if (__hasOwnProp.call(b, prop))
14
- __defNormalProp(a, prop, b[prop]);
15
- if (__getOwnPropSymbols)
16
- for (var prop of __getOwnPropSymbols(b)) {
17
- if (__propIsEnum.call(b, prop))
18
- __defNormalProp(a, prop, b[prop]);
19
- }
20
- return a;
9
+ var __objRest = (source, exclude) => {
10
+ var target = {};
11
+ for (var prop in source)
12
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
13
+ target[prop] = source[prop];
14
+ if (source != null && __getOwnPropSymbols)
15
+ for (var prop of __getOwnPropSymbols(source)) {
16
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
17
+ target[prop] = source[prop];
18
+ }
19
+ return target;
21
20
  };
22
21
  var __async = (__this, __arguments, generator) => {
23
22
  return new Promise((resolve, reject) => {
@@ -39,134 +38,47 @@ var __async = (__this, __arguments, generator) => {
39
38
  step((generator = generator.apply(__this, __arguments)).next());
40
39
  });
41
40
  };
42
- var LIFECYCLE = {
43
- mount: "mount",
44
- destroy: "destroy",
45
- update: "update"
46
- };
47
- function registerScopedHook(scope, listKey, hook) {
48
- let hookList = scope[listKey];
49
- if (!hookList) {
50
- hookList = scope[listKey] = [];
51
- }
52
- if (!hookList.includes(hook)) {
53
- hookList.push(hook);
54
- }
55
- }
56
- function executeHooks(hooks, scopeId2, phase) {
57
- const len = hooks.length;
58
- if (len === 0) return;
59
- let pending;
60
- for (let i = 0; i < len; i++) {
61
- try {
62
- const result = hooks[i]();
63
- if (shared.isPromise(result)) {
64
- const safePromise = result.catch((error_) => {
65
- if (true) {
66
- shared.error(`Scope(${scopeId2}): Async ${phase} hook rejected:`, error_);
67
- }
68
- });
69
- (pending != null ? pending : pending = []).push(safePromise);
70
- }
71
- } catch (error_) {
72
- {
73
- shared.error(`Scope(${scopeId2}): Error in ${phase} hook:`, error_);
74
- }
75
- }
76
- }
77
- if (!pending) return;
78
- return Promise.all(pending).then(() => void 0);
79
- }
80
- function onMount(hook) {
81
- const scope = getActiveScope();
82
- if (!scope) {
83
- shared.error("onMount() must be called within a scope");
84
- return;
85
- }
86
- if (scope.isMounted) {
87
- try {
88
- const result = hook();
89
- if (shared.isPromise(result)) {
90
- result.catch((error_) => {
91
- if (true) shared.error(`Scope(${scope.id}): Async ${LIFECYCLE.mount} hook rejected:`, error_);
92
- });
93
- }
94
- } catch (error_) {
95
- shared.error(`Scope(${scope.id}): Error in ${LIFECYCLE.mount} hook:`, error_);
96
- }
97
- return;
98
- }
99
- registerScopedHook(scope, "onMount", hook);
100
- }
101
- function onUpdate(hook) {
102
- const scope = getActiveScope();
103
- if (!scope) {
104
- shared.error("onUpdate() must be called within a scope");
105
- return;
106
- }
107
- registerScopedHook(scope, "onUpdate", hook);
108
- }
109
- function onDestroy(hook) {
110
- const scope = getActiveScope();
111
- if (!scope) {
112
- shared.error("onDestroy() must be called within a scope");
113
- return;
114
- }
115
- registerScopedHook(scope, "onDestroy", hook);
116
- }
117
- function triggerMountHooks(scope) {
118
- var _a2;
119
- if (scope.isDestroyed || !((_a2 = scope.onMount) == null ? void 0 : _a2.length)) {
120
- scope.isMounted = true;
121
- return;
122
- }
123
- const mountHooks = scope.onMount;
124
- const result = runWithScope(scope, () => executeHooks(mountHooks, scope.id, LIFECYCLE.mount));
125
- mountHooks.length = 0;
126
- scope.isMounted = true;
127
- return result;
128
- }
129
- function triggerUpdateHooks(scope) {
130
- var _a2;
131
- if (scope.isDestroyed || !((_a2 = scope.onUpdate) == null ? void 0 : _a2.length)) return;
132
- const updateHooks = scope.onUpdate;
133
- const result = runWithScope(scope, () => executeHooks(updateHooks, scope.id, "update"));
134
- updateHooks.length = 0;
135
- return result;
136
- }
137
- function triggerDestroyHooks(scope) {
138
- var _a2;
139
- if (scope.isDestroyed || !((_a2 = scope.onDestroy) == null ? void 0 : _a2.length)) return;
140
- return runWithScope(scope, () => executeHooks(scope.onDestroy, scope.id, "destroy"));
141
- }
142
41
 
143
- // src/scope.ts
42
+ // src/constants.ts
43
+ var SPREAD_NAME = "_$spread$";
44
+ var REF_KEY = "ref";
45
+ var KEY_PROP = "key";
46
+ var SVG_NAMESPACE = "http://www.w3.org/2000/svg";
47
+ var XLINK_NAMESPACE = "http://www.w3.org/2000/xlink";
48
+ var XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/";
49
+ var FRAGMENT_COMPONENT = /* @__PURE__ */ Symbol("Fragment Component" );
50
+ var PORTAL_COMPONENT = /* @__PURE__ */ Symbol("Portal Component" );
51
+ var SUSPENSE_COMPONENT = /* @__PURE__ */ Symbol("Suspense Component" );
52
+ var FOR_COMPONENT = /* @__PURE__ */ Symbol("For Component" );
144
53
  var activeScope = null;
145
54
  var scopeId = 0;
146
55
  function getActiveScope() {
147
56
  return activeScope;
148
57
  }
149
- function setActiveScope(scope) {
150
- activeScope = scope;
151
- }
152
58
  function createScope(parent = activeScope) {
153
59
  const scope = {
154
60
  id: ++scopeId,
155
61
  parent,
156
62
  children: null,
63
+ // Lazy initialized
157
64
  provides: null,
65
+ // Lazy initialized
158
66
  cleanup: null,
67
+ // Lazy initialized
159
68
  onMount: null,
69
+ // Lazy initialized
160
70
  onUpdate: null,
71
+ // Lazy initialized
161
72
  onDestroy: null,
73
+ // Lazy initialized
162
74
  isMounted: false,
163
75
  isDestroyed: false
164
76
  };
165
77
  if (parent) {
166
78
  if (!parent.children) {
167
- parent.children = [];
79
+ parent.children = /* @__PURE__ */ new Set();
168
80
  }
169
- parent.children.push(scope);
81
+ parent.children.add(scope);
170
82
  }
171
83
  return scope;
172
84
  }
@@ -180,47 +92,61 @@ function runWithScope(scope, fn) {
180
92
  }
181
93
  }
182
94
  function disposeScope(scope) {
183
- var _a2, _b, _c;
95
+ var _a2;
184
96
  if (!scope || scope.isDestroyed) {
185
97
  return;
186
98
  }
187
- const parentScope = scope.parent;
188
- if (scope.children) {
189
- for (const child of scope.children) {
190
- disposeScope(child);
99
+ scope.isDestroyed = true;
100
+ if (scope.children && scope.children.size > 0) {
101
+ for (const child2 of scope.children) {
102
+ if (child2) {
103
+ child2.parent = null;
104
+ disposeScope(child2);
105
+ }
191
106
  }
192
- scope.children.length = 0;
107
+ scope.children.clear();
193
108
  }
194
- if ((_a2 = scope.onDestroy) == null ? void 0 : _a2.length) {
195
- triggerDestroyHooks(scope);
196
- scope.onDestroy.length = 0;
197
- }
198
- if ((_b = scope.cleanup) == null ? void 0 : _b.length) {
199
- for (const fn of scope.cleanup) {
200
- try {
201
- fn();
202
- } catch (error_) {
203
- {
204
- shared.error(`Scope(${scope.id}): Error in cleanup:`, error_);
109
+ const prevScope = activeScope;
110
+ activeScope = scope;
111
+ try {
112
+ if (scope.onDestroy) {
113
+ for (let i = 0; i < scope.onDestroy.length; i++) {
114
+ try {
115
+ scope.onDestroy[i]();
116
+ } catch (error_) {
117
+ if (true) {
118
+ shared.error(`Scope(${scope.id}): Error in destroy hook:`, error_);
119
+ }
205
120
  }
206
121
  }
122
+ scope.onDestroy = null;
207
123
  }
208
- scope.cleanup.length = 0;
209
- }
210
- if (parentScope == null ? void 0 : parentScope.children) {
211
- const idx = parentScope.children.indexOf(scope);
212
- if (idx !== -1) {
213
- parentScope.children.splice(idx, 1);
124
+ if (scope.cleanup) {
125
+ for (let i = 0; i < scope.cleanup.length; i++) {
126
+ try {
127
+ scope.cleanup[i]();
128
+ } catch (error_) {
129
+ if (true) {
130
+ shared.error(`Scope(${scope.id}): Error in cleanup:`, error_);
131
+ }
132
+ }
133
+ }
134
+ scope.cleanup = null;
214
135
  }
136
+ } finally {
137
+ activeScope = prevScope;
215
138
  }
216
- (_c = scope.provides) == null ? void 0 : _c.clear();
217
- if (scope.onMount) scope.onMount.length = 0;
218
- if (scope.onUpdate) scope.onUpdate.length = 0;
219
- scope.parent = null;
220
- scope.isDestroyed = true;
221
- if (activeScope === scope) {
222
- activeScope = parentScope;
139
+ if ((_a2 = scope.parent) == null ? void 0 : _a2.children) {
140
+ scope.parent.children.delete(scope);
223
141
  }
142
+ if (scope.provides) {
143
+ scope.provides.clear();
144
+ scope.provides = null;
145
+ }
146
+ scope.onMount = null;
147
+ scope.onUpdate = null;
148
+ scope.children = null;
149
+ scope.parent = null;
224
150
  }
225
151
  function onCleanup(fn) {
226
152
  const scope = activeScope;
@@ -235,456 +161,449 @@ function onCleanup(fn) {
235
161
  }
236
162
  scope.cleanup.push(fn);
237
163
  }
238
-
239
- // src/constants.ts
240
- var EVENT_PREFIX = "on";
241
- var SPREAD_NAME = "_$spread$";
242
- var REF_KEY = "ref";
243
- var KEY_PROP = "key";
244
- var SVG_NAMESPACE = "http://www.w3.org/2000/svg";
245
- var XLINK_NAMESPACE = "http://www.w3.org/2000/xlink";
246
- var XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/";
247
- var NORMAL_COMPONENT = /* @__PURE__ */ Symbol("Normal Component" );
248
- var FRAGMENT_COMPONENT = /* @__PURE__ */ Symbol("Fragment Component" );
249
- var PORTAL_COMPONENT = /* @__PURE__ */ Symbol("Portal Component" );
250
- var SUSPENSE_COMPONENT = /* @__PURE__ */ Symbol("Suspense Component" );
251
- var FOR_COMPONENT = /* @__PURE__ */ Symbol("For Component" );
252
- var MAX_KEY_LENGTH = 1e3;
253
- var componentKeyPrefixCache = /* @__PURE__ */ new WeakMap();
254
- function getComponentKey(type) {
255
- let prefix = componentKeyPrefixCache.get(type);
256
- if (!prefix) {
257
- const name = type.name || "anonymous";
258
- const hash = simpleHash(type.toString()).toString(36);
259
- prefix = `${name}_${hash}`;
260
- componentKeyPrefixCache.set(type, prefix);
261
- }
262
- return prefix;
263
- }
264
- function simpleHash(str) {
265
- let hash = 0;
266
- const len = str.length < 100 ? str.length : 100;
267
- for (let i = 0; i < len; i++) {
268
- hash = Math.trunc((hash << 5) - hash + str.charCodeAt(i));
269
- }
270
- return hash < 0 ? -hash : hash;
271
- }
272
- var symbolIdCounter = 0;
273
- function normalizeKey(key) {
274
- if (shared.isFalsy(key)) {
275
- return void 0;
276
- }
277
- if (shared.isString(key)) {
278
- if (key.length <= MAX_KEY_LENGTH) {
279
- return key;
280
- }
281
- {
282
- shared.warn(
283
- `[Key System] Key length exceeds ${MAX_KEY_LENGTH} characters. Consider using a shorter identifier.`
284
- );
164
+ function patchAttr(el, key, prev, next2) {
165
+ if (key === KEY_PROP) {
166
+ if (next2 == null) {
167
+ el.removeAttribute(key);
168
+ } else {
169
+ el.setAttribute(key, String(next2));
285
170
  }
286
- return `${key.slice(0, MAX_KEY_LENGTH - 10)}_${simpleHash(key).toString(36)}`;
171
+ return;
287
172
  }
288
- if (shared.isNumber(key)) {
173
+ if (key === SPREAD_NAME) {
174
+ const prevObj = shared.isObject(prev) ? prev : null;
175
+ const nextObj = shared.isObject(next2) ? next2 : null;
289
176
  {
290
- if (key !== key) {
291
- shared.warn("[Key System] NaN cannot be used as a key");
292
- return void 0;
177
+ if (next2 != null && !nextObj) {
178
+ shared.warn("spread attribute must be an object");
293
179
  }
294
- if (!Number.isFinite(key)) {
295
- shared.warn("[Key System] Infinity cannot be used as a key");
296
- return void 0;
180
+ }
181
+ if (prevObj) {
182
+ for (const attrKey in prevObj) {
183
+ if (attrKey === SPREAD_NAME) {
184
+ {
185
+ shared.warn("nested spread attributes are ignored");
186
+ }
187
+ continue;
188
+ }
189
+ if (!nextObj || !(attrKey in nextObj)) {
190
+ patchAttr(el, attrKey, prevObj[attrKey], null);
191
+ }
297
192
  }
298
193
  }
299
- return String(key);
300
- }
301
- if (shared.isSymbol(key)) {
302
- const globalKey = Symbol.keyFor(key);
303
- if (globalKey) {
304
- return `_s.${globalKey}`;
194
+ if (nextObj) {
195
+ for (const attrKey in nextObj) {
196
+ if (attrKey === SPREAD_NAME) {
197
+ {
198
+ shared.warn("nested spread attributes are ignored");
199
+ }
200
+ continue;
201
+ }
202
+ patchAttr(el, attrKey, prevObj == null ? void 0 : prevObj[attrKey], nextObj[attrKey]);
203
+ }
305
204
  }
306
- const desc = key.description;
307
- return desc ? `_s.${desc}` : `${symbolIdCounter++}`;
205
+ return;
308
206
  }
309
- return String(key);
310
- }
311
- var NODE_KEY_SYMBOL = /* @__PURE__ */ Symbol("essor.key");
312
- function setNodeKey(node, key) {
313
- if (isComponent(node)) {
207
+ const elementIsSVG = (el == null ? void 0 : el.namespaceURI) === SVG_NAMESPACE;
208
+ const isXlink = elementIsSVG && key.startsWith("xlink:");
209
+ const isXmlns = elementIsSVG && key.startsWith("xmlns:");
210
+ const isBoolean2 = shared.isSpecialBooleanAttr(key) || shared.isBooleanAttr(key);
211
+ if (prev === next2) {
314
212
  return;
315
213
  }
316
- if (!node || node.nodeType === Node.DOCUMENT_NODE) {
214
+ if (key.length > 2 && key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110) {
215
+ return;
216
+ }
217
+ const lowerKey = key.toLowerCase();
218
+ if (lowerKey === "innerhtml" || lowerKey === "srcdoc") {
317
219
  {
318
- shared.warn("[Key System] Cannot set key on invalid node");
220
+ shared.warn(`${key} updates are ignored by patchAttr`);
319
221
  }
320
222
  return;
321
223
  }
322
- const normalizedKey = normalizeKey(key);
323
- if (shared.isFalsy(normalizedKey)) {
324
- delete node[NODE_KEY_SYMBOL];
325
- } else {
326
- node[NODE_KEY_SYMBOL] = normalizedKey;
224
+ if (next2 == null) {
225
+ if (isXlink) {
226
+ el.removeAttributeNS(XLINK_NAMESPACE, key.slice(6));
227
+ } else if (isXmlns) {
228
+ const localName = key.slice(6);
229
+ el.removeAttributeNS(XMLNS_NAMESPACE, localName);
230
+ } else {
231
+ el.removeAttribute(key);
232
+ }
233
+ return;
327
234
  }
328
- }
329
- function getNodeKey(node) {
330
- if (!node) return void 0;
331
- return isComponent(node) ? node.key : node[NODE_KEY_SYMBOL];
332
- }
333
-
334
- // src/utils/node.ts
335
- function normalizeNode(node) {
336
- if (shared.isHTMLElement(node)) {
337
- return node;
235
+ if (isBoolean2) {
236
+ if (shared.includeBooleanAttr(next2)) {
237
+ el.setAttribute(key, "");
238
+ } else {
239
+ el.removeAttribute(key);
240
+ }
241
+ return;
338
242
  }
339
- if (shared.isPrimitive(node)) {
340
- const textContent = shared.isFalsy(node) ? "" : String(node);
341
- return document.createTextNode(textContent);
243
+ const attrValue = shared.isSymbol(next2) ? String(next2) : next2;
244
+ const isUrlAttr = lowerKey === "href" || lowerKey === "src" || lowerKey === "xlink:href" || lowerKey === "action" || lowerKey === "formaction" || lowerKey === "poster";
245
+ if (isUrlAttr && shared.isString(attrValue)) {
246
+ const v = attrValue.trim().toLowerCase();
247
+ if (v.startsWith("javascript:") || v.startsWith("data:")) {
248
+ return;
249
+ }
342
250
  }
343
- return node;
344
- }
345
- function isSameNode(a, b) {
346
- const keyA = getNodeKey(a);
347
- const keyB = getNodeKey(b);
348
- if (keyA !== keyB) {
349
- return false;
251
+ if (isXlink) {
252
+ el.setAttributeNS(XLINK_NAMESPACE, key, String(attrValue));
253
+ return;
350
254
  }
351
- const aIsComponent = isComponent(a);
352
- const bIsComponent = isComponent(b);
353
- if (aIsComponent && bIsComponent) {
354
- return a.component === b.component;
255
+ if (isXmlns) {
256
+ el.setAttributeNS(XMLNS_NAMESPACE, key, String(attrValue));
257
+ return;
355
258
  }
356
- if (aIsComponent !== bIsComponent) {
357
- return false;
259
+ if (elementIsSVG) {
260
+ el.setAttribute(key, String(attrValue));
261
+ } else {
262
+ if (key in el) {
263
+ try {
264
+ el[key] = attrValue;
265
+ } catch (e) {
266
+ el.setAttribute(key, String(attrValue));
267
+ }
268
+ } else {
269
+ el.setAttribute(key, String(attrValue));
270
+ }
271
+ }
272
+ }
273
+ function patchClass(el, prev, next2, isSVG = false) {
274
+ if (prev === next2) {
275
+ return;
358
276
  }
359
- if (shared.isPrimitive(a) || shared.isPrimitive(b)) {
360
- return a === b;
277
+ const normalizedNext = normalizeClass(next2);
278
+ if (!normalizedNext) {
279
+ el.removeAttribute("class");
280
+ return;
361
281
  }
362
- const aNode = a;
363
- const bNode = b;
364
- if (aNode.nodeType !== bNode.nodeType) {
365
- return false;
282
+ const normalizedPrev = shared.isString(prev) ? prev : normalizeClass(prev);
283
+ if (normalizedPrev === normalizedNext) {
284
+ return;
366
285
  }
367
- if (aNode.nodeType === Node.ELEMENT_NODE) {
368
- return aNode.tagName === bNode.tagName;
286
+ if (isSVG) {
287
+ el.setAttribute("class", normalizedNext);
288
+ } else {
289
+ el.className = normalizedNext;
369
290
  }
370
- return true;
371
291
  }
372
- function shallowCompare(a, b) {
373
- if (a === b) return true;
374
- if (shared.isNull(a) || shared.isNull(b)) return false;
375
- if (!shared.isObject(a) || !shared.isObject(b)) return false;
376
- if (shared.isArray(a) !== shared.isArray(b)) return false;
377
- const aRecord = a;
378
- const bRecord = b;
379
- const aKeys = Object.keys(aRecord);
380
- const bKeys = Object.keys(bRecord);
381
- if (aKeys.length !== bKeys.length) return false;
382
- for (const key of aKeys) {
383
- if (!(key in bRecord) || aRecord[key] !== bRecord[key]) {
384
- return false;
292
+ var normalizeClass = shared.normalizeClassName;
293
+ var importantRE = /\s*!important$/;
294
+ var prefixes = ["Webkit", "Moz", "ms"];
295
+ var prefixCache = {};
296
+ function patchStyle(el, prev, next2) {
297
+ const style = el.style;
298
+ if (next2 && shared.isString(next2)) {
299
+ if (prev !== next2) {
300
+ style.cssText = next2;
385
301
  }
302
+ return;
386
303
  }
387
- return true;
388
- }
389
- function removeNode(node) {
390
- if (!node) return;
391
- if (isComponent(node)) {
392
- node.destroy();
304
+ if (!next2) {
305
+ if (prev) {
306
+ el.removeAttribute("style");
307
+ }
393
308
  return;
394
309
  }
395
- const element = node;
396
- if (element.parentElement) {
397
- element.remove();
310
+ if (prev && !shared.isString(prev)) {
311
+ const prevObj = prev;
312
+ for (const key in prevObj) {
313
+ if (!next2 || next2[key] == null) {
314
+ setStyle(style, key, "");
315
+ }
316
+ }
317
+ } else if (prev && shared.isString(prev)) {
318
+ const declRE = /(?:^|;)\s*([a-z][a-z\d-]*)\s*:/gi;
319
+ let match;
320
+ while ((match = declRE.exec(prev)) !== null) {
321
+ const key = match[1].trim();
322
+ if (key && next2 && shared.isObject(next2) && next2[key] == null) {
323
+ setStyle(style, key, "");
324
+ }
325
+ }
326
+ }
327
+ if (next2 && !shared.isString(next2)) {
328
+ const nextObj = next2;
329
+ for (const key in nextObj) {
330
+ const value = nextObj[key];
331
+ if ((!prev || shared.isString(prev) || prev[key] !== value) && value != null) {
332
+ setStyle(style, key, value);
333
+ }
334
+ }
398
335
  }
399
336
  }
400
- function insertNode(parent, child, before) {
401
- if (!parent || !child) return;
402
- if (isComponent(child)) {
403
- const beforeNode2 = isComponent(before) ? before.firstChild : before;
404
- child.mount(parent, beforeNode2);
337
+ function setStyle(style, name, val) {
338
+ if (shared.isArray(val)) {
339
+ for (const element of val) {
340
+ setStyle(style, name, element);
341
+ }
405
342
  return;
406
343
  }
407
- const beforeNode = isComponent(before) ? before.firstChild : before;
408
- if (beforeNode) {
409
- parent.insertBefore(child, beforeNode);
410
- } else {
411
- parent.appendChild(child);
344
+ if (val == null || val === "") {
345
+ val = "";
412
346
  }
413
- }
414
- function replaceNode(parent, newNode, oldNode) {
415
- if (!parent || !newNode || !oldNode || newNode === oldNode) return;
416
- const beforeNode = isComponent(oldNode) ? oldNode.beforeNode : oldNode.nextSibling;
417
- removeNode(oldNode);
418
- insertNode(parent, newNode, beforeNode);
419
- }
420
- function getFirstDOMNode(node) {
421
- if (!node) {
347
+ if (name.startsWith("--")) {
348
+ style.setProperty(name, val);
422
349
  return;
423
350
  }
424
- if (isComponent(node)) {
425
- return node.firstChild;
426
- }
427
- if (shared.isPrimitive(node)) {
428
- return void 0;
351
+ const prefixed = autoPrefix(style, name);
352
+ if (shared.isString(val) && importantRE.test(val)) {
353
+ style.setProperty(shared.camelCase(prefixed), val.replace(importantRE, ""), "important");
354
+ } else {
355
+ style[prefixed] = val;
429
356
  }
430
- return node;
431
357
  }
432
- function transferKey(oldNode, newNode) {
433
- if (isComponent(oldNode) || isComponent(newNode)) {
434
- return;
358
+ function autoPrefix(style, rawName) {
359
+ const cached = prefixCache[rawName];
360
+ if (cached) {
361
+ return cached;
435
362
  }
436
- const oldKey = getNodeKey(oldNode);
437
- if (oldKey && !getNodeKey(newNode)) {
438
- setNodeKey(newNode, oldKey);
363
+ let name = shared.camelCase(rawName);
364
+ if (name !== "filter" && name in style) {
365
+ return prefixCache[rawName] = name;
366
+ }
367
+ name = shared.capitalize(name);
368
+ for (const prefix of prefixes) {
369
+ const prefixed = prefix + name;
370
+ if (prefixed in style) {
371
+ return prefixCache[rawName] = prefixed;
372
+ }
439
373
  }
374
+ return rawName;
440
375
  }
441
- function patch(parent, oldNode, newNode) {
442
- if (newNode === oldNode) {
443
- return oldNode;
444
- }
445
- const oldIsElement = shared.isHTMLElement(oldNode);
446
- const newIsElement = shared.isHTMLElement(newNode);
447
- if (newIsElement && oldIsElement) {
448
- if (newNode.isEqualNode(oldNode)) {
449
- return oldNode;
376
+
377
+ // src/hydration.ts
378
+ var _hydrationKey = 0;
379
+ function getHydrationKey() {
380
+ return String(_hydrationKey++);
381
+ }
382
+ function resetHydrationKey() {
383
+ _hydrationKey = 0;
384
+ }
385
+ var _isHydrating = false;
386
+ function isHydrating() {
387
+ return _isHydrating;
388
+ }
389
+ var _registry = /* @__PURE__ */ new Map();
390
+ function gatherHydratable(root) {
391
+ const nodes = root.querySelectorAll("[data-hk]");
392
+ for (const node of nodes) {
393
+ const key = node.dataset.hk;
394
+ if (key != null && !_registry.has(key)) {
395
+ _registry.set(key, node);
450
396
  }
451
- if (oldNode.tagName === newNode.tagName) {
452
- const oldAttrs = oldNode.attributes;
453
- const newAttrs = newNode.attributes;
454
- for (let i = oldAttrs.length - 1; i >= 0; i--) {
455
- const attrName = oldAttrs[i].name;
456
- if (!newNode.hasAttribute(attrName)) {
457
- oldNode.removeAttribute(attrName);
458
- }
459
- }
460
- for (let i = 0, len = newAttrs.length; i < len; i++) {
461
- const attr = newAttrs[i];
462
- if (oldNode.getAttribute(attr.name) !== attr.value) {
463
- oldNode.setAttribute(attr.name, attr.value);
464
- }
397
+ }
398
+ }
399
+ var _teleportCallsiteAnchors = [];
400
+ var _teleportTargetStarts = /* @__PURE__ */ new Map();
401
+ function gatherTeleportAnchors() {
402
+ if (typeof document === "undefined") return;
403
+ const walker = document.createNodeIterator(document.body, NodeFilter.SHOW_COMMENT);
404
+ let node;
405
+ while (node = walker.nextNode()) {
406
+ const data = node.data;
407
+ if (data === "teleport-anchor") {
408
+ _teleportCallsiteAnchors.push(node);
409
+ } else if (data === "teleport-start") {
410
+ const parent = node.parentElement;
411
+ if (!parent) continue;
412
+ let bucket = _teleportTargetStarts.get(parent);
413
+ if (!bucket) {
414
+ bucket = [];
415
+ _teleportTargetStarts.set(parent, bucket);
465
416
  }
466
- transferKey(oldNode, newNode);
467
- return oldNode;
417
+ bucket.push(node);
468
418
  }
469
419
  }
470
- if (shared.isTextNode(oldNode) && shared.isTextNode(newNode)) {
471
- if (oldNode.textContent !== newNode.textContent) {
472
- oldNode.textContent = newNode.textContent;
420
+ }
421
+ function consumeTeleportAnchor() {
422
+ var _a2;
423
+ return (_a2 = _teleportCallsiteAnchors.shift()) != null ? _a2 : null;
424
+ }
425
+ function consumeTeleportBlock(target) {
426
+ const bucket = _teleportTargetStarts.get(target);
427
+ const start = bucket == null ? void 0 : bucket.shift();
428
+ if (!start) return null;
429
+ const nodes = [];
430
+ let cursor = start.nextSibling;
431
+ while (cursor) {
432
+ if (cursor.nodeType === Node.COMMENT_NODE && cursor.data === "teleport-end") {
433
+ return { start, end: cursor, nodes };
473
434
  }
474
- transferKey(oldNode, newNode);
475
- return oldNode;
435
+ nodes.push(cursor);
436
+ cursor = cursor.nextSibling;
476
437
  }
477
- const oldIsComponent = isComponent(oldNode);
478
- const newIsComponent = isComponent(newNode);
479
- if (oldIsComponent && newIsComponent) {
480
- if (oldNode.component === newNode.component) {
481
- return newNode.update(oldNode);
482
- }
438
+ {
439
+ shared.warn("[Portal] hydration: orphaned <!--teleport-start--> without matching <!--teleport-end-->");
483
440
  }
484
- replaceNode(parent, newNode, oldNode);
485
- return newNode;
441
+ return null;
486
442
  }
487
- function patchChildren(parent, oldChildren, newChildren, anchor) {
488
- const oldLength = oldChildren.length;
489
- const newLength = newChildren.length;
490
- if (oldLength === 0 && newLength === 0) {
491
- return [];
443
+ function beginHydration(root) {
444
+ _isHydrating = true;
445
+ _hydrationKey = 0;
446
+ _registry.clear();
447
+ _teleportCallsiteAnchors.length = 0;
448
+ _teleportTargetStarts.clear();
449
+ gatherHydratable(root);
450
+ gatherTeleportAnchors();
451
+ }
452
+ function endHydration() {
453
+ _isHydrating = false;
454
+ _registry.clear();
455
+ _teleportCallsiteAnchors.length = 0;
456
+ _teleportTargetStarts.clear();
457
+ }
458
+ function getRenderedElement(html) {
459
+ if (!shared.isBrowser()) {
460
+ return () => {
461
+ throw new Error("[essor] getRenderedElement called in non-browser environment");
462
+ };
492
463
  }
464
+ let _csrFactory = null;
465
+ return () => {
466
+ if (!_isHydrating) {
467
+ if (!_csrFactory) _csrFactory = template(html);
468
+ return _csrFactory();
469
+ }
470
+ const key = getHydrationKey();
471
+ const node = _registry.get(key);
472
+ if (node) {
473
+ _registry.delete(key);
474
+ return node;
475
+ }
476
+ shared.warn(`[essor] hydration mismatch: no SSR element for key "${key}"`);
477
+ if (!_csrFactory) _csrFactory = template(html);
478
+ return _csrFactory();
479
+ };
480
+ }
481
+ function patchClassHydrate(el, prev, next2, isSVG) {
482
+ if (_isHydrating) return;
483
+ patchClass(el, prev, next2, isSVG);
484
+ }
485
+ function patchAttrHydrate(el, key, prev, next2) {
486
+ if (_isHydrating) return;
487
+ patchAttr(el, key, prev, next2);
488
+ }
489
+ function patchStyleHydrate(el, prev, next2) {
490
+ if (_isHydrating) return;
491
+ patchStyle(el, prev, next2);
492
+ }
493
+
494
+ // src/reconcile.ts
495
+ function resolveInsertAnchor(parent, candidate) {
496
+ return candidate && candidate.parentNode === parent ? candidate : null;
497
+ }
498
+ function reconcileArrays(parent, oldNodes, newNodes, anchor) {
499
+ const fallbackAnchor = resolveInsertAnchor(parent, anchor);
500
+ const oldLength = oldNodes.length;
501
+ const newLength = newNodes.length;
502
+ if (oldLength === 0 && newLength === 0) return newNodes;
493
503
  if (oldLength === 0) {
494
504
  for (let i = 0; i < newLength; i++) {
495
- insertNode(parent, newChildren[i], anchor);
505
+ insertNode(parent, newNodes[i], fallbackAnchor);
496
506
  }
497
- return newChildren;
507
+ return newNodes;
498
508
  }
499
509
  if (newLength === 0) {
500
510
  for (let i = 0; i < oldLength; i++) {
501
- removeNode(oldChildren[i]);
511
+ removeNode(oldNodes[i]);
502
512
  }
503
513
  return [];
504
514
  }
505
- if (oldLength === 1 && newLength === 1) {
506
- const oldNode = oldChildren[0];
507
- const newNode = newChildren[0];
508
- if (isSameNode(oldNode, newNode)) {
509
- patch(parent, oldNode, newNode);
510
- newChildren[0] = oldNode;
511
- } else {
512
- replaceNode(parent, newNode, oldNode);
513
- }
514
- return newChildren;
515
- }
516
- if (oldLength === 2 && newLength === 2) {
517
- const o0 = oldChildren[0];
518
- const o1 = oldChildren[1];
519
- const n0 = newChildren[0];
520
- const n1 = newChildren[1];
521
- if (isSameNode(o0, n0) && isSameNode(o1, n1)) {
522
- patch(parent, o0, n0);
523
- patch(parent, o1, n1);
524
- newChildren[0] = o0;
525
- newChildren[1] = o1;
526
- return newChildren;
527
- }
528
- if (isSameNode(o0, n1) && isSameNode(o1, n0)) {
529
- patch(parent, o0, n1);
530
- patch(parent, o1, n0);
531
- const dom1 = getFirstDOMNode(o1);
532
- const dom0 = getFirstDOMNode(o0);
533
- if (dom1 && dom0 && dom1.parentNode === parent) {
534
- parent.insertBefore(dom1, dom0);
535
- }
536
- newChildren[0] = o1;
537
- newChildren[1] = o0;
538
- return newChildren;
539
- }
540
- }
541
- return patchKeyedChildren(parent, oldChildren, newChildren, anchor);
542
- }
543
- function patchKeyedChildren(parent, oldChildren, newChildren, anchor) {
544
- let oldStartIdx = 0;
545
- let newStartIdx = 0;
546
- let oldEndIdx = oldChildren.length - 1;
547
- let newEndIdx = newChildren.length - 1;
548
- let oldStartNode = oldChildren[0];
549
- let oldEndNode = oldChildren[oldEndIdx];
550
- let newStartNode = newChildren[0];
551
- let newEndNode = newChildren[newEndIdx];
552
- while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
553
- if (!oldStartNode) {
554
- oldStartNode = oldChildren[++oldStartIdx];
555
- } else if (!oldEndNode) {
556
- oldEndNode = oldChildren[--oldEndIdx];
557
- } else if (isSameNode(oldStartNode, newStartNode)) {
558
- patch(parent, oldStartNode, newStartNode);
559
- newChildren[newStartIdx] = oldStartNode;
560
- oldStartNode = oldChildren[++oldStartIdx];
561
- newStartNode = newChildren[++newStartIdx];
515
+ let start = 0;
516
+ let oldEnd = oldLength - 1;
517
+ let newEnd = newLength - 1;
518
+ while (start <= oldEnd && start <= newEnd) {
519
+ if (oldNodes[start] === newNodes[start]) {
520
+ start++;
562
521
  } else {
563
522
  break;
564
523
  }
565
524
  }
566
- while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
567
- if (!oldStartNode) {
568
- oldStartNode = oldChildren[++oldStartIdx];
569
- } else if (!oldEndNode) {
570
- oldEndNode = oldChildren[--oldEndIdx];
571
- } else if (isSameNode(oldEndNode, newEndNode)) {
572
- patch(parent, oldEndNode, newEndNode);
573
- newChildren[newEndIdx] = oldEndNode;
574
- oldEndNode = oldChildren[--oldEndIdx];
575
- newEndNode = newChildren[--newEndIdx];
525
+ while (oldEnd >= start && newEnd >= start) {
526
+ if (oldNodes[oldEnd] === newNodes[newEnd]) {
527
+ oldEnd--;
528
+ newEnd--;
576
529
  } else {
577
530
  break;
578
531
  }
579
532
  }
580
- if (oldStartIdx > oldEndIdx) {
581
- if (newStartIdx <= newEndIdx) {
582
- const anchorNode = newEndIdx + 1 < newChildren.length ? getFirstDOMNode(newChildren[newEndIdx + 1]) : anchor;
583
- for (let i = newStartIdx; i <= newEndIdx; i++) {
584
- insertNode(parent, newChildren[i], anchorNode);
533
+ if (start > oldEnd) {
534
+ if (start <= newEnd) {
535
+ const nextPos = newEnd + 1;
536
+ const nextNode = resolveInsertAnchor(
537
+ parent,
538
+ nextPos < newLength ? newNodes[nextPos] : fallbackAnchor
539
+ );
540
+ for (let i = start; i <= newEnd; i++) {
541
+ insertNode(parent, newNodes[i], nextNode);
585
542
  }
586
543
  }
587
- } else if (newStartIdx > newEndIdx) {
588
- for (let i = oldStartIdx; i <= oldEndIdx; i++) {
589
- const node = oldChildren[i];
590
- if (node) {
591
- removeNode(node);
592
- }
544
+ } else if (start > newEnd) {
545
+ for (let i = start; i <= oldEnd; i++) {
546
+ removeNode(oldNodes[i]);
593
547
  }
594
548
  } else {
595
- patchUnknownSequence(
596
- parent,
597
- oldChildren,
598
- newChildren,
599
- oldStartIdx,
600
- oldEndIdx,
601
- newStartIdx,
602
- newEndIdx,
603
- anchor
604
- );
549
+ reconcileUnknownSequence(parent, oldNodes, newNodes, start, oldEnd, newEnd, fallbackAnchor);
605
550
  }
606
- return newChildren;
551
+ return newNodes;
607
552
  }
608
- function patchUnknownSequence(parent, oldChildren, newChildren, oldStartIdx, oldEndIdx, newStartIdx, newEndIdx, anchor) {
609
- const newLength = newEndIdx - newStartIdx + 1;
610
- let keyToNewIndexMap;
611
- for (let i = newStartIdx; i <= newEndIdx; i++) {
612
- const key = getNodeKey(newChildren[i]);
613
- if (key !== void 0) {
614
- if (!keyToNewIndexMap) {
615
- keyToNewIndexMap = /* @__PURE__ */ Object.create(null);
616
- }
617
- keyToNewIndexMap[key] = i;
618
- }
553
+ function reconcileUnknownSequence(parent, oldNodes, newNodes, start, oldEnd, newEnd, anchor) {
554
+ const newLength = newEnd - start + 1;
555
+ const newIndexMap = /* @__PURE__ */ new Map();
556
+ for (let i = start; i <= newEnd; i++) {
557
+ newIndexMap.set(newNodes[i], i);
619
558
  }
620
559
  const newIndexToOldIndexMap = new Int32Array(newLength);
560
+ newIndexToOldIndexMap.fill(0);
561
+ let patched = 0;
621
562
  let moved = false;
622
563
  let maxNewIndexSoFar = 0;
623
- let patched = 0;
624
- for (let i = oldStartIdx; i <= oldEndIdx; i++) {
625
- const oldNode = oldChildren[i];
626
- if (!oldNode) continue;
564
+ for (let i = start; i <= oldEnd; i++) {
565
+ const oldNode = oldNodes[i];
627
566
  if (patched >= newLength) {
628
567
  removeNode(oldNode);
629
568
  continue;
630
569
  }
631
- let newIndex;
632
- const oldKey = getNodeKey(oldNode);
633
- if (oldKey !== void 0 && keyToNewIndexMap && oldKey in keyToNewIndexMap) {
634
- newIndex = keyToNewIndexMap[oldKey];
635
- } else {
636
- for (let j2 = newStartIdx; j2 <= newEndIdx; j2++) {
637
- if (newIndexToOldIndexMap[j2 - newStartIdx] === 0 && oldKey === void 0 && getNodeKey(newChildren[j2]) === void 0 && isSameNode(oldNode, newChildren[j2])) {
638
- newIndex = j2;
639
- break;
640
- }
641
- }
642
- }
570
+ const newIndex = newIndexMap.get(oldNode);
643
571
  if (newIndex === void 0) {
644
572
  removeNode(oldNode);
645
573
  } else {
646
- newIndexToOldIndexMap[newIndex - newStartIdx] = i + 1;
574
+ newIndexToOldIndexMap[newIndex - start] = i + 1;
647
575
  if (newIndex >= maxNewIndexSoFar) {
648
576
  maxNewIndexSoFar = newIndex;
649
577
  } else {
650
578
  moved = true;
651
579
  }
652
- patch(parent, oldNode, newChildren[newIndex]);
653
- newChildren[newIndex] = oldNode;
654
580
  patched++;
655
581
  }
656
582
  }
657
583
  const increasingNewIndexSequence = moved ? getSequence(newIndexToOldIndexMap) : [];
658
584
  let j = increasingNewIndexSequence.length - 1;
659
- let cachedAnchor = anchor;
660
585
  for (let i = newLength - 1; i >= 0; i--) {
661
- const nextIndex = newStartIdx + i;
662
- const nextNode = newChildren[nextIndex];
586
+ const nextIndex = start + i;
587
+ const nextNode = newNodes[nextIndex];
588
+ const anchorNode = resolveInsertAnchor(
589
+ parent,
590
+ nextIndex + 1 < newNodes.length ? newNodes[nextIndex + 1] : anchor
591
+ );
663
592
  if (newIndexToOldIndexMap[i] === 0) {
664
- insertNode(parent, nextNode, cachedAnchor);
665
- cachedAnchor = getFirstDOMNode(nextNode) || cachedAnchor;
593
+ insertNode(parent, nextNode, anchorNode);
666
594
  } else if (moved) {
667
595
  if (j < 0 || i !== increasingNewIndexSequence[j]) {
668
- const domNode = getFirstDOMNode(nextNode);
669
- if (domNode && domNode.parentNode === parent) {
670
- insertNode(parent, domNode, cachedAnchor);
671
- }
672
- cachedAnchor = domNode || cachedAnchor;
596
+ insertNode(parent, nextNode, anchorNode);
673
597
  } else {
674
- cachedAnchor = getFirstDOMNode(nextNode) || cachedAnchor;
675
598
  j--;
676
599
  }
677
- } else {
678
- cachedAnchor = getFirstDOMNode(nextNode) || cachedAnchor;
679
600
  }
680
601
  }
681
602
  }
682
603
  function getSequence(arr) {
604
+ const p = new Int32Array(arr.length);
605
+ const result = [0];
683
606
  const len = arr.length;
684
- if (len === 0) return [];
685
- if (len === 1) return arr[0] !== 0 ? [0] : [];
686
- const result = [];
687
- const p = new Int32Array(len);
688
607
  let i;
689
608
  let j;
690
609
  let u;
@@ -694,7 +613,7 @@ function getSequence(arr) {
694
613
  const arrI = arr[i];
695
614
  if (arrI !== 0) {
696
615
  j = result[result.length - 1];
697
- if (result.length === 0 || arr[j] < arrI) {
616
+ if (arr[j] < arrI) {
698
617
  p[i] = j;
699
618
  result.push(i);
700
619
  continue;
@@ -726,348 +645,385 @@ function getSequence(arr) {
726
645
  return result;
727
646
  }
728
647
 
729
- // src/binding.ts
730
- function addEventListener(element, event, handler, options) {
731
- element.addEventListener(event, handler, options);
732
- onCleanup(() => {
733
- element.removeEventListener(event, handler, options);
734
- });
735
- }
736
- function bindElement(node, key, defaultValue, setter) {
737
- if (shared.isHtmlInputElement(node)) {
738
- bindInputElement(node, setter);
739
- } else if (shared.isHtmlSelectElement(node)) {
740
- bindSelectElement(node, setter);
741
- } else if (shared.isHtmlTextAreaElement(node)) {
742
- addEventListener(node, "input", () => {
743
- setter(node.value);
744
- });
648
+ // src/dom.ts
649
+ function removeNode(node) {
650
+ if (!node) return;
651
+ if (isComponent(node)) {
652
+ node.destroy();
653
+ } else {
654
+ const element = node;
655
+ if (element.parentNode) {
656
+ element.remove();
657
+ }
745
658
  }
746
659
  }
747
- function bindInputElement(node, setter) {
748
- switch (node.type) {
749
- case "checkbox":
750
- addEventListener(node, "change", () => {
751
- setter(Boolean(node.checked));
752
- });
753
- break;
754
- case "radio":
755
- addEventListener(node, "change", () => {
756
- setter(node.checked ? node.value : "");
757
- });
758
- break;
759
- case "file":
760
- addEventListener(node, "change", () => {
761
- setter(node.files);
762
- });
763
- break;
764
- case "number":
765
- case "range":
766
- addEventListener(node, "input", () => {
767
- setter(node.value || "");
768
- });
769
- break;
770
- case "date":
771
- case "datetime-local":
772
- case "month":
773
- case "time":
774
- case "week":
775
- addEventListener(node, "change", () => {
776
- setter(node.value || "");
777
- });
778
- break;
779
- default:
780
- addEventListener(node, "input", () => {
781
- setter(node.value);
782
- });
783
- break;
660
+ function insertNode(parent, child2, before) {
661
+ if (!parent || !child2) return;
662
+ const beforeNode = isComponent(before) ? before.firstChild : before;
663
+ if (isComponent(child2)) {
664
+ child2.mount(parent, beforeNode);
665
+ return;
784
666
  }
785
- }
786
- function bindSelectElement(node, setter) {
787
- addEventListener(node, "change", () => {
788
- if (node.multiple) {
789
- const values = Array.from(node.options).filter((option) => option.selected).map((option) => option.value);
790
- setter(values);
791
- } else {
792
- setter(node.value);
667
+ if (beforeNode) {
668
+ parent.insertBefore(child2, beforeNode);
669
+ } else {
670
+ {
671
+ if (!child2) {
672
+ shared.error("insertNode: child is not a Node", child2);
673
+ }
793
674
  }
794
- });
675
+ parent.appendChild(child2);
676
+ }
677
+ }
678
+ function normalizeNode(node) {
679
+ if (shared.isHTMLElement(node)) {
680
+ return node;
681
+ }
682
+ if (shared.isPrimitive(node)) {
683
+ return document.createTextNode(shared.isFalsy(node) ? "" : String(node));
684
+ }
685
+ return node;
795
686
  }
796
687
  function insert(parent, nodeFactory, before) {
797
688
  if (!parent) return;
689
+ const ownerScope = getActiveScope();
798
690
  let renderedNodes = [];
799
- const currentScope = getActiveScope();
800
- const cleanup = signals.effect(() => {
801
- const run = () => {
691
+ let isFirstRun = true;
692
+ const resolveNodes = (raw) => {
693
+ if (raw instanceof Node) return [raw];
694
+ if (shared.isNull(raw) || shared.isUndefined(raw) || shared.isString(raw) || shared.isNumber(raw) || shared.isBoolean(raw)) {
695
+ return [normalizeNode(raw)];
696
+ }
697
+ return shared.coerceArray(raw).map((item) => shared.isFunction(item) ? item() : item).flatMap((i) => i).map(normalizeNode);
698
+ };
699
+ const effectRunner = signals.effect(() => {
700
+ const executeUpdate = () => {
802
701
  const rawNodes = shared.isFunction(nodeFactory) ? nodeFactory() : nodeFactory;
803
- const nodes = shared.coerceArray(rawNodes).map((item) => shared.isFunction(item) ? item() : item).flatMap(normalizeNode);
804
- renderedNodes = patchChildren(parent, renderedNodes, nodes, before);
702
+ const nodes = resolveNodes(rawNodes);
703
+ if (isFirstRun && isHydrating() && nodes.every((node) => node instanceof Node && node.parentNode === parent)) {
704
+ renderedNodes = nodes;
705
+ isFirstRun = false;
706
+ return;
707
+ }
708
+ renderedNodes = reconcileArrays(parent, renderedNodes, nodes, before);
709
+ isFirstRun = false;
805
710
  };
806
- if (currentScope) {
807
- runWithScope(currentScope, run);
711
+ if (ownerScope && !ownerScope.isDestroyed) {
712
+ runWithScope(ownerScope, executeUpdate);
808
713
  } else {
809
- run();
714
+ executeUpdate();
810
715
  }
811
716
  });
812
717
  onCleanup(() => {
813
- cleanup();
814
- renderedNodes.forEach((node) => removeNode(node));
815
- renderedNodes.length = 0;
718
+ effectRunner.stop();
719
+ for (const node of renderedNodes) removeNode(node);
720
+ renderedNodes = [];
816
721
  });
817
722
  return renderedNodes;
818
723
  }
819
- function mapNodes(template2, indexes) {
820
- const len = indexes.length;
821
- const tree = new Array(len);
822
- const indexSet = new Set(indexes);
823
- let index = 1;
824
- let found = 0;
825
- const walk = (node) => {
826
- if (node.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {
827
- if (indexSet.has(index)) {
828
- tree[found++] = node;
829
- if (found === len) return true;
830
- }
831
- index++;
832
- }
833
- let child = node.firstChild;
834
- while (child) {
835
- if (walk(child)) return true;
836
- child = child.nextSibling;
837
- }
838
- return false;
839
- };
840
- walk(template2);
841
- return tree;
724
+ function child(node) {
725
+ return (node == null ? void 0 : node.firstChild) || null;
842
726
  }
843
-
844
- // src/component.ts
845
- var _a;
846
- _a = NORMAL_COMPONENT;
847
- var Component = class {
848
- constructor(component, props = {}) {
849
- this.component = component;
850
- this.props = props;
851
- // Component rendered nodes (supports arrays and fragments)
852
- this.renderedNodes = [];
853
- // Component scope (unified context management)
854
- this.scope = null;
855
- // Component parent node
856
- this.parentNode = void 0;
857
- // Component before node
858
- this.beforeNode = void 0;
859
- // Component props (reactive and snapshot)
860
- this.reactiveProps = {};
861
- this._propSnapshots = {};
862
- // Component lifecycle state
863
- this.state = 0 /* INITIAL */;
864
- // Parent scope captured at construction time for correct hierarchy
865
- this.parentScope = null;
866
- // @ts-ignore
867
- this[_a] = true;
868
- this.key = props.key ? normalizeKey(props.key) : getComponentKey(component);
869
- this.reactiveProps = signals.shallowReactive(__spreadValues({}, props));
870
- this.parentScope = getActiveScope();
871
- for (const key in props) {
872
- const val = props[key];
873
- if (shared.isObject(val)) {
874
- this._propSnapshots[key] = shared.isArray(val) ? [...val] : __spreadValues({}, val);
875
- }
876
- }
727
+ function next(node, step = 1) {
728
+ while (node && step > 0) {
729
+ node = node.nextSibling;
730
+ step--;
877
731
  }
878
- get isConnected() {
879
- return this.state === 2 /* MOUNTED */;
732
+ return node || null;
733
+ }
734
+ function nthChild(node, index) {
735
+ if (!node || index < 0) return null;
736
+ let current = node.firstChild;
737
+ while (current && index > 0) {
738
+ current = current.nextSibling;
739
+ index--;
880
740
  }
881
- get firstChild() {
882
- for (const node of this.renderedNodes) {
883
- const dom = getFirstDOMNode(node);
884
- if (dom) return dom;
885
- }
886
- return void 0;
741
+ return current || null;
742
+ }
743
+
744
+ // src/operations/event.ts
745
+ function addEvent(el, event, handler, options) {
746
+ if (!(options == null ? void 0 : options.delegate)) {
747
+ el.addEventListener(event, handler, options);
748
+ return () => el.removeEventListener(event, handler, options);
887
749
  }
888
- mount(parentNode, beforeNode) {
889
- var _a2, _b;
890
- this.parentNode = parentNode;
891
- this.beforeNode = beforeNode;
892
- this.state = 1 /* MOUNTING */;
893
- if (this.renderedNodes.length > 0) {
894
- for (const node of this.renderedNodes) {
895
- insertNode(parentNode, node, beforeNode);
896
- }
897
- this.state = 2 /* MOUNTED */;
898
- return this.renderedNodes;
899
- }
900
- const parentScope = (_a2 = this.parentScope) != null ? _a2 : getActiveScope();
901
- this.scope = createScope(parentScope);
902
- setActiveScope(this.scope);
903
- let result = this.component(this.reactiveProps);
904
- if (shared.isFunction(result)) {
905
- result = result(this.reactiveProps);
906
- }
907
- if (signals.isSignal(result) || signals.isComputed(result)) {
908
- result = result.value;
750
+ const selector = options.delegate;
751
+ const wrappedHandler = (e) => {
752
+ const target = e.target;
753
+ if (target.matches(selector) || target.closest(selector)) {
754
+ handler.call(el, e);
909
755
  }
910
- const renderedNodes = (_b = insert(parentNode, result, beforeNode)) != null ? _b : [];
911
- this.renderedNodes = renderedNodes;
912
- this.applyProps(this.props);
913
- this.state = 2 /* MOUNTED */;
914
- triggerMountHooks(this.scope);
915
- return this.renderedNodes;
916
- }
917
- update(prevNode) {
918
- if (this.key !== prevNode.key) {
919
- this.mount(prevNode.parentNode, prevNode.beforeNode);
920
- return this;
921
- }
922
- this.parentNode = prevNode.parentNode;
923
- this.beforeNode = prevNode.beforeNode;
924
- this.scope = prevNode.scope;
925
- this.parentScope = prevNode.parentScope;
926
- this.renderedNodes = prevNode.renderedNodes;
927
- this.state = prevNode.state;
928
- this.reactiveProps = prevNode.reactiveProps;
929
- this._propSnapshots = prevNode._propSnapshots;
930
- this._updateReactiveProps(this.props);
931
- if (!this.isConnected && this.parentNode) {
932
- this.mount(this.parentNode, this.beforeNode);
933
- return this;
934
- }
935
- if (this.scope) {
936
- setActiveScope(this.scope);
937
- this.applyProps(this.props);
938
- triggerUpdateHooks(this.scope);
939
- }
940
- return this;
756
+ };
757
+ const _a2 = options, { delegate: _ } = _a2, nativeOptions = __objRest(_a2, ["delegate"]);
758
+ el.addEventListener(event, wrappedHandler, nativeOptions);
759
+ return () => {
760
+ el.removeEventListener(event, wrappedHandler, nativeOptions);
761
+ };
762
+ }
763
+ function registerScopedHook(scope, listKey, hook) {
764
+ let hookList = scope[listKey];
765
+ if (!hookList) {
766
+ hookList = [];
767
+ scope[listKey] = hookList;
941
768
  }
942
- /**
943
- * Update reactive props by comparing with current values
944
- */
945
- _updateReactiveProps(props) {
946
- for (const key in props) {
947
- if (key === "key") continue;
948
- const newValue = props[key];
949
- const oldValue = this.reactiveProps[key];
950
- if (newValue === oldValue && !this._propSnapshots[key]) continue;
951
- const isNewValueObject = shared.isObject(newValue);
952
- if (isNewValueObject) {
953
- const snapshot = this._propSnapshots[key];
954
- if (snapshot && shallowCompare(newValue, snapshot)) continue;
955
- const newSnapshot = shared.isArray(newValue) ? [...newValue] : __spreadValues({}, newValue);
956
- this.reactiveProps[key] = newSnapshot;
957
- this._propSnapshots[key] = newSnapshot;
958
- } else {
959
- if (shared.hasChanged(newValue, oldValue)) {
960
- this.reactiveProps[key] = newValue;
961
- if (this._propSnapshots[key]) {
962
- delete this._propSnapshots[key];
769
+ hookList.push(hook);
770
+ }
771
+ function executeHooks(hooks, scopeId2, phase) {
772
+ const len = hooks.length;
773
+ if (len === 0) return;
774
+ let pending;
775
+ for (let i = 0; i < len; i++) {
776
+ try {
777
+ const result = hooks[i]();
778
+ if (shared.isPromise(result)) {
779
+ const safePromise = result.catch((error_) => {
780
+ if (true) {
781
+ shared.error(`Scope(${scopeId2}): Async ${phase} hook rejected:`, error_);
963
782
  }
964
- }
783
+ });
784
+ (pending || (pending = [])).push(safePromise);
785
+ }
786
+ } catch (error_) {
787
+ {
788
+ shared.error(`Scope(${scopeId2}): Error in ${phase} hook:`, error_);
965
789
  }
966
790
  }
967
791
  }
968
- unwrapRenderResult(result) {
969
- if (shared.isFunction(result)) {
970
- result = result(this.reactiveProps);
971
- }
972
- if (signals.isSignal(result) || signals.isComputed(result)) {
973
- result = result.value;
974
- }
975
- if (isComponent(result)) {
976
- result = result.mount(this.parentNode, this.beforeNode);
977
- }
978
- if (shared.isPromise(result)) {
979
- result = result.then((r) => this.unwrapRenderResult(r));
980
- }
981
- return result;
792
+ if (!pending) return;
793
+ return Promise.all(pending).then(() => {
794
+ });
795
+ }
796
+ function onMount(hook) {
797
+ const scope = getActiveScope();
798
+ if (!scope) {
799
+ shared.error("onMount() must be called within a scope");
800
+ return;
982
801
  }
983
- forceUpdate() {
984
- if (this.state === 5 /* DESTROYED */ || !this.parentNode || !this.scope) {
985
- return;
986
- }
987
- const originalNodes = [...this.renderedNodes];
802
+ if (scope.isMounted) {
988
803
  try {
989
- runWithScope(this.scope, () => {
990
- let result = this.component(this.reactiveProps);
991
- if (shared.isFunction(result)) {
992
- result = result(this.reactiveProps);
993
- }
994
- if (signals.isSignal(result) || signals.isComputed(result)) {
995
- result = result.value;
996
- }
997
- const newNodes = shared.coerceArray(result);
998
- const anchor = this._getAnchorNode();
999
- if (!this.parentNode) return;
1000
- for (const node of this.renderedNodes) {
1001
- removeNode(node);
1002
- }
1003
- for (const node of newNodes) {
1004
- insertNode(this.parentNode, node, anchor);
1005
- }
1006
- this.renderedNodes = newNodes;
1007
- });
1008
- if (this.scope) {
1009
- triggerUpdateHooks(this.scope);
804
+ const result = hook();
805
+ if (shared.isPromise(result)) {
806
+ result.catch((error_) => {
807
+ if (true) shared.error(`Scope(${scope.id}): Async mount hook rejected:`, error_);
808
+ });
1010
809
  }
1011
- } catch (error8) {
1012
- this.renderedNodes = originalNodes;
1013
- throw error8;
810
+ } catch (error_) {
811
+ shared.error(`Scope(${scope.id}): Error in mount hook:`, error_);
812
+ }
813
+ return;
814
+ }
815
+ registerScopedHook(scope, "onMount", hook);
816
+ }
817
+ function onUpdate(hook) {
818
+ const scope = getActiveScope();
819
+ if (!scope) {
820
+ shared.error("onUpdate() must be called within a scope");
821
+ return;
822
+ }
823
+ registerScopedHook(scope, "onUpdate", hook);
824
+ }
825
+ function onDestroy(hook) {
826
+ const scope = getActiveScope();
827
+ if (!scope) {
828
+ shared.error("onDestroy() must be called within a scope");
829
+ return;
830
+ }
831
+ registerScopedHook(scope, "onDestroy", hook);
832
+ }
833
+ function triggerMountHooks(scope) {
834
+ if (scope.isDestroyed) {
835
+ return;
836
+ }
837
+ if (!scope.onMount || scope.onMount.length === 0) {
838
+ scope.isMounted = true;
839
+ return;
840
+ }
841
+ const mountHooks = scope.onMount;
842
+ const result = runWithScope(scope, () => executeHooks(mountHooks, scope.id, "mount"));
843
+ mountHooks.length = 0;
844
+ scope.isMounted = true;
845
+ return result;
846
+ }
847
+ function triggerUpdateHooks(scope) {
848
+ if (scope.isDestroyed || !scope.onUpdate || scope.onUpdate.length === 0) return;
849
+ return runWithScope(scope, () => executeHooks(scope.onUpdate, scope.id, "update"));
850
+ }
851
+
852
+ // src/component.ts
853
+ function syncDescriptors(target, source, pruneMissing = false) {
854
+ const seen = pruneMissing ? /* @__PURE__ */ new Set() : null;
855
+ for (const key of Object.getOwnPropertyNames(source)) {
856
+ seen == null ? void 0 : seen.add(key);
857
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
858
+ }
859
+ if (seen) {
860
+ for (const key of Object.getOwnPropertyNames(target)) {
861
+ if (!seen.has(key)) delete target[key];
1014
862
  }
1015
863
  }
864
+ }
865
+ function readProp(source, key) {
866
+ const descriptor = Object.getOwnPropertyDescriptor(source, key);
867
+ return descriptor.get ? descriptor.get.call(source) : descriptor.value;
868
+ }
869
+ var _a;
870
+ _a = "normal" /* NORMAL */;
871
+ var Component = class {
872
+ constructor(component, props = {}) {
873
+ this.component = component;
874
+ this.props = props;
875
+ this[_a] = true;
876
+ this.scope = null;
877
+ this.state = 0 /* INITIAL */;
878
+ this.beforeNode = void 0;
879
+ this.renderedNodes = [];
880
+ this.firstChild = void 0;
881
+ this.parentNode = void 0;
882
+ this.rootEventCleanups = [];
883
+ this.parentScope = getActiveScope();
884
+ const container = {};
885
+ syncDescriptors(container, props);
886
+ this.reactiveProps = signals.shallowReactive(container);
887
+ }
1016
888
  /**
1017
- * Get anchor node for insertion
889
+ * Mount the component into `parentNode` (optionally before `beforeNode`).
890
+ * If already rendered, the existing DOM is re-inserted without re-running
891
+ * the component function.
1018
892
  */
1019
- _getAnchorNode() {
1020
- if (this.beforeNode) return this.beforeNode;
893
+ mount(parentNode, beforeNode) {
894
+ var _a2;
895
+ this.parentNode = parentNode;
896
+ this.beforeNode = beforeNode;
897
+ this.state = 1 /* MOUNTING */;
1021
898
  if (this.renderedNodes.length > 0) {
1022
- const lastNode = this.renderedNodes[this.renderedNodes.length - 1];
1023
- const lastDom = getFirstDOMNode(lastNode);
1024
- if (lastDom) {
1025
- return lastDom.nextSibling;
899
+ for (const node of this.renderedNodes) {
900
+ insertNode(parentNode, node, beforeNode);
1026
901
  }
902
+ this.state = 2 /* MOUNTED */;
903
+ return this.renderedNodes;
1027
904
  }
1028
- return void 0;
905
+ const scope = createScope((_a2 = this.parentScope) != null ? _a2 : getActiveScope());
906
+ this.scope = scope;
907
+ const renderedNodes = runWithScope(scope, () => {
908
+ var _a3;
909
+ let result = this.component(this.reactiveProps);
910
+ if (shared.isFunction(result)) {
911
+ result = result(this.reactiveProps);
912
+ }
913
+ if (signals.isSignal(result) || signals.isComputed(result)) {
914
+ result = result.value;
915
+ }
916
+ return (_a3 = insert(parentNode, result, beforeNode)) != null ? _a3 : [];
917
+ });
918
+ this.renderedNodes = renderedNodes;
919
+ this.firstChild = renderedNodes[0];
920
+ this.syncSpecialProps(this.props);
921
+ this.state = 2 /* MOUNTED */;
922
+ triggerMountHooks(scope);
923
+ return this.renderedNodes;
924
+ }
925
+ /**
926
+ * Re-install props into the same `reactiveProps` container (preserving
927
+ * any closures already holding a reference to it) and re-apply
928
+ * refs/events against the current root element.
929
+ */
930
+ update(props) {
931
+ this.props = props;
932
+ const scope = this.scope;
933
+ if (!scope || scope.isDestroyed) return;
934
+ syncDescriptors(
935
+ this.reactiveProps,
936
+ props != null ? props : {},
937
+ /* pruneMissing */
938
+ true
939
+ );
940
+ this.syncSpecialProps(props);
941
+ triggerUpdateHooks(scope);
1029
942
  }
1030
943
  /**
1031
- * Destroy component
944
+ * Tear down and re-mount the component at its current insertion point.
945
+ * No-op if the component has never been mounted.
946
+ */
947
+ forceUpdate() {
948
+ if (!this.parentNode) return;
949
+ const parent = this.parentNode;
950
+ const before = this.beforeNode;
951
+ this.destroy();
952
+ this.mount(parent, before);
953
+ }
954
+ /**
955
+ * Dispose the scope, remove all rendered nodes, and clear bookkeeping.
956
+ * Idempotent: subsequent calls are no-ops.
1032
957
  */
1033
958
  destroy() {
1034
- if (this.state === 4 /* DESTROYING */ || this.state === 5 /* DESTROYED */) {
1035
- return;
1036
- }
1037
- this.state = 4 /* DESTROYING */;
1038
- for (const node of this.renderedNodes) {
1039
- removeNode(node);
1040
- }
1041
959
  const scope = this.scope;
1042
- if (scope) {
1043
- disposeScope(scope);
1044
- this.scope = null;
1045
- }
960
+ if (!scope || scope.isDestroyed) return;
961
+ this.scope = null;
962
+ this.releaseSpecialProps();
963
+ disposeScope(scope);
964
+ for (const node of this.renderedNodes) removeNode(node);
1046
965
  this.renderedNodes = [];
966
+ this.firstChild = void 0;
1047
967
  this.parentNode = void 0;
1048
- this.beforeNode = void 0;
1049
- this.parentScope = null;
1050
- this.reactiveProps = {};
1051
- this.props = {};
1052
- this.state = 5 /* DESTROYED */;
1053
968
  }
1054
- applyProps(props) {
969
+ /**
970
+ * Apply props that bind to the root DOM element rather than flowing into
971
+ * the component body: `ref` (signal/function) and `onXxx` event handlers.
972
+ * The render-facing `reactiveProps` already has those keys; here we just
973
+ * wire them to the actual DOM node.
974
+ */
975
+ syncSpecialProps(props) {
1055
976
  if (!props) return;
1056
- const firstElement = this.firstChild;
1057
- for (const [propName, propValue] of Object.entries(props)) {
1058
- if (shared.startsWith(propName, EVENT_PREFIX)) {
1059
- if (!firstElement || !shared.isHTMLElement(firstElement)) return;
1060
- const eventName = propName.slice(EVENT_PREFIX.length).toLowerCase();
1061
- addEventListener(firstElement, eventName, propValue);
1062
- } else if (propName === REF_KEY && signals.isSignal(propValue)) {
1063
- propValue.value = firstElement;
977
+ const root = this.firstChild;
978
+ if (!root) return;
979
+ this.releaseSpecialProps();
980
+ for (const key of Object.getOwnPropertyNames(props)) {
981
+ const value = readProp(props, key);
982
+ if (key === REF_KEY) {
983
+ this.rootRefCleanup = this.bindRootRef(value, root);
984
+ continue;
985
+ }
986
+ if (shared.isOn(key) && shared.isFunction(value)) {
987
+ const eventName = key.slice(2).toLowerCase();
988
+ this.rootEventCleanups.push(addEvent(root, eventName, value));
1064
989
  }
1065
990
  }
1066
- this.props = props;
991
+ }
992
+ /**
993
+ * Remove all listeners/ref bindings currently attached to the root element.
994
+ */
995
+ releaseSpecialProps() {
996
+ for (const cleanup of this.rootEventCleanups) {
997
+ cleanup();
998
+ }
999
+ this.rootEventCleanups.length = 0;
1000
+ if (this.rootRefCleanup) {
1001
+ this.rootRefCleanup();
1002
+ this.rootRefCleanup = void 0;
1003
+ }
1004
+ }
1005
+ /**
1006
+ * Bind the root ref prop and return a cleanup that restores the previous ref state.
1007
+ */
1008
+ bindRootRef(value, root) {
1009
+ if (shared.isFunction(value)) {
1010
+ value(root);
1011
+ return () => value(null);
1012
+ }
1013
+ if (signals.isSignal(value)) {
1014
+ const previousValue = value.value;
1015
+ value.value = root;
1016
+ return () => {
1017
+ if (value.value === root) {
1018
+ value.value = previousValue;
1019
+ }
1020
+ };
1021
+ }
1022
+ return void 0;
1067
1023
  }
1068
1024
  };
1069
1025
  function isComponent(node) {
1070
- return !!node && !!node[NORMAL_COMPONENT];
1026
+ return !!node && !!node["normal" /* NORMAL */];
1071
1027
  }
1072
1028
  function createComponent(componentFn, props) {
1073
1029
  if (isComponent(componentFn)) {
@@ -1093,17 +1049,72 @@ function template(html) {
1093
1049
  function createApp(component, target) {
1094
1050
  const container = shared.isString(target) ? document.querySelector(target) : target;
1095
1051
  if (!container) {
1096
- shared.error(`Target element not found: ${target}`);
1052
+ {
1053
+ shared.warn(`Target element not found: ${target}`);
1054
+ }
1097
1055
  return;
1098
1056
  }
1099
- const existingContext = container.innerHTML;
1100
- if (existingContext) {
1101
- shared.error(`Target element is not empty, it will be delete: ${target}`);
1057
+ const existingContent = container.innerHTML;
1058
+ if (existingContent) {
1059
+ {
1060
+ shared.warn(`Target element is not empty, it will be cleared: ${target}`);
1061
+ }
1102
1062
  container.innerHTML = "";
1103
1063
  }
1104
- const rootComponent = isComponent(component) ? component : createComponent(component);
1105
- rootComponent.mount(container);
1106
- return rootComponent;
1064
+ const scope = createScope();
1065
+ let rootNode;
1066
+ try {
1067
+ runWithScope(scope, () => {
1068
+ const mountedRoot = createComponent(component);
1069
+ if (isComponent(mountedRoot)) {
1070
+ rootNode = mountedRoot;
1071
+ insertNode(container, mountedRoot);
1072
+ }
1073
+ });
1074
+ } catch (error_) {
1075
+ disposeScope(scope);
1076
+ throw error_;
1077
+ }
1078
+ return {
1079
+ root: rootNode,
1080
+ unmount: () => {
1081
+ disposeScope(scope);
1082
+ rootNode == null ? void 0 : rootNode.destroy();
1083
+ }
1084
+ };
1085
+ }
1086
+ function hydrate(component, target) {
1087
+ const container = shared.isString(target) ? document.querySelector(target) : target;
1088
+ if (!container) {
1089
+ {
1090
+ shared.warn(`[essor] hydrate: target element not found: ${target}`);
1091
+ }
1092
+ return;
1093
+ }
1094
+ beginHydration(container);
1095
+ const scope = createScope();
1096
+ let rootNode;
1097
+ try {
1098
+ runWithScope(scope, () => {
1099
+ const mountedRoot = createComponent(component);
1100
+ if (isComponent(mountedRoot)) {
1101
+ rootNode = mountedRoot;
1102
+ insert(container, mountedRoot);
1103
+ }
1104
+ });
1105
+ } catch (error_) {
1106
+ disposeScope(scope);
1107
+ throw error_;
1108
+ } finally {
1109
+ endHydration();
1110
+ }
1111
+ return {
1112
+ root: rootNode,
1113
+ unmount: () => {
1114
+ disposeScope(scope);
1115
+ rootNode == null ? void 0 : rootNode.destroy();
1116
+ }
1117
+ };
1107
1118
  }
1108
1119
  function provide(key, value) {
1109
1120
  const scope = getActiveScope();
@@ -1129,68 +1140,66 @@ function inject(key, defaultValue) {
1129
1140
  let current = scope;
1130
1141
  while (current) {
1131
1142
  if (current.provides) {
1132
- const value = current.provides.get(key);
1133
- if (value) {
1134
- return value;
1143
+ if (current.provides.has(key)) {
1144
+ return current.provides.get(key);
1135
1145
  }
1136
1146
  }
1137
1147
  current = current.parent;
1138
1148
  }
1139
1149
  return defaultValue;
1140
1150
  }
1141
- function reTarget(event, value) {
1142
- Object.defineProperty(event, "target", {
1151
+ function reTargetEvent(e, value) {
1152
+ Object.defineProperty(e, "target", {
1143
1153
  configurable: true,
1144
1154
  value
1145
1155
  });
1146
1156
  }
1147
- function handleNodeEvent(node, event, key) {
1148
- const handler = node[`_$${key}`];
1149
- if (handler && shared.isFunction(handler) && !node.disabled) {
1150
- const data = node[`${key}Data`];
1151
- data ? handler.call(node, data, event) : handler.call(node, event);
1152
- if (event.cancelBubble) return false;
1153
- }
1154
- if (node.host && !shared.isString(node.host) && !node.host._$host && shared.isFunction(node.contains) && node.contains(event.target)) {
1155
- reTarget(event, node.host);
1156
- }
1157
- return true;
1158
- }
1159
- function walkUpTree(startNode, event, key) {
1160
- let node = startNode;
1161
- while (handleNodeEvent(node, event, key) && (node = node._$host || node.parentNode || node.host)) ;
1162
- return node;
1163
- }
1164
- function eventHandler(event) {
1165
- let node = event.target;
1166
- const key = `${event.type}`;
1167
- const oriTarget = event.target;
1168
- const oriCurrentTarget = event.currentTarget;
1169
- Object.defineProperty(event, "currentTarget", {
1157
+ function eventHandler(e) {
1158
+ let node = e.target;
1159
+ const key = e.type;
1160
+ const oriTarget = e.target;
1161
+ const oriCurrentTarget = e.currentTarget;
1162
+ const handleNode = () => {
1163
+ const handler = node[`_$${key}`];
1164
+ if (handler && shared.isFunction(handler) && !node.disabled) {
1165
+ const data = node[`${key}Data`];
1166
+ data ? handler.call(node, data, e) : handler.call(node, e);
1167
+ if (e.cancelBubble) return false;
1168
+ }
1169
+ if (node.host && !shared.isString(node.host) && !node.host._$host && shared.isFunction(node.contains) && node.contains(e.target)) {
1170
+ reTargetEvent(e, node.host);
1171
+ }
1172
+ return true;
1173
+ };
1174
+ const walkUpTree = () => {
1175
+ while (handleNode() && (node = node._$host || node.parentNode || node.host)) ;
1176
+ };
1177
+ Object.defineProperty(e, "currentTarget", {
1170
1178
  configurable: true,
1179
+ /**
1180
+ * Returns the current delegated target for the event.
1181
+ */
1171
1182
  get() {
1172
1183
  return node || document;
1173
1184
  }
1174
1185
  });
1175
- if (event.composedPath) {
1176
- const path = event.composedPath();
1177
- reTarget(event, path[0]);
1186
+ if (e.composedPath) {
1187
+ const path = e.composedPath();
1188
+ reTargetEvent(e, path[0]);
1178
1189
  for (let i = 0; i < path.length - 2; i++) {
1179
1190
  node = path[i];
1180
- if (!handleNodeEvent(node, event, key)) break;
1191
+ if (!handleNode()) break;
1181
1192
  if (node._$host) {
1182
1193
  node = node._$host;
1183
- node = walkUpTree(node, event, key);
1194
+ walkUpTree();
1184
1195
  break;
1185
1196
  }
1186
1197
  if (node.parentNode === oriCurrentTarget) {
1187
1198
  break;
1188
1199
  }
1189
1200
  }
1190
- } else {
1191
- node = walkUpTree(node, event, key);
1192
- }
1193
- reTarget(event, oriTarget);
1201
+ } else walkUpTree();
1202
+ reTargetEvent(e, oriTarget);
1194
1203
  }
1195
1204
  var $EVENTS = /* @__PURE__ */ Symbol("_$EVENTS");
1196
1205
  function delegateEvents(eventNames, document2 = window.document) {
@@ -1203,424 +1212,354 @@ function delegateEvents(eventNames, document2 = window.document) {
1203
1212
  }
1204
1213
  }
1205
1214
  }
1206
-
1207
- // src/utils/props.ts
1208
- function omitProps(target, keys) {
1209
- const excludeSet = new Set(keys);
1210
- return new Proxy(target, {
1211
- // Intercept property reads
1212
- get(obj, prop) {
1213
- if (excludeSet.has(prop)) {
1214
- return void 0;
1215
- }
1216
- return Reflect.get(obj, prop);
1217
- },
1218
- // Intercept property enumeration (for...in, Object.keys, etc.)
1219
- ownKeys(obj) {
1220
- return Reflect.ownKeys(obj).filter((key) => !excludeSet.has(key));
1221
- },
1222
- // Intercept property descriptor retrieval
1223
- getOwnPropertyDescriptor(obj, prop) {
1224
- if (excludeSet.has(prop)) {
1225
- return void 0;
1226
- }
1227
- return Reflect.getOwnPropertyDescriptor(obj, prop);
1228
- },
1229
- // Intercept the 'in' operator
1230
- has(obj, prop) {
1231
- if (excludeSet.has(prop)) {
1232
- return false;
1233
- }
1234
- return Reflect.has(obj, prop);
1235
- }
1236
- });
1237
- }
1238
-
1239
- // src/hydration/shared.ts
1240
- var isHydrationActive = false;
1241
- function startHydration() {
1242
- isHydrationActive = true;
1243
- }
1244
- function endHydration() {
1245
- isHydrationActive = false;
1246
- }
1247
- function isHydrating() {
1248
- return isHydrationActive;
1249
- }
1250
- var hydrationCounter = 0;
1251
- function getHydrationKey() {
1252
- return `${hydrationCounter++}`;
1253
- }
1254
- function resetHydrationKey() {
1255
- hydrationCounter = 0;
1256
- }
1257
-
1258
- // src/hydration/hydration.ts
1259
- var DATA_IDX_REGEX = /^\d+-\d+$/;
1260
- function getRenderedElement(temp) {
1261
- return () => {
1262
- if (!shared.isBrowser()) {
1263
- return null;
1264
- }
1265
- const key = getHydrationKey();
1266
- const node = document.querySelector(`[data-hk="${key}"]`);
1267
- if (node) {
1268
- return node;
1269
- }
1270
- return template(temp)();
1271
- };
1272
- }
1273
- function mapSSRNodes(templateEl, idx) {
1274
- const hk = templateEl.dataset.hk;
1275
- if (!hk) {
1276
- return mapNodes(templateEl, idx);
1277
- }
1278
- const nodesList = [];
1279
- const elements = templateEl.querySelectorAll(`[data-idx^="${hk}"]`);
1280
- if (elements.length > 0) {
1281
- nodesList.push(
1282
- ...Array.from(elements).filter((item) => {
1283
- const idxAttr = item.dataset.idx;
1284
- return idxAttr !== null && DATA_IDX_REGEX.test(idxAttr);
1285
- }).map((item) => {
1286
- const idxAttr = item.dataset.idx || "";
1287
- const [hkPart, idxPart] = idxAttr.split("-");
1288
- return {
1289
- hk: hkPart,
1290
- idx: idxPart,
1291
- node: item
1292
- };
1293
- })
1294
- );
1295
- }
1296
- const commentNodes = [];
1297
- const walkNodes = (node) => {
1298
- if (node.nodeType === Node.COMMENT_NODE && node.textContent && DATA_IDX_REGEX.test(node.textContent)) {
1299
- const [hkPart, idxPart] = node.textContent.split("-");
1300
- commentNodes.push({
1301
- hk: hkPart,
1302
- idx: idxPart,
1303
- node
1304
- });
1305
- }
1306
- let child = node.firstChild;
1307
- while (child) {
1308
- walkNodes(child);
1309
- child = child.nextSibling;
1310
- }
1311
- };
1312
- walkNodes(templateEl);
1313
- nodesList.push(...commentNodes);
1314
- const nodes = [templateEl];
1315
- idx.forEach((indexValue) => {
1316
- const node = nodesList.find((item) => item.idx === String(indexValue));
1317
- if (node) {
1318
- nodes.push(node.node);
1319
- }
1320
- });
1321
- return nodes;
1322
- }
1323
- function hydrate(component, container) {
1324
- startHydration();
1325
- resetHydrationKey();
1326
- try {
1327
- const rootElement = shared.isString(container) ? document.querySelector(container) : container;
1328
- if (!rootElement) {
1329
- shared.error("Hydration error: Root element not found");
1330
- return void 0;
1331
- }
1332
- const rootComponent = createComponent(component);
1333
- rootComponent.mount(rootElement);
1334
- endHydration();
1335
- return rootComponent;
1336
- } catch (error_) {
1337
- shared.error("Hydration error:", error_);
1338
- endHydration();
1339
- return void 0;
1340
- }
1341
- }
1342
- function patchClass(el, prev, next, isSVG = false) {
1343
- if (prev === next) {
1344
- return;
1345
- }
1346
- if (isHydrating()) {
1347
- return;
1348
- }
1349
- const normalizedNext = normalizeClass(next);
1350
- const normalizedPrev = normalizeClass(prev);
1351
- if (normalizedNext && normalizedPrev === normalizedNext) {
1352
- return;
1353
- }
1354
- if (!normalizedNext) {
1355
- el.removeAttribute("class");
1356
- } else if (isSVG) {
1357
- el.setAttribute("class", normalizedNext);
1358
- } else {
1359
- el.className = normalizedNext;
1360
- }
1361
- }
1362
- function normalizeClass(value) {
1363
- return shared.normalizeClassName(value);
1364
- }
1365
- var importantRE = /\s*!important$/;
1366
- var prefixes = ["Webkit", "Moz", "ms"];
1367
- var prefixCache = {};
1368
- function patchStyle(el, prev, next) {
1369
- const style = el.style;
1370
- const isCssString = shared.isString(next);
1371
- if (isHydrating()) {
1372
- return;
1373
- }
1374
- if (next && isCssString) {
1375
- if (prev !== next) {
1376
- style.cssText = next;
1377
- }
1378
- return;
1379
- }
1380
- if (!next) {
1381
- if (prev) {
1382
- el.removeAttribute("style");
1383
- }
1384
- return;
1385
- }
1386
- if (prev && !shared.isString(prev)) {
1387
- for (const key in prev) {
1388
- if (!next || next[key] == null) {
1389
- setStyle(style, key, "");
1390
- }
1391
- }
1392
- } else if (prev && shared.isString(prev)) {
1393
- const prevStyles = prev.split(";");
1394
- for (const stylePart of prevStyles) {
1395
- const colonIndex = stylePart.indexOf(":");
1396
- if (colonIndex > 0) {
1397
- const key = stylePart.slice(0, colonIndex).trim();
1398
- if (next && shared.isObject(next) && next[key] == null) {
1399
- setStyle(style, key, "");
1400
- }
1401
- }
1402
- }
1403
- }
1404
- if (next && !shared.isString(next)) {
1405
- for (const key in next) {
1406
- const value = next[key];
1407
- if ((!prev || shared.isString(prev) || prev[key] !== value) && value != null) {
1408
- setStyle(style, key, value);
1409
- }
1410
- }
1411
- }
1412
- }
1413
- function setStyle(style, name, val) {
1414
- if (shared.isArray(val)) {
1415
- for (const element of val) {
1416
- setStyle(style, name, element);
1215
+ function clearDelegatedEvents(document2 = window.document) {
1216
+ const docWithEvents = document2;
1217
+ const eventSet = docWithEvents[$EVENTS];
1218
+ if (eventSet) {
1219
+ for (const name of eventSet.keys()) {
1220
+ document2.removeEventListener(name, eventHandler);
1417
1221
  }
1418
- return;
1419
- }
1420
- if (val == null || val === "") {
1421
- val = "";
1422
- }
1423
- if (name.startsWith("--")) {
1424
- style.setProperty(name, val);
1425
- return;
1426
- }
1427
- const prefixed = autoPrefix(style, name);
1428
- if (shared.isString(val) && importantRE.test(val)) {
1429
- style.setProperty(shared.camelCase(prefixed), val.replace(importantRE, ""), "important");
1430
- } else {
1431
- style[prefixed] = val;
1222
+ delete docWithEvents[$EVENTS];
1432
1223
  }
1433
1224
  }
1434
- function autoPrefix(style, rawName) {
1435
- const cached = prefixCache[rawName];
1436
- if (cached) {
1437
- return cached;
1438
- }
1439
- let name = shared.camelCase(rawName);
1440
- if (name !== "filter" && name in style) {
1441
- return prefixCache[rawName] = name;
1442
- }
1443
- name = shared.capitalize(name);
1444
- for (const prefix of prefixes) {
1445
- const prefixed = prefix + name;
1446
- if (prefixed in style) {
1447
- return prefixCache[rawName] = prefixed;
1448
- }
1225
+ function addEventListener(element, event, handler, options) {
1226
+ const cleanup = addEvent(element, event, handler, options);
1227
+ if (getActiveScope()) {
1228
+ onCleanup(cleanup);
1449
1229
  }
1450
- return rawName;
1451
1230
  }
1452
- function patchAttr(el, key, prev, next) {
1453
- if (key === KEY_PROP) {
1454
- if (next == null) {
1455
- setNodeKey(el, void 0);
1456
- } else {
1457
- setNodeKey(el, String(next));
1458
- }
1459
- return;
1460
- }
1461
- if (key === SPREAD_NAME) {
1462
- {
1463
- if (!shared.isObject(next)) {
1464
- shared.warn("spread attribute must be an object");
1465
- }
1466
- }
1467
- Object.keys(next).forEach((k) => {
1468
- patchAttr(el, k, prev == null ? void 0 : prev[k], next == null ? void 0 : next[k]);
1469
- });
1470
- return;
1471
- }
1472
- if (isHydrating()) {
1473
- return;
1474
- }
1475
- const elementIsSVG = (el == null ? void 0 : el.namespaceURI) === SVG_NAMESPACE;
1476
- const isXlink = elementIsSVG && key.startsWith("xlink:");
1477
- const isXmlns = elementIsSVG && key.startsWith("xmlns:");
1478
- const isBoolean = shared.isSpecialBooleanAttr(key) || shared.isBooleanAttr(key);
1479
- if (prev === next) {
1480
- return;
1231
+
1232
+ // src/binding.ts
1233
+ var INPUT_CHECKBOX_CHECKED = {
1234
+ event: "change",
1235
+ forceChangeEvent: true,
1236
+ read: (n) => n.checked,
1237
+ write: (n, v) => {
1238
+ const el = n;
1239
+ const next2 = Boolean(v);
1240
+ if (el.checked !== next2) el.checked = next2;
1481
1241
  }
1482
- const lowerKey = key.toLowerCase();
1483
- if (lowerKey.length > 2 && lowerKey.charCodeAt(0) === 111 && lowerKey.charCodeAt(1) === 110) {
1484
- return;
1242
+ };
1243
+ var INPUT_RADIO_CHECKED = {
1244
+ event: "change",
1245
+ forceChangeEvent: true,
1246
+ read: (n) => {
1247
+ const el = n;
1248
+ return el.checked ? el.value : "";
1249
+ },
1250
+ write: (n, v) => {
1251
+ const el = n;
1252
+ const next2 = String(v) === el.value;
1253
+ if (el.checked !== next2) el.checked = next2;
1485
1254
  }
1486
- if (lowerKey === "innerhtml") {
1487
- return;
1255
+ };
1256
+ var INPUT_FILE_FILES = {
1257
+ event: "change",
1258
+ forceChangeEvent: true,
1259
+ read: (n) => n.files,
1260
+ // Browsers do not allow programmatic writes to <input type="file">.
1261
+ write: () => {
1488
1262
  }
1489
- if (next == null) {
1490
- if (isXlink) {
1491
- el.removeAttributeNS(XLINK_NAMESPACE, key.slice(6));
1492
- } else if (isXmlns) {
1493
- const localName = key.slice(6);
1494
- el.removeAttributeNS(XMLNS_NAMESPACE, localName);
1263
+ };
1264
+ var INPUT_VALUE = {
1265
+ event: "input",
1266
+ needsComposition: true,
1267
+ read: (n) => n.value,
1268
+ write: (n, v) => {
1269
+ const el = n;
1270
+ const next2 = v == null ? "" : String(v);
1271
+ if (el.value !== next2) el.value = next2;
1272
+ }
1273
+ };
1274
+ var SELECT_VALUE = {
1275
+ event: "change",
1276
+ forceChangeEvent: true,
1277
+ read: (n) => {
1278
+ const s = n;
1279
+ return s.multiple ? Array.from(s.selectedOptions, (o) => o.value) : s.value;
1280
+ },
1281
+ write: (n, v) => {
1282
+ const s = n;
1283
+ if (s.multiple) {
1284
+ const set = new Set((Array.isArray(v) ? v : []).map(String));
1285
+ for (const opt of Array.from(s.options)) opt.selected = set.has(opt.value);
1495
1286
  } else {
1496
- el.removeAttribute(key);
1287
+ const next2 = v == null ? "" : String(v);
1288
+ if (s.value !== next2) s.value = next2;
1497
1289
  }
1498
- return;
1499
1290
  }
1500
- if (isXlink) {
1501
- el.setAttributeNS(XLINK_NAMESPACE, key, String(next));
1502
- return;
1503
- }
1504
- if (isXmlns) {
1505
- el.setAttributeNS(XMLNS_NAMESPACE, key, String(next));
1506
- return;
1291
+ };
1292
+ var TEXTAREA_VALUE = {
1293
+ event: "input",
1294
+ needsComposition: true,
1295
+ read: (n) => n.value,
1296
+ write: (n, v) => {
1297
+ const el = n;
1298
+ const next2 = v == null ? "" : String(v);
1299
+ if (el.value !== next2) el.value = next2;
1507
1300
  }
1508
- if (isBoolean) {
1509
- if (shared.includeBooleanAttr(next)) {
1510
- el.setAttribute(key, "");
1511
- } else {
1512
- el.removeAttribute(key);
1301
+ };
1302
+ function resolveStrategy(node, prop) {
1303
+ const tag = node.nodeName;
1304
+ if (tag === "INPUT") {
1305
+ const type = node.type;
1306
+ if (prop === "checked") {
1307
+ return type === "radio" ? INPUT_RADIO_CHECKED : INPUT_CHECKBOX_CHECKED;
1308
+ }
1309
+ if (prop === "files") return INPUT_FILE_FILES;
1310
+ return INPUT_VALUE;
1311
+ }
1312
+ if (tag === "SELECT") return SELECT_VALUE;
1313
+ if (tag === "TEXTAREA") return TEXTAREA_VALUE;
1314
+ return {
1315
+ event: "input",
1316
+ read: (n) => n[prop],
1317
+ write: (n, v) => {
1318
+ n[prop] = v;
1513
1319
  }
1514
- return;
1320
+ };
1321
+ }
1322
+ function castValue(val, trim, number) {
1323
+ if (!shared.isString(val)) return val;
1324
+ if (trim) val = val.trim();
1325
+ if (number && val !== "") {
1326
+ const parsed = Number(val);
1327
+ if (!Number.isNaN(parsed)) return parsed;
1515
1328
  }
1516
- const attrValue = shared.isSymbol(next) ? String(next) : next;
1517
- const isUrlAttr = lowerKey === "href" || lowerKey === "src" || lowerKey === "xlink:href";
1518
- if (isUrlAttr && shared.isString(attrValue)) {
1519
- const v = attrValue.trim().toLowerCase();
1520
- if (v.startsWith("javascript:") || v.startsWith("data:")) {
1329
+ return val;
1330
+ }
1331
+ function isFocused(node) {
1332
+ const root = node.getRootNode();
1333
+ return (root instanceof Document || root instanceof ShadowRoot) && root.activeElement === node;
1334
+ }
1335
+ function bindElement(node, prop, getter, setter, modifiers = {}) {
1336
+ if (!node) return;
1337
+ const strategy = resolveStrategy(node, prop);
1338
+ const { trim, number, lazy } = modifiers;
1339
+ const isFiles = prop === "files";
1340
+ const readModel = () => shared.isFunction(getter) ? getter() : getter;
1341
+ const transform = (v) => isFiles ? v : castValue(v, trim, number);
1342
+ const eventName = lazy || strategy.forceChangeEvent ? "change" : strategy.event;
1343
+ let composing = false;
1344
+ const syncFromDom = () => {
1345
+ if (composing) return;
1346
+ const raw = strategy.read(node);
1347
+ if (raw === void 0) return;
1348
+ if (isFiles) {
1349
+ setter(raw);
1521
1350
  return;
1522
1351
  }
1352
+ const next2 = transform(raw);
1353
+ if (!Object.is(readModel(), next2)) {
1354
+ setter(next2);
1355
+ }
1356
+ };
1357
+ addEventListener(node, eventName, syncFromDom);
1358
+ if (!lazy && !isFiles && (trim || number) && eventName !== "change") {
1359
+ addEventListener(node, "change", () => {
1360
+ strategy.write(node, transform(strategy.read(node)));
1361
+ });
1523
1362
  }
1524
- if (elementIsSVG) {
1525
- el.setAttribute(key, String(attrValue));
1526
- } else {
1527
- if (key in el) {
1528
- try {
1529
- el[key] = attrValue;
1530
- } catch (e) {
1531
- el.setAttribute(key, String(attrValue));
1532
- }
1533
- } else {
1534
- el.setAttribute(key, String(attrValue));
1363
+ if (strategy.needsComposition && !lazy) {
1364
+ addEventListener(node, "compositionstart", () => {
1365
+ composing = true;
1366
+ });
1367
+ addEventListener(node, "compositionend", () => {
1368
+ if (!composing) return;
1369
+ composing = false;
1370
+ syncFromDom();
1371
+ });
1372
+ }
1373
+ const runner = signals.effect(() => {
1374
+ const value = readModel();
1375
+ if (strategy.needsComposition && !lazy && isFocused(node)) {
1376
+ if (composing) return;
1377
+ const current = transform(strategy.read(node));
1378
+ if (Object.is(current, value)) return;
1535
1379
  }
1380
+ strategy.write(node, value);
1381
+ });
1382
+ if (getActiveScope()) {
1383
+ onCleanup(() => runner.stop());
1536
1384
  }
1537
1385
  }
1538
1386
 
1539
- // src/operations/event.ts
1540
- function addEvent(el, event, handler, options) {
1541
- if (!(options == null ? void 0 : options.delegate)) {
1542
- el.addEventListener(event, handler, options);
1543
- return () => el.removeEventListener(event, handler, options);
1544
- }
1545
- const selector = options.delegate;
1546
- const wrappedHandler = (e) => {
1547
- const target = e.target;
1548
- if (target.matches(selector) || target.closest(selector)) {
1549
- handler.call(el, e);
1387
+ // src/utils.ts
1388
+ function omitProps(target, keys) {
1389
+ const excludeSet = new Set(keys);
1390
+ return new Proxy(target, {
1391
+ /**
1392
+ * Returns a property unless it is excluded by the proxy.
1393
+ */
1394
+ get(obj, prop) {
1395
+ if (excludeSet.has(prop)) {
1396
+ return void 0;
1397
+ }
1398
+ return Reflect.get(obj, prop);
1399
+ },
1400
+ /**
1401
+ * Returns the enumerable keys that are not excluded from the proxy.
1402
+ */
1403
+ ownKeys(obj) {
1404
+ return Reflect.ownKeys(obj).filter((key) => !excludeSet.has(key));
1405
+ },
1406
+ /**
1407
+ * Returns the property descriptor unless the key is excluded.
1408
+ */
1409
+ getOwnPropertyDescriptor(obj, prop) {
1410
+ if (excludeSet.has(prop)) {
1411
+ return void 0;
1412
+ }
1413
+ return Reflect.getOwnPropertyDescriptor(obj, prop);
1414
+ },
1415
+ /**
1416
+ * Returns whether the requested value exists.
1417
+ */
1418
+ has(obj, prop) {
1419
+ if (excludeSet.has(prop)) {
1420
+ return false;
1421
+ }
1422
+ return Reflect.has(obj, prop);
1550
1423
  }
1551
- };
1552
- const cleanOptions = __spreadValues({}, options);
1553
- cleanOptions.delegate = void 0;
1554
- el.addEventListener(event, wrappedHandler, cleanOptions);
1555
- return () => {
1556
- el.removeEventListener(event, wrappedHandler, cleanOptions);
1557
- };
1424
+ });
1558
1425
  }
1426
+
1427
+ // src/components/Fragment.ts
1559
1428
  function Fragment(props) {
1560
- {
1561
- if (!props) {
1562
- shared.error("Fragment component requires props");
1563
- return null;
1564
- }
1565
- }
1566
- if (!(props == null ? void 0 : props.children)) {
1567
- shared.error("Fragment component requires children");
1568
- return null;
1569
- }
1570
- const { children } = props;
1571
- return children;
1429
+ if (!props || props.children == null) return null;
1430
+ return props.children;
1572
1431
  }
1573
1432
  Fragment[FRAGMENT_COMPONENT] = true;
1574
1433
  function isFragment(node) {
1575
1434
  return !!node && !!node[FRAGMENT_COMPONENT];
1576
1435
  }
1436
+ function resolveTarget(props) {
1437
+ const raw = shared.isFunction(props.target) ? props.target() : props.target;
1438
+ if (raw == null) return null;
1439
+ if (shared.isString(raw)) return document.querySelector(raw);
1440
+ return raw;
1441
+ }
1442
+ function evalDisabled(props) {
1443
+ return shared.isFunction(props.disabled) ? !!props.disabled() : !!props.disabled;
1444
+ }
1577
1445
  function Portal(props) {
1446
+ if (isHydrating()) {
1447
+ const adopted = tryHydratePortal(props);
1448
+ if (adopted) return adopted;
1449
+ }
1578
1450
  const placeholder = document.createComment("portal");
1579
1451
  placeholder[PORTAL_COMPONENT] = true;
1580
- const children = props.children;
1581
- if (children) {
1582
- const childArray = shared.isArray(children) ? children : [children];
1583
- const nodes = [];
1584
- onMount(() => {
1585
- const targetElement = shared.isString(props.target) ? document.querySelector(props.target) : props.target;
1586
- if (!targetElement) {
1587
- if (true) {
1588
- shared.warn(`[Portal] Target element not found: ${props.target}`);
1589
- }
1590
- return;
1452
+ const { children } = props;
1453
+ if (children == null) return placeholder;
1454
+ const ownerScope = getActiveScope();
1455
+ let innerScope = null;
1456
+ const mountAt = (parent, before) => {
1457
+ innerScope = createScope(ownerScope);
1458
+ runWithScope(innerScope, () => {
1459
+ insert(parent, () => children, before);
1460
+ });
1461
+ };
1462
+ const teardown = () => {
1463
+ if (innerScope) {
1464
+ disposeScope(innerScope);
1465
+ innerScope = null;
1466
+ }
1467
+ };
1468
+ const apply = (disabled, target) => {
1469
+ teardown();
1470
+ if (disabled) {
1471
+ const parent = placeholder.parentNode;
1472
+ if (!parent) return;
1473
+ mountAt(parent, placeholder);
1474
+ return;
1475
+ }
1476
+ if (!target) {
1477
+ {
1478
+ shared.warn(`[Portal] Target element not found: ${String(props.target)}`);
1591
1479
  }
1592
- childArray.forEach((child) => {
1593
- if (child != null) {
1594
- const normalized = normalizeNode(child);
1595
- if (normalized) {
1596
- insertNode(targetElement, normalized);
1597
- nodes.push(normalized);
1598
- }
1599
- }
1600
- });
1601
- onCleanup(() => {
1602
- nodes.forEach((node) => {
1603
- if (!shared.isString(node) && node.parentNode === targetElement) {
1604
- targetElement.removeChild(node);
1605
- }
1606
- });
1607
- });
1480
+ return;
1481
+ }
1482
+ mountAt(target);
1483
+ };
1484
+ let mounted = false;
1485
+ const effectRunner = signals.effect(() => {
1486
+ const disabled = evalDisabled(props);
1487
+ const target = disabled ? null : resolveTarget(props);
1488
+ if (mounted) {
1489
+ apply(disabled, target);
1490
+ }
1491
+ });
1492
+ onMount(() => {
1493
+ mounted = true;
1494
+ const disabled = evalDisabled(props);
1495
+ const target = disabled ? null : resolveTarget(props);
1496
+ if (disabled || target) {
1497
+ apply(disabled, target);
1498
+ return;
1499
+ }
1500
+ queueMicrotask(() => {
1501
+ if (!placeholder.parentNode) return;
1502
+ apply(evalDisabled(props), resolveTarget(props));
1608
1503
  });
1609
- }
1504
+ });
1505
+ onCleanup(() => {
1506
+ effectRunner.stop();
1507
+ teardown();
1508
+ });
1610
1509
  return placeholder;
1611
1510
  }
1612
1511
  Portal[PORTAL_COMPONENT] = true;
1512
+ function tryHydratePortal(props) {
1513
+ if (evalDisabled(props)) return null;
1514
+ const anchor = consumeTeleportAnchor();
1515
+ if (!anchor) {
1516
+ {
1517
+ shared.warn("[Portal] hydration mismatch: no <!--teleport-anchor--> at call site.");
1518
+ }
1519
+ return null;
1520
+ }
1521
+ const target = resolveTarget(props);
1522
+ if (!target) {
1523
+ {
1524
+ shared.warn(`[Portal] hydration mismatch: target not found: ${String(props.target)}`);
1525
+ }
1526
+ return null;
1527
+ }
1528
+ const block = consumeTeleportBlock(target);
1529
+ if (!block) {
1530
+ {
1531
+ shared.warn(
1532
+ `[Portal] hydration mismatch: no <!--teleport-start--> in target ${String(props.target)}`
1533
+ );
1534
+ }
1535
+ return null;
1536
+ }
1537
+ anchor[PORTAL_COMPONENT] = true;
1538
+ return anchor;
1539
+ }
1613
1540
  function isPortal(node) {
1614
1541
  return !!node && !!node[PORTAL_COMPONENT];
1615
1542
  }
1543
+ function clearContainer(el) {
1544
+ while (el.firstChild) {
1545
+ el.removeChild(el.firstChild);
1546
+ }
1547
+ }
1548
+ function resolveNodeValue(value) {
1549
+ let current = value;
1550
+ while (shared.isFunction(current)) {
1551
+ current = current();
1552
+ }
1553
+ if (signals.isSignal(current) || signals.isComputed(current)) {
1554
+ return resolveNodeValue(current.value);
1555
+ }
1556
+ return current;
1557
+ }
1616
1558
  var SuspenseContext = /* @__PURE__ */ Symbol("SuspenseContext");
1617
1559
  function Suspense(props) {
1618
- if (shared.isUndefined(document)) {
1619
- const fallback = props.fallback;
1620
- if (fallback) {
1621
- return String(fallback || "");
1622
- }
1623
- return "";
1560
+ var _a2;
1561
+ if (!shared.isBrowser()) {
1562
+ return (_a2 = props.fallback) != null ? _a2 : "";
1624
1563
  }
1625
1564
  const container = document.createElement("div");
1626
1565
  container.style.display = "contents";
@@ -1628,19 +1567,42 @@ function Suspense(props) {
1628
1567
  let pendingCount = 0;
1629
1568
  let isShowingFallback = false;
1630
1569
  let resolvedChildren = null;
1631
- const showFallback = () => {
1632
- if (isShowingFallback) return;
1633
- isShowingFallback = true;
1634
- while (container.firstChild) {
1635
- container.removeChild(container.firstChild);
1570
+ const materializeChild = (value) => {
1571
+ const current = resolveNodeValue(value);
1572
+ if (shared.isArray(current)) {
1573
+ const nodes = [];
1574
+ for (const item of current) {
1575
+ const materialized = materializeChild(item);
1576
+ if (shared.isArray(materialized)) {
1577
+ nodes.push(...materialized);
1578
+ } else {
1579
+ nodes.push(materialized);
1580
+ }
1581
+ }
1582
+ return nodes;
1636
1583
  }
1637
- if (props.fallback != null) {
1638
- const normalized = normalizeNode(props.fallback);
1639
- if (normalized) {
1640
- insertNode(container, normalized);
1584
+ return normalizeNode(current);
1585
+ };
1586
+ const insertMaterializedChild = (value) => {
1587
+ const normalized = materializeChild(value);
1588
+ const nodes = shared.isArray(normalized) ? normalized : [normalized];
1589
+ for (const node of nodes) {
1590
+ if (node != null) {
1591
+ insertNode(container, node);
1641
1592
  }
1642
1593
  }
1643
1594
  };
1595
+ const renderFallbackContent = () => {
1596
+ clearContainer(container);
1597
+ if (props.fallback != null) {
1598
+ insertMaterializedChild(props.fallback);
1599
+ }
1600
+ };
1601
+ const showFallback = () => {
1602
+ if (isShowingFallback) return;
1603
+ isShowingFallback = true;
1604
+ renderFallbackContent();
1605
+ };
1644
1606
  const showChildren = () => {
1645
1607
  if (!isShowingFallback) return;
1646
1608
  const hasContent = resolvedChildren || props.children != null && !shared.isPromise(props.children);
@@ -1648,9 +1610,7 @@ function Suspense(props) {
1648
1610
  return;
1649
1611
  }
1650
1612
  isShowingFallback = false;
1651
- while (container.firstChild) {
1652
- container.removeChild(container.firstChild);
1653
- }
1613
+ clearContainer(container);
1654
1614
  if (resolvedChildren) {
1655
1615
  renderChildren(resolvedChildren);
1656
1616
  } else if (props.children != null && !shared.isPromise(props.children)) {
@@ -1658,33 +1618,17 @@ function Suspense(props) {
1658
1618
  }
1659
1619
  };
1660
1620
  const renderChildren = (children2) => {
1661
- while (container.firstChild) {
1662
- container.removeChild(container.firstChild);
1663
- }
1621
+ if (isShowingFallback) return;
1622
+ clearContainer(container);
1664
1623
  if (children2 == null) return;
1665
- const currentScope = getActiveScope();
1666
1624
  const childArray = shared.isArray(children2) ? children2 : [children2];
1667
- childArray.forEach((child) => {
1668
- if (child != null) {
1669
- if (isComponent(child)) {
1670
- child.parentContext = currentScope;
1671
- }
1672
- const normalized = normalizeNode(child);
1673
- if (normalized) {
1674
- insertNode(container, normalized);
1675
- }
1625
+ for (const child2 of childArray) {
1626
+ if (child2 != null) {
1627
+ insertMaterializedChild(child2);
1676
1628
  }
1677
- });
1629
+ }
1678
1630
  if (isShowingFallback) {
1679
- while (container.firstChild) {
1680
- container.removeChild(container.firstChild);
1681
- }
1682
- if (props.fallback != null) {
1683
- const normalized = normalizeNode(props.fallback);
1684
- if (normalized) {
1685
- insertNode(container, normalized);
1686
- }
1687
- }
1631
+ renderFallbackContent();
1688
1632
  }
1689
1633
  };
1690
1634
  const suspenseContext = {
@@ -1697,9 +1641,9 @@ function Suspense(props) {
1697
1641
  if (pendingCount === 0) {
1698
1642
  showChildren();
1699
1643
  }
1700
- }).catch((error8) => {
1644
+ }).catch((error5) => {
1701
1645
  {
1702
- shared.warn("[Suspense] Resource failed:", error8);
1646
+ shared.warn("[Suspense] Resource failed:", error5);
1703
1647
  }
1704
1648
  if (!isMounted) return;
1705
1649
  pendingCount--;
@@ -1713,7 +1657,7 @@ function Suspense(props) {
1713
1657
  showFallback();
1714
1658
  },
1715
1659
  decrement: () => {
1716
- pendingCount--;
1660
+ pendingCount = Math.max(0, pendingCount - 1);
1717
1661
  if (pendingCount === 0) {
1718
1662
  showChildren();
1719
1663
  }
@@ -1734,9 +1678,10 @@ function Suspense(props) {
1734
1678
  }
1735
1679
  onDestroy(() => {
1736
1680
  isMounted = false;
1737
- while (container.firstChild) {
1738
- container.removeChild(container.firstChild);
1739
- }
1681
+ pendingCount = 0;
1682
+ resolvedChildren = null;
1683
+ clearContainer(container);
1684
+ container.remove();
1740
1685
  });
1741
1686
  return container;
1742
1687
  }
@@ -1747,19 +1692,25 @@ function isSuspense(node) {
1747
1692
  function createResource(fetcher, options) {
1748
1693
  const value = signals.signal(options == null ? void 0 : options.initialValue);
1749
1694
  const loading = signals.signal(true);
1750
- const error8 = signals.signal(null);
1695
+ const error5 = signals.signal(null);
1751
1696
  const state = signals.signal("pending");
1752
1697
  let fetchId = 0;
1753
1698
  let currentPromise = null;
1699
+ let suspenseRegistered = false;
1700
+ const suspenseContext = inject(SuspenseContext, null);
1754
1701
  const fetch = () => __async(null, null, function* () {
1755
1702
  const currentFetchId = ++fetchId;
1756
1703
  loading.value = true;
1757
1704
  state.value = "pending";
1758
- error8.value = null;
1705
+ error5.value = null;
1706
+ suspenseRegistered = false;
1707
+ if (suspenseContext) {
1708
+ suspenseContext.increment();
1709
+ }
1759
1710
  try {
1760
1711
  const promise = fetcher();
1761
- currentPromise = promise.then(() => {
1762
- }).catch(() => {
1712
+ currentPromise = promise;
1713
+ promise.catch(() => {
1763
1714
  });
1764
1715
  const result = yield promise;
1765
1716
  if (currentFetchId === fetchId) {
@@ -1769,31 +1720,33 @@ function createResource(fetcher, options) {
1769
1720
  }
1770
1721
  } catch (error_) {
1771
1722
  if (currentFetchId === fetchId) {
1772
- error8.value = error_ instanceof Error ? error_ : new Error(String(error_));
1723
+ error5.value = error_ instanceof Error ? error_ : new Error(String(error_));
1773
1724
  state.value = "errored";
1774
1725
  loading.value = false;
1775
1726
  }
1727
+ } finally {
1728
+ if (suspenseContext) {
1729
+ suspenseContext.decrement();
1730
+ }
1776
1731
  }
1777
1732
  });
1778
1733
  fetch();
1779
1734
  const resource = (() => {
1780
- if (loading.value && currentPromise) {
1781
- const suspenseContext = inject(SuspenseContext, null);
1782
- if (suspenseContext) {
1783
- suspenseContext.register(currentPromise);
1784
- }
1735
+ if (!suspenseRegistered && loading.value && currentPromise && suspenseContext) {
1736
+ suspenseRegistered = true;
1737
+ suspenseContext.register(currentPromise);
1785
1738
  }
1786
1739
  return value.value;
1787
1740
  });
1788
1741
  resource.loading = loading;
1789
- resource.error = error8;
1742
+ resource.error = error5;
1790
1743
  resource.state = state;
1791
1744
  const actions = {
1792
1745
  mutate: (newValue) => {
1793
1746
  value.value = newValue;
1794
1747
  state.value = "ready";
1795
1748
  loading.value = false;
1796
- error8.value = null;
1749
+ error5.value = null;
1797
1750
  },
1798
1751
  refetch: () => __async(null, null, function* () {
1799
1752
  yield fetch();
@@ -1801,89 +1754,274 @@ function createResource(fetcher, options) {
1801
1754
  };
1802
1755
  return [resource, actions];
1803
1756
  }
1757
+ function resolveModule(mod) {
1758
+ return shared.isFunction(mod) ? mod : mod.default;
1759
+ }
1760
+ function renderInto(el, fn, props) {
1761
+ const comp = new Component(fn, props);
1762
+ comp.mount(el);
1763
+ return comp;
1764
+ }
1765
+ function defineAsyncComponent(loader, options = {}) {
1766
+ const { delay = 200, timeout, ssr = "blocking", onError } = options;
1767
+ if (typeof window === "undefined") {
1768
+ if (ssr === "client-only") {
1769
+ const placeholder = () => "";
1770
+ placeholder.__asyncLoader = loader;
1771
+ placeholder.__asyncResolved = () => null;
1772
+ return placeholder;
1773
+ }
1774
+ let ssrResolved = null;
1775
+ let ssrPromise = null;
1776
+ const ssrLoad = () => {
1777
+ if (ssrPromise) return ssrPromise;
1778
+ ssrPromise = loader().then((mod) => {
1779
+ ssrResolved = resolveModule(mod);
1780
+ }).catch(() => {
1781
+ });
1782
+ return ssrPromise;
1783
+ };
1784
+ ssrLoad();
1785
+ const ssrWrapper = (props) => {
1786
+ if (ssrResolved) {
1787
+ return ssrResolved(props);
1788
+ }
1789
+ return "";
1790
+ };
1791
+ ssrWrapper.__asyncLoader = ssrLoad;
1792
+ ssrWrapper.__asyncResolved = () => ssrResolved;
1793
+ return ssrWrapper;
1794
+ }
1795
+ let cachedComponent = null;
1796
+ let cachedError = null;
1797
+ let cachedStatus = "pending";
1798
+ let loadPromise = null;
1799
+ function load() {
1800
+ if (loadPromise) return loadPromise;
1801
+ loadPromise = loader().then((mod) => {
1802
+ cachedComponent = resolveModule(mod);
1803
+ cachedStatus = "resolved";
1804
+ }).catch((error5) => {
1805
+ cachedError = error5 instanceof Error ? error5 : new Error(String(error5));
1806
+ cachedStatus = "errored";
1807
+ loadPromise = null;
1808
+ });
1809
+ return loadPromise;
1810
+ }
1811
+ load();
1812
+ function AsyncWrapper(props) {
1813
+ var _a2;
1814
+ if (cachedStatus === "resolved" && cachedComponent) {
1815
+ const el = document.createElement("div");
1816
+ el.style.display = "contents";
1817
+ const comp = renderInto(el, cachedComponent, props);
1818
+ onCleanup(() => comp.destroy());
1819
+ return el;
1820
+ }
1821
+ if (cachedStatus === "errored" && cachedError) {
1822
+ const el = document.createElement("div");
1823
+ el.style.display = "contents";
1824
+ if (options.error) {
1825
+ let alive2 = true;
1826
+ let currentComp2 = null;
1827
+ const swap2 = (fn, swapProps) => {
1828
+ if (!alive2) return;
1829
+ currentComp2 == null ? void 0 : currentComp2.destroy();
1830
+ currentComp2 = renderInto(el, fn, swapProps);
1831
+ };
1832
+ const retry = () => {
1833
+ loadPromise = null;
1834
+ cachedStatus = "pending";
1835
+ cachedError = null;
1836
+ if (options.loading) swap2(options.loading);
1837
+ load().then(() => {
1838
+ if (!alive2) return;
1839
+ if (cachedStatus === "resolved" && cachedComponent) {
1840
+ swap2(cachedComponent, props);
1841
+ } else if (cachedStatus === "errored" && cachedError) {
1842
+ if (options.error) swap2(options.error, { error: cachedError, retry });
1843
+ }
1844
+ });
1845
+ };
1846
+ swap2(options.error, { error: cachedError, retry });
1847
+ onDestroy(() => {
1848
+ alive2 = false;
1849
+ currentComp2 == null ? void 0 : currentComp2.destroy();
1850
+ currentComp2 = null;
1851
+ });
1852
+ }
1853
+ return el;
1854
+ }
1855
+ const container = document.createElement("div");
1856
+ container.style.display = "contents";
1857
+ let alive = true;
1858
+ let currentComp = null;
1859
+ let delayTimer = null;
1860
+ let timeoutTimer = null;
1861
+ const swap = (fn, swapProps) => {
1862
+ if (!alive) return;
1863
+ currentComp == null ? void 0 : currentComp.destroy();
1864
+ currentComp = renderInto(container, fn, swapProps);
1865
+ };
1866
+ const retryWith = (retryProps) => () => {
1867
+ loadPromise = null;
1868
+ cachedStatus = "pending";
1869
+ cachedError = null;
1870
+ if (options.loading) swap(options.loading);
1871
+ load().then(() => {
1872
+ if (cachedStatus === "resolved" && cachedComponent) {
1873
+ swap(cachedComponent, retryProps);
1874
+ } else if (cachedStatus === "errored" && cachedError) {
1875
+ if (options.error) {
1876
+ swap(options.error, {
1877
+ error: cachedError,
1878
+ retry: retryWith(retryProps)
1879
+ });
1880
+ }
1881
+ }
1882
+ });
1883
+ };
1884
+ onDestroy(() => {
1885
+ alive = false;
1886
+ currentComp == null ? void 0 : currentComp.destroy();
1887
+ currentComp = null;
1888
+ if (delayTimer != null) clearTimeout(delayTimer);
1889
+ if (timeoutTimer != null) clearTimeout(timeoutTimer);
1890
+ });
1891
+ const suspenseCtx = (_a2 = inject(SuspenseContext)) != null ? _a2 : null;
1892
+ const showResolved = (compFn) => swap(compFn, props);
1893
+ const showError = (err) => {
1894
+ if (options.error) swap(options.error, { error: err, retry: retryWith(props) });
1895
+ };
1896
+ const showLoading = () => {
1897
+ if (options.loading) swap(options.loading);
1898
+ };
1899
+ const instancePromise = load().then(() => {
1900
+ if (!alive) return;
1901
+ if (cachedStatus === "resolved" && cachedComponent) {
1902
+ showResolved(cachedComponent);
1903
+ } else if (cachedStatus === "errored" && cachedError) {
1904
+ showError(cachedError);
1905
+ if (onError) onError(cachedError, retryWith(props));
1906
+ }
1907
+ if (delayTimer != null) clearTimeout(delayTimer);
1908
+ if (timeoutTimer != null) clearTimeout(timeoutTimer);
1909
+ });
1910
+ if (suspenseCtx) {
1911
+ suspenseCtx.register(instancePromise);
1912
+ }
1913
+ if (delay > 0) {
1914
+ delayTimer = setTimeout(() => {
1915
+ if (alive && cachedStatus === "pending") {
1916
+ showLoading();
1917
+ }
1918
+ }, delay);
1919
+ } else if (options.loading) {
1920
+ showLoading();
1921
+ }
1922
+ if (timeout != null) {
1923
+ timeoutTimer = setTimeout(() => {
1924
+ if (alive && cachedStatus === "pending") {
1925
+ const err = new Error(`[defineAsyncComponent] Timeout after ${timeout}ms`);
1926
+ cachedError = err;
1927
+ cachedStatus = "errored";
1928
+ showError(err);
1929
+ if (onError) onError(err, retryWith(props));
1930
+ }
1931
+ }, timeout);
1932
+ }
1933
+ return container;
1934
+ }
1935
+ AsyncWrapper.__asyncLoader = load;
1936
+ AsyncWrapper.__asyncResolved = () => cachedComponent;
1937
+ return AsyncWrapper;
1938
+ }
1804
1939
  function For(props) {
1805
1940
  const fragment = document.createDocumentFragment();
1806
1941
  const marker = document.createComment("");
1807
1942
  fragment.appendChild(marker);
1808
1943
  let entries = [];
1809
- let fallbackNode = null;
1810
- const keyFn = props.keyFn;
1944
+ let fallbackNodes = [];
1945
+ const keyFn = props.key;
1811
1946
  const renderFn = props.children;
1812
1947
  const getList = () => {
1813
1948
  var _a2, _b;
1814
1949
  const input = props.each;
1815
1950
  if (signals.isSignal(input)) return (_a2 = input.value) != null ? _a2 : [];
1816
- if (typeof input === "function") return (_b = input()) != null ? _b : [];
1951
+ if (shared.isFunction(input)) return (_b = input()) != null ? _b : [];
1817
1952
  return input != null ? input : [];
1818
1953
  };
1819
1954
  const getKey = (item) => keyFn ? keyFn(item) : item;
1820
- const renderItem = (item, index, parent, before) => {
1821
- var _a2;
1822
- const prevScope = getActiveScope();
1823
- const scope = createScope(prevScope);
1824
- setActiveScope(scope);
1825
- let node;
1826
- try {
1827
- const result = renderFn(item, index);
1828
- if (isComponent(result)) {
1829
- result.mount(parent, before);
1830
- node = (_a2 = result.firstChild) != null ? _a2 : document.createComment("empty");
1955
+ const normalizeNodes = (value) => {
1956
+ if (Array.isArray(value)) {
1957
+ const nodes = [];
1958
+ for (const item of value) {
1959
+ nodes.push(...normalizeNodes(item));
1960
+ }
1961
+ return nodes;
1962
+ }
1963
+ return [normalizeNode(value)];
1964
+ };
1965
+ const mountValue = (value, parent, before) => {
1966
+ const nodes = normalizeNodes(value);
1967
+ for (const node of nodes) {
1968
+ if (before) {
1969
+ parent.insertBefore(node, before);
1831
1970
  } else {
1832
- node = result;
1833
- if (!node.parentNode) {
1834
- if (before) {
1835
- parent.insertBefore(node, before);
1836
- } else {
1837
- parent.appendChild(node);
1838
- }
1839
- }
1971
+ parent.appendChild(node);
1972
+ }
1973
+ }
1974
+ return nodes;
1975
+ };
1976
+ const mountFallback = (parent, before) => {
1977
+ if (!props.fallback) return;
1978
+ const nodes = mountValue(props.fallback(), parent, before);
1979
+ fallbackNodes = nodes;
1980
+ };
1981
+ const clearFallback = () => {
1982
+ for (const node of fallbackNodes) {
1983
+ if (node.parentNode) {
1984
+ node.parentNode.removeChild(node);
1840
1985
  }
1841
- } finally {
1842
- setActiveScope(prevScope);
1843
1986
  }
1844
- return { key: getKey(item), node, scope };
1987
+ fallbackNodes = [];
1988
+ };
1989
+ const renderItem = (item, index, parent, before) => {
1990
+ const parentScope = getActiveScope();
1991
+ const scope = createScope(parentScope);
1992
+ let mountedNodes = [];
1993
+ runWithScope(scope, () => {
1994
+ mountedNodes = mountValue(renderFn(item, index), parent, before);
1995
+ });
1996
+ return { key: getKey(item), item, nodes: mountedNodes, scope };
1845
1997
  };
1846
1998
  const disposeItem = (entry) => {
1847
1999
  disposeScope(entry.scope);
1848
- if (entry.node.parentNode) {
1849
- entry.node.parentNode.removeChild(entry.node);
2000
+ for (const node of entry.nodes) {
2001
+ if (node.parentNode) {
2002
+ node.parentNode.removeChild(node);
2003
+ }
1850
2004
  }
1851
2005
  };
1852
- signals.memoEffect(
1853
- ({ prev }) => {
1854
- var _a2;
1855
- const newItems = getList();
1856
- if (prev === newItems) return { prev: newItems };
1857
- const parent = marker.parentNode;
1858
- if (!parent) {
1859
- if (newItems.length === 0) {
1860
- if (props.fallback) {
1861
- const fb = props.fallback();
1862
- if (isComponent(fb)) {
1863
- fb.mount(fragment, marker);
1864
- fallbackNode = (_a2 = fb.firstChild) != null ? _a2 : document.createComment("empty");
1865
- } else {
1866
- fallbackNode = fb;
1867
- fragment.insertBefore(fallbackNode, marker);
1868
- }
1869
- }
1870
- return { prev: newItems };
1871
- }
2006
+ const effectRunner = signals.effect(() => {
2007
+ const newItems = getList();
2008
+ const parent = marker.parentNode;
2009
+ if (!parent) {
2010
+ if (newItems.length === 0) {
2011
+ mountFallback(fragment, marker);
2012
+ } else {
1872
2013
  entries = new Array(newItems.length);
1873
- for (const [i, newItem] of newItems.entries()) {
1874
- entries[i] = renderItem(newItem, i, fragment, marker);
2014
+ let idx = 0;
2015
+ for (const newItem of newItems) {
2016
+ entries[idx] = renderItem(newItem, idx, fragment, marker);
2017
+ idx++;
1875
2018
  }
1876
- return { prev: newItems };
1877
2019
  }
1878
- signals.untrack(() => reconcile(parent, newItems));
1879
- return { prev: newItems };
1880
- },
1881
- {
1882
- prev: []
2020
+ return;
1883
2021
  }
1884
- );
2022
+ reconcile(parent, newItems);
2023
+ });
1885
2024
  function reconcile(parent, newItems) {
1886
- var _a2;
1887
2025
  const oldLen = entries.length;
1888
2026
  const newLen = newItems.length;
1889
2027
  if (newLen === 0) {
@@ -1891,22 +2029,14 @@ function For(props) {
1891
2029
  disposeItem(entries[i]);
1892
2030
  }
1893
2031
  entries = [];
1894
- if (props.fallback && !fallbackNode) {
1895
- const fb = props.fallback();
1896
- if (isComponent(fb)) {
1897
- fb.mount(parent, marker);
1898
- fallbackNode = (_a2 = fb.firstChild) != null ? _a2 : document.createComment("empty");
1899
- } else {
1900
- fallbackNode = fb;
1901
- parent.insertBefore(fallbackNode, marker);
1902
- }
2032
+ if (props.fallback && fallbackNodes.length === 0) {
2033
+ mountFallback(parent, marker);
1903
2034
  }
1904
2035
  return;
1905
2036
  }
1906
- if (oldLen === 0 || fallbackNode) {
1907
- if (fallbackNode) {
1908
- if (fallbackNode.parentNode) fallbackNode.parentNode.removeChild(fallbackNode);
1909
- fallbackNode = null;
2037
+ if (oldLen === 0 || fallbackNodes.length > 0) {
2038
+ if (fallbackNodes.length > 0) {
2039
+ clearFallback();
1910
2040
  }
1911
2041
  entries = new Array(newLen);
1912
2042
  const batchFragment2 = document.createDocumentFragment();
@@ -1920,46 +2050,76 @@ function For(props) {
1920
2050
  for (let i = 0; i < oldLen; i++) {
1921
2051
  const entry = entries[i];
1922
2052
  const list = oldKeyMap.get(entry.key);
1923
- if (list) {
1924
- list.push(entry);
1925
- } else {
1926
- oldKeyMap.set(entry.key, [entry]);
1927
- }
2053
+ const pair = [entry, i];
2054
+ if (list) list.push(pair);
2055
+ else oldKeyMap.set(entry.key, [pair]);
1928
2056
  }
1929
2057
  const newEntries = new Array(newLen);
1930
2058
  const toRemove = [];
1931
- const batchFragment = document.createDocumentFragment();
2059
+ let batchFragment = null;
2060
+ const newIndexToOldIndex = new Int32Array(newLen);
2061
+ let moved = false;
2062
+ let maxOldSeen = 0;
2063
+ const newKeys = new Array(newLen);
2064
+ for (let i = 0; i < newLen; i++) {
2065
+ newKeys[i] = getKey(newItems[i]);
2066
+ }
1932
2067
  for (let i = 0; i < newLen; i++) {
1933
2068
  const item = newItems[i];
1934
- const key = getKey(item);
2069
+ const key = newKeys[i];
1935
2070
  const oldList = oldKeyMap.get(key);
1936
2071
  if (oldList && oldList.length > 0) {
1937
- newEntries[i] = oldList.shift();
2072
+ const [reused, oldIndex] = oldList.shift();
2073
+ if (Object.is(reused.item, item)) {
2074
+ reused.item = item;
2075
+ newEntries[i] = reused;
2076
+ newIndexToOldIndex[i] = oldIndex + 1;
2077
+ if (oldIndex < maxOldSeen) moved = true;
2078
+ else maxOldSeen = oldIndex;
2079
+ } else {
2080
+ if (!batchFragment) batchFragment = document.createDocumentFragment();
2081
+ disposeItem(reused);
2082
+ newEntries[i] = renderItem(item, i, batchFragment, null);
2083
+ }
1938
2084
  } else {
2085
+ if (!batchFragment) batchFragment = document.createDocumentFragment();
1939
2086
  newEntries[i] = renderItem(item, i, batchFragment, null);
1940
2087
  }
1941
2088
  }
1942
2089
  for (const list of oldKeyMap.values()) {
1943
- for (const entry of list) {
1944
- toRemove.push(entry);
2090
+ for (const [entry] of list) toRemove.push(entry);
2091
+ }
2092
+ for (const entry of toRemove) disposeItem(entry);
2093
+ const lis = moved ? getSequence(newIndexToOldIndex) : [];
2094
+ let lisCursor = lis.length - 1;
2095
+ let nextNode = marker;
2096
+ for (let i = newLen - 1; i >= 0; i--) {
2097
+ const entry = newEntries[i];
2098
+ const nodes = entry.nodes;
2099
+ const isFresh = newIndexToOldIndex[i] === 0;
2100
+ const inLis = !isFresh && moved && lisCursor >= 0 && i === lis[lisCursor];
2101
+ if (inLis) {
2102
+ lisCursor--;
2103
+ for (let j = nodes.length - 1; j >= 0; j--) nextNode = nodes[j];
2104
+ continue;
2105
+ }
2106
+ for (let j = nodes.length - 1; j >= 0; j--) {
2107
+ const node = nodes[j];
2108
+ if (node.nextSibling !== nextNode) {
2109
+ parent.insertBefore(node, nextNode);
2110
+ }
2111
+ nextNode = node;
1945
2112
  }
1946
- }
1947
- for (const entry of toRemove) {
1948
- disposeItem(entry);
1949
- }
1950
- for (let i = 0; i < newLen; i++) {
1951
- const node = newEntries[i].node;
1952
- parent.insertBefore(node, marker);
1953
2113
  }
1954
2114
  entries = newEntries;
1955
2115
  }
1956
2116
  onCleanup(() => {
2117
+ effectRunner.stop();
1957
2118
  for (const entry of entries) {
1958
2119
  disposeItem(entry);
1959
2120
  }
1960
- if (fallbackNode && fallbackNode.parentNode) {
1961
- fallbackNode.parentNode.removeChild(fallbackNode);
1962
- }
2121
+ entries = [];
2122
+ clearFallback();
1963
2123
  if (marker.parentNode) {
1964
2124
  marker.parentNode.removeChild(marker);
1965
2125
  }
@@ -1975,49 +2135,44 @@ exports.Portal = Portal;
1975
2135
  exports.Suspense = Suspense;
1976
2136
  exports.addEvent = addEvent;
1977
2137
  exports.addEventListener = addEventListener;
2138
+ exports.beginHydration = beginHydration;
1978
2139
  exports.bindElement = bindElement;
2140
+ exports.child = child;
2141
+ exports.clearDelegatedEvents = clearDelegatedEvents;
2142
+ exports.consumeTeleportAnchor = consumeTeleportAnchor;
2143
+ exports.consumeTeleportBlock = consumeTeleportBlock;
1979
2144
  exports.createApp = createApp;
1980
2145
  exports.createComponent = createComponent;
1981
2146
  exports.createResource = createResource;
1982
- exports.createScope = createScope;
2147
+ exports.defineAsyncComponent = defineAsyncComponent;
1983
2148
  exports.delegateEvents = delegateEvents;
1984
- exports.disposeScope = disposeScope;
1985
2149
  exports.endHydration = endHydration;
1986
- exports.getActiveScope = getActiveScope;
1987
- exports.getFirstDOMNode = getFirstDOMNode;
1988
2150
  exports.getHydrationKey = getHydrationKey;
1989
2151
  exports.getRenderedElement = getRenderedElement;
1990
2152
  exports.hydrate = hydrate;
1991
2153
  exports.inject = inject;
1992
2154
  exports.insert = insert;
1993
- exports.insertNode = insertNode;
1994
2155
  exports.isComponent = isComponent;
1995
2156
  exports.isFragment = isFragment;
1996
2157
  exports.isHydrating = isHydrating;
1997
2158
  exports.isPortal = isPortal;
1998
- exports.isSameNode = isSameNode;
1999
2159
  exports.isSuspense = isSuspense;
2000
- exports.mapNodes = mapNodes;
2001
- exports.mapSSRNodes = mapSSRNodes;
2160
+ exports.next = next;
2002
2161
  exports.normalizeClass = normalizeClass;
2003
- exports.normalizeNode = normalizeNode;
2162
+ exports.nthChild = nthChild;
2004
2163
  exports.omitProps = omitProps;
2005
- exports.onCleanup = onCleanup;
2006
2164
  exports.onDestroy = onDestroy;
2007
2165
  exports.onMount = onMount;
2008
2166
  exports.onUpdate = onUpdate;
2009
2167
  exports.patchAttr = patchAttr;
2168
+ exports.patchAttrHydrate = patchAttrHydrate;
2010
2169
  exports.patchClass = patchClass;
2170
+ exports.patchClassHydrate = patchClassHydrate;
2011
2171
  exports.patchStyle = patchStyle;
2172
+ exports.patchStyleHydrate = patchStyleHydrate;
2012
2173
  exports.provide = provide;
2013
- exports.removeNode = removeNode;
2014
- exports.replaceNode = replaceNode;
2015
2174
  exports.resetHydrationKey = resetHydrationKey;
2016
- exports.runWithScope = runWithScope;
2017
- exports.setActiveScope = setActiveScope;
2018
2175
  exports.setStyle = setStyle;
2019
- exports.shallowCompare = shallowCompare;
2020
- exports.startHydration = startHydration;
2021
2176
  exports.template = template;
2022
2177
  //# sourceMappingURL=template.dev.cjs.js.map
2023
2178
  //# sourceMappingURL=template.dev.cjs.js.map