@estjs/template 0.0.14-beta.9 → 0.0.15-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.
@@ -1,979 +1,1838 @@
1
1
  'use strict';
2
2
 
3
3
  var shared = require('@estjs/shared');
4
- var signal = require('@estjs/signal');
4
+ var signals = require('@estjs/signals');
5
5
 
6
6
  /**
7
- * @estjs/template v0.0.14-beta.9
7
+ * @estjs/template v0.0.15-beta.1
8
8
  * (c) 2023-Present jiangxd <jiangxd2016@gmail.com>
9
9
  * @license MIT
10
10
  **/
11
+ var __defProp = Object.defineProperty;
12
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
15
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
16
+ var __spreadValues = (a, b) => {
17
+ for (var prop in b || (b = {}))
18
+ if (__hasOwnProp.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ if (__getOwnPropSymbols)
21
+ for (var prop of __getOwnPropSymbols(b)) {
22
+ if (__propIsEnum.call(b, prop))
23
+ __defNormalProp(a, prop, b[prop]);
24
+ }
25
+ return a;
26
+ };
27
+ var __async = (__this, __arguments, generator) => {
28
+ return new Promise((resolve, reject) => {
29
+ var fulfilled = (value) => {
30
+ try {
31
+ step(generator.next(value));
32
+ } catch (e) {
33
+ reject(e);
34
+ }
35
+ };
36
+ var rejected = (value) => {
37
+ try {
38
+ step(generator.throw(value));
39
+ } catch (e) {
40
+ reject(e);
41
+ }
42
+ };
43
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
44
+ step((generator = generator.apply(__this, __arguments)).next());
45
+ });
46
+ };
47
+ var activeContext = null;
48
+ var contextStack = [];
49
+ var contextId = 0;
50
+ function createContext(parent = null) {
51
+ const context = {
52
+ id: ++contextId,
53
+ parent,
54
+ provides: /* @__PURE__ */ new Map(),
55
+ cleanup: /* @__PURE__ */ new Set(),
56
+ mount: /* @__PURE__ */ new Set(),
57
+ update: /* @__PURE__ */ new Set(),
58
+ destroy: /* @__PURE__ */ new Set(),
59
+ isMount: false,
60
+ isDestroy: false,
61
+ children: /* @__PURE__ */ new Set()
62
+ };
63
+ if (parent) {
64
+ parent.children.add(context);
65
+ }
66
+ return context;
67
+ }
68
+ function getActiveContext() {
69
+ return activeContext;
70
+ }
71
+ function pushContextStack(context) {
72
+ if (activeContext) {
73
+ contextStack.push(activeContext);
74
+ }
75
+ activeContext = context;
76
+ }
77
+ function popContextStack() {
78
+ activeContext = contextStack.pop() || null;
79
+ }
80
+ function destroyContext(context) {
81
+ if (!context || context.isDestroy) {
82
+ return;
83
+ }
84
+ const childrenToDestroy = Array.from(context.children);
85
+ childrenToDestroy.forEach(destroyContext);
86
+ cleanupContext(context);
87
+ }
88
+ function cleanupContext(context) {
89
+ if (!context || context.isDestroy) {
90
+ return;
91
+ }
92
+ if (context.parent) {
93
+ context.parent.children.delete(context);
94
+ context.parent = null;
95
+ }
96
+ try {
97
+ context.cleanup.forEach((fn) => fn());
98
+ context.cleanup.clear();
99
+ context.mount.clear();
100
+ context.update.clear();
101
+ context.destroy.clear();
102
+ context.provides.clear();
103
+ context.children.clear();
104
+ } catch (error_) {
105
+ shared.error("Error during context cleanup:", error_);
106
+ }
107
+ context.isDestroy = true;
108
+ }
109
+ var LIFECYCLE = {
110
+ mount: "mount",
111
+ destroy: "destroy",
112
+ update: "update"
113
+ };
114
+ function registerLifecycleHook(type, hook) {
115
+ const context = getActiveContext();
116
+ if (!context) {
117
+ shared.error(`Cannot register ${type} hook outside component context`);
118
+ return;
119
+ }
120
+ if (!LIFECYCLE[type]) {
121
+ shared.error(`Invalid lifecycle type: ${type}`);
122
+ return;
123
+ }
124
+ if (type === LIFECYCLE.mount && context.isMount) {
125
+ try {
126
+ hook();
127
+ } catch (error_) {
128
+ shared.error(`Error in ${type} hook:`, error_);
129
+ }
130
+ return;
131
+ }
132
+ context[type].add(hook);
133
+ }
134
+ function triggerLifecycleHook(type) {
135
+ const context = getActiveContext();
136
+ if (!context) {
137
+ shared.error(`Cannot trigger ${type} hook outside component context`);
138
+ return;
139
+ }
140
+ const hooks = context[type];
141
+ if (!(hooks == null ? void 0 : hooks.size)) {
142
+ return;
143
+ }
144
+ hooks.forEach((hook) => {
145
+ try {
146
+ hook();
147
+ } catch (error_) {
148
+ {
149
+ shared.error(`Error in ${type} lifecycle hook:`, error_);
150
+ }
151
+ }
152
+ });
153
+ }
154
+ function onMount(hook) {
155
+ registerLifecycleHook(LIFECYCLE.mount, hook);
156
+ }
157
+ function onDestroy(hook) {
158
+ registerLifecycleHook(LIFECYCLE.destroy, hook);
159
+ }
160
+ function onUpdate(hook) {
161
+ registerLifecycleHook(LIFECYCLE.update, hook);
162
+ }
11
163
 
12
-
13
- // src/sharedConfig.ts
164
+ // src/constants.ts
14
165
  var EVENT_PREFIX = "on";
15
- var UPDATE_PREFIX = "update";
16
- var CHILDREN_PROP = "children";
17
- var EMPTY_TEMPLATE = "";
18
- var FRAGMENT_PROP_KEY = "0";
19
- var SINGLE_PROP_KEY = "1";
20
166
  var REF_KEY = "ref";
21
- var PLACEHOLDER = " __PLACEHOLDER__ ";
22
- var RenderContext = class {
23
- constructor() {
24
- this.renderMode = 0 /* CLIENT */;
25
- }
26
- get isSSG() {
27
- return this.renderMode === 1 /* SSG */;
167
+ var KEY_PROP = "key";
168
+ var SVG_NAMESPACE = "http://www.w3.org/2000/svg";
169
+ var XLINK_NAMESPACE = "http://www.w3.org/2000/xlink";
170
+ var XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/";
171
+ var DATA_IDX_REGEX = /^\d+-\d+$/;
172
+ var MAX_KEY_LENGTH = 1e3;
173
+ var componentKeyPrefixCache = /* @__PURE__ */ new WeakMap();
174
+ function getComponentKey(type) {
175
+ let prefix = componentKeyPrefixCache.get(type);
176
+ if (!prefix) {
177
+ const name = type.name || "anonymous";
178
+ const hash = simpleHash(type.toString()).toString(36);
179
+ prefix = `${name}_${hash}`;
180
+ componentKeyPrefixCache.set(type, prefix);
181
+ }
182
+ return prefix;
183
+ }
184
+ function simpleHash(str) {
185
+ let hash = 0;
186
+ const len = str.length < 100 ? str.length : 100;
187
+ for (let i = 0; i < len; i++) {
188
+ hash = Math.trunc((hash << 5) - hash + str.charCodeAt(i));
28
189
  }
29
- get isSSR() {
30
- return this.renderMode === 2 /* SSR */;
190
+ return hash < 0 ? -hash : hash;
191
+ }
192
+ var symbolIdCounter = 0;
193
+ function normalizeKey(key) {
194
+ if (shared.isFalsy(key)) {
195
+ return void 0;
196
+ }
197
+ if (shared.isString(key)) {
198
+ if (key.length <= MAX_KEY_LENGTH) {
199
+ return key;
200
+ }
201
+ {
202
+ shared.warn(
203
+ `[Key System] Key length exceeds ${MAX_KEY_LENGTH} characters. Consider using a shorter identifier.`
204
+ );
205
+ }
206
+ return `${key.slice(0, MAX_KEY_LENGTH - 10)}_${simpleHash(key).toString(36)}`;
31
207
  }
32
- get isClient() {
33
- return this.renderMode === 0 /* CLIENT */;
208
+ if (shared.isNumber(key)) {
209
+ {
210
+ if (key !== key) {
211
+ shared.warn("[Key System] NaN cannot be used as a key");
212
+ return void 0;
213
+ }
214
+ if (!Number.isFinite(key)) {
215
+ shared.warn("[Key System] Infinity cannot be used as a key");
216
+ return void 0;
217
+ }
218
+ }
219
+ return String(key);
34
220
  }
35
- setSSR() {
36
- this.renderMode = 2 /* SSR */;
221
+ if (shared.isSymbol(key)) {
222
+ const globalKey = Symbol.keyFor(key);
223
+ if (globalKey) {
224
+ return `_s.${globalKey}`;
225
+ }
226
+ const desc = key.description;
227
+ return desc ? `_s.${desc}` : `${symbolIdCounter++}`;
37
228
  }
38
- setSSG() {
39
- this.renderMode = 1 /* SSG */;
229
+ return String(key);
230
+ }
231
+ var NODE_KEY_SYMBOL = Symbol("essor.key");
232
+ function setNodeKey(node, key) {
233
+ if (isComponent(node)) {
234
+ return;
235
+ }
236
+ if (!node || node.nodeType === Node.DOCUMENT_NODE) {
237
+ {
238
+ shared.warn("[Key System] Cannot set key on invalid node");
239
+ }
240
+ return;
40
241
  }
41
- setClient() {
42
- this.renderMode = 0 /* CLIENT */;
242
+ const normalizedKey = normalizeKey(key);
243
+ if (shared.isFalsy(normalizedKey)) {
244
+ delete node[NODE_KEY_SYMBOL];
245
+ } else {
246
+ node[NODE_KEY_SYMBOL] = normalizedKey;
43
247
  }
44
- };
45
- var renderContext = new RenderContext();
46
- var componentMap = /* @__PURE__ */ new Map();
47
- function enterComponent(temp, index) {
48
- componentMap.set(temp, {
49
- index
50
- });
51
248
  }
52
- function getComponentIndex(temp) {
53
- var _a;
54
- return (_a = componentMap.get(temp)) == null ? void 0 : _a.index;
249
+ function getNodeKey(node) {
250
+ if (!node) return void 0;
251
+ return isComponent(node) ? node.key : node[NODE_KEY_SYMBOL];
55
252
  }
56
253
 
57
- // src/lifecycleContext.ts
58
- var _LifecycleContext = class _LifecycleContext {
59
- constructor() {
60
- // Hooks for different lifecycle stages
61
- this.hooks = {
62
- mounted: /* @__PURE__ */ new Set(),
63
- destroy: /* @__PURE__ */ new Set()
64
- };
254
+ // src/utils.ts
255
+ function removeNode(node) {
256
+ if (!node) return;
257
+ try {
258
+ if (isComponent(node)) {
259
+ node.destroy();
260
+ } else {
261
+ const element = node;
262
+ if (element.parentElement) {
263
+ element.remove();
264
+ }
265
+ }
266
+ } catch (_error) {
267
+ shared.error("Failed to remove node:", _error);
65
268
  }
66
- addEventListener() {
269
+ }
270
+ function insertNode(parent, child, before = null) {
271
+ if (!parent || !child) return;
272
+ try {
273
+ const beforeNode = isComponent(before) ? before.firstChild : before;
274
+ if (isComponent(child)) {
275
+ child.mount(parent, beforeNode);
276
+ return;
277
+ }
278
+ if (beforeNode) {
279
+ parent.insertBefore(child, beforeNode);
280
+ } else {
281
+ if (true) {
282
+ if (!child) {
283
+ shared.error("insertNode: child is not a Node", child);
284
+ }
285
+ }
286
+ parent.appendChild(child);
287
+ }
288
+ } catch (_error) {
289
+ shared.error("Failed to insert node:", _error);
67
290
  }
68
- removeEventListener() {
291
+ }
292
+ function replaceNode(parent, newNode, oldNode) {
293
+ if (!parent || !newNode || !oldNode || newNode === oldNode) return;
294
+ try {
295
+ insertNode(parent, newNode, oldNode);
296
+ removeNode(oldNode);
297
+ } catch (_error) {
298
+ shared.error("Failed to replace node:", _error);
69
299
  }
70
- // Add a hook for a specific lifecycle stage
71
- addHook(hook, cb) {
72
- var _a;
73
- (_a = this.hooks[hook]) == null ? void 0 : _a.add(cb);
300
+ }
301
+ function getFirstDOMNode(node) {
302
+ if (!node) {
303
+ return null;
74
304
  }
75
- // Get a value from the static context
76
- getContext(context) {
77
- return _LifecycleContext.context[context];
305
+ if (isComponent(node)) {
306
+ return node.firstChild;
78
307
  }
79
- // Set a value in the static context
80
- setContext(context, value) {
81
- _LifecycleContext.context[context] = value;
308
+ return node;
309
+ }
310
+ function isSameNode(a, b) {
311
+ const keyA = getNodeKey(a);
312
+ const keyB = getNodeKey(b);
313
+ if (keyA !== keyB) {
314
+ return false;
82
315
  }
83
- initRef() {
84
- _LifecycleContext.ref = this;
316
+ const aIsComponent = isComponent(a);
317
+ const bIsComponent = isComponent(b);
318
+ if (aIsComponent && bIsComponent) {
319
+ return a.component === b.component;
85
320
  }
86
- removeRef() {
87
- _LifecycleContext.ref = null;
321
+ if (aIsComponent !== bIsComponent) {
322
+ return false;
88
323
  }
89
- // Clear all hooks
90
- clearHooks() {
91
- Object.values(this.hooks).forEach((set) => set.clear());
324
+ const aNode = a;
325
+ const bNode = b;
326
+ if (aNode.nodeType !== bNode.nodeType) {
327
+ return false;
92
328
  }
93
- };
94
- _LifecycleContext.ref = null;
95
- _LifecycleContext.context = {};
96
- var LifecycleContext = _LifecycleContext;
97
-
98
- // src/ssgNode.ts
99
- function isSSGNode(node) {
100
- return node instanceof SSGNode;
101
- }
102
- var componentIndex = 1;
103
- var SSGNode = class extends LifecycleContext {
104
- constructor(template, props = {}, key) {
105
- super();
106
- this.template = template;
107
- this.props = props;
108
- this.key = key;
109
- enterComponent(template, componentIndex);
110
- this.templates = this.processTemplate();
329
+ if (aNode.nodeType === Node.ELEMENT_NODE) {
330
+ return aNode.tagName === bNode.tagName;
111
331
  }
112
- processTemplate() {
113
- if (shared.isArray(this.template)) {
114
- const htmlString = this.template.join(PLACEHOLDER);
115
- const processedString = this.processHtmlString(htmlString);
116
- return processedString.split(PLACEHOLDER);
117
- }
118
- return [];
332
+ return true;
333
+ }
334
+ function normalizeNode(node) {
335
+ if (shared.isHTMLElement(node)) {
336
+ return node;
119
337
  }
120
- processHtmlString(htmlString) {
121
- return htmlString.replaceAll(/(<[^>]+>)|([^<]+)/g, (match, p1, p2) => {
122
- if (p1) {
123
- if (p1.includes("data-ci")) return match;
124
- return p1.replace(/<\s*([\da-z]+)(\s[^>]*)?>/i, (_, tagName, attrs) => {
125
- return `<${tagName} data-ci="${componentIndex}"${attrs || ""}>`;
126
- });
127
- } else if (p2 && p2.replace(PLACEHOLDER, "").trim()) {
128
- return `<!--${0 /* TEXT */}-${componentIndex}-->${p2}<!$>`;
129
- }
130
- return match;
131
- });
338
+ if (shared.isPrimitive(node)) {
339
+ const textContent = shared.isFalsy(node) ? "" : String(node);
340
+ return document.createTextNode(textContent);
132
341
  }
133
- mount() {
134
- this.initRef();
135
- const output = this.render();
136
- this.removeRef();
137
- return output;
138
- }
139
- render() {
140
- if (shared.isFunction(this.template)) {
141
- const root = this.template(this.props);
142
- if (isSSGNode(root)) {
143
- return root.mount();
144
- } else {
145
- return String(root);
342
+ return node;
343
+ }
344
+ function isHtmlInputElement(val) {
345
+ return val instanceof HTMLInputElement;
346
+ }
347
+ function isHtmlSelectElement(val) {
348
+ return val instanceof HTMLSelectElement;
349
+ }
350
+ function isHtmlTextAreaElement(val) {
351
+ return val instanceof HTMLTextAreaElement;
352
+ }
353
+ function isHtmLTextElement(val) {
354
+ return val instanceof Text;
355
+ }
356
+ function shallowCompare(a, b) {
357
+ if (a === b) return true;
358
+ if (!a || !b) return false;
359
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
360
+ for (const key in a) {
361
+ if (a[key] !== b[key]) return false;
362
+ }
363
+ for (const key in b) {
364
+ if (!(key in a)) return false;
365
+ }
366
+ return true;
367
+ }
368
+ function transferKey(oldNode, newNode) {
369
+ if (isComponent(oldNode) || isComponent(newNode)) {
370
+ return;
371
+ }
372
+ const oldKey = getNodeKey(oldNode);
373
+ if (oldKey && !getNodeKey(newNode)) {
374
+ setNodeKey(newNode, oldKey);
375
+ }
376
+ }
377
+ function patch(parent, oldNode, newNode) {
378
+ if (newNode === oldNode) {
379
+ return oldNode;
380
+ }
381
+ const oldIsElement = shared.isHTMLElement(oldNode);
382
+ const newIsElement = shared.isHTMLElement(newNode);
383
+ if (newIsElement && oldIsElement) {
384
+ if (newNode.isEqualNode(oldNode)) {
385
+ return oldNode;
386
+ }
387
+ if (oldNode.tagName === newNode.tagName) {
388
+ const oldAttrs = oldNode.attributes;
389
+ const newAttrs = newNode.attributes;
390
+ for (let i = oldAttrs.length - 1; i >= 0; i--) {
391
+ const attrName = oldAttrs[i].name;
392
+ if (!newNode.hasAttribute(attrName)) {
393
+ oldNode.removeAttribute(attrName);
394
+ }
146
395
  }
396
+ for (let i = 0, len = newAttrs.length; i < len; i++) {
397
+ const attr = newAttrs[i];
398
+ if (oldNode.getAttribute(attr.name) !== attr.value) {
399
+ oldNode.setAttribute(attr.name, attr.value);
400
+ }
401
+ }
402
+ transferKey(oldNode, newNode);
403
+ return oldNode;
147
404
  }
148
- return this.renderTemplate();
149
405
  }
150
- renderTemplate() {
151
- Object.entries(this.props).forEach(([key, cur]) => {
152
- const children = cur.children;
153
- this.normalizeProps(cur);
154
- const findIndex = this.templates.findIndex((t) => t.includes(`data-hk="${key}"`));
155
- if (children) {
156
- this.renderChildren(children, findIndex);
157
- }
158
- this.templates[findIndex] = this.templates[findIndex].replace(
159
- `data-hk="${key}"`,
160
- `data-hk="${key}" ${this.generateAttributes(cur)}`
161
- );
162
- });
163
- return this.templates.join("");
406
+ if (isHtmLTextElement(oldNode) && isHtmLTextElement(newNode)) {
407
+ if (oldNode.textContent !== newNode.textContent) {
408
+ oldNode.textContent = newNode.textContent;
409
+ }
410
+ transferKey(oldNode, newNode);
411
+ return oldNode;
412
+ }
413
+ const oldIsComponent = isComponent(oldNode);
414
+ const newIsComponent = isComponent(newNode);
415
+ if (oldIsComponent && newIsComponent) {
416
+ if (oldNode.component === newNode.component) {
417
+ return newNode.update(oldNode);
418
+ }
164
419
  }
165
- normalizeProps(props) {
166
- Object.entries(props).forEach(([key, value]) => {
167
- if (key === CHILDREN_PROP) {
168
- delete props[key];
169
- } else if (shared.isFunction(value)) {
170
- delete props[key];
171
- } else if (signal.isSignal(value)) {
172
- props[key] = value.value;
173
- }
174
- });
420
+ replaceNode(parent, newNode, oldNode);
421
+ return newNode;
422
+ }
423
+ function patchChildren(parent, oldChildren, newChildren, anchor) {
424
+ const oldLength = oldChildren.length;
425
+ const newLength = newChildren.length;
426
+ if (oldLength === 0 && newLength === 0) {
427
+ return [];
175
428
  }
176
- generateAttributes(props) {
177
- return Object.entries(props).filter(([key, value]) => key !== CHILDREN_PROP && !shared.isFunction(value)).map(([key, value]) => `${key}="${shared.escape(String(value))}"`).join(" ");
429
+ if (oldLength === 0) {
430
+ const fragment = document.createDocumentFragment();
431
+ for (let i = 0; i < newLength; i++) {
432
+ insertNode(fragment, newChildren[i]);
433
+ }
434
+ insertNode(parent, fragment, anchor);
435
+ return newChildren;
178
436
  }
179
- renderChildren(children, findIndex) {
180
- children.forEach(([child]) => {
181
- componentIndex++;
182
- const renderedChild = this.renderChild(child);
183
- this.templates[findIndex] += renderedChild;
184
- });
437
+ if (newLength === 0) {
438
+ for (let i = 0; i < oldLength; i++) {
439
+ removeNode(oldChildren[i]);
440
+ }
441
+ return [];
185
442
  }
186
- renderChild(child) {
187
- if (shared.isFunction(child)) {
188
- return this.renderChild(child(this.props));
189
- } else if (signal.isSignal(child)) {
190
- return `<!--${1 /* TEXT_COMPONENT */}-${componentIndex}-->${child.value}<!$>`;
191
- } else if (isSSGNode(child)) {
192
- const childResult = child.mount();
193
- return shared.isFunction(childResult) ? childResult(this.props) : extractSignal(childResult);
443
+ if (oldLength === 1 && newLength === 1) {
444
+ const oldNode = oldChildren[0];
445
+ const newNode = newChildren[0];
446
+ if (isSameNode(oldNode, newNode)) {
447
+ patch(parent, oldNode, newNode);
448
+ newChildren[0] = oldNode;
194
449
  } else {
195
- return `<!--${1 /* TEXT_COMPONENT */}-${componentIndex}-->${child}<!$>`;
450
+ replaceNode(parent, newNode, oldNode);
196
451
  }
197
- }
198
- };
199
-
200
- // src/utils.ts
201
- var SELF_CLOSING_TAGS = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr".split(",");
202
- function coerceNode(data) {
203
- if (isJsxElement(data) || data instanceof Node || isSSGNode(data)) {
204
- return data;
205
- }
206
- const text = shared.isFalsy(data) ? "" : String(data);
207
- return document.createTextNode(text);
208
- }
209
- function insertChild(parent, child, before = null) {
210
- const beforeNode = isJsxElement(before) ? before.firstChild : before;
211
- const ssr = renderContext.isSSR;
212
- if (isJsxElement(child)) {
213
- child.mount(parent, beforeNode);
214
- } else if (beforeNode && !ssr) {
215
- beforeNode.before(child);
216
- } else if (!ssr) {
217
- parent.append(child);
218
- }
219
- }
220
- function removeChild(child) {
221
- if (isJsxElement(child)) {
222
- child.unmount();
223
- } else {
224
- const parent = child.parentNode;
225
- if (parent) {
226
- child.remove();
452
+ return newChildren;
453
+ }
454
+ if (oldLength === 2 && newLength === 2) {
455
+ const o0 = oldChildren[0];
456
+ const o1 = oldChildren[1];
457
+ const n0 = newChildren[0];
458
+ const n1 = newChildren[1];
459
+ if (isSameNode(o0, n0) && isSameNode(o1, n1)) {
460
+ patch(parent, o0, n0);
461
+ patch(parent, o1, n1);
462
+ newChildren[0] = o0;
463
+ newChildren[1] = o1;
464
+ return newChildren;
465
+ }
466
+ if (isSameNode(o0, n1) && isSameNode(o1, n0)) {
467
+ patch(parent, o0, n1);
468
+ patch(parent, o1, n0);
469
+ const dom1 = getFirstDOMNode(o1);
470
+ const dom0 = getFirstDOMNode(o0);
471
+ if (dom1 && dom0 && dom1.parentNode === parent) {
472
+ parent.insertBefore(dom1, dom0);
473
+ }
474
+ newChildren[0] = o1;
475
+ newChildren[1] = o0;
476
+ return newChildren;
227
477
  }
228
478
  }
479
+ return patchKeyedChildren(parent, oldChildren, newChildren, anchor);
229
480
  }
230
- function replaceChild(parent, node, child) {
231
- insertChild(parent, node, child);
232
- removeChild(child);
233
- }
234
- function setAttribute(element, attr, value) {
235
- if (attr === "class") {
236
- setClassAttribute(element, value);
237
- } else if (attr === "style") {
238
- setStyleAttribute(element, value);
481
+ function patchKeyedChildren(parent, oldChildren, newChildren, anchor) {
482
+ let oldStartIdx = 0;
483
+ let newStartIdx = 0;
484
+ let oldEndIdx = oldChildren.length - 1;
485
+ let newEndIdx = newChildren.length - 1;
486
+ let oldStartNode = oldChildren[0];
487
+ let oldEndNode = oldChildren[oldEndIdx];
488
+ let newStartNode = newChildren[0];
489
+ let newEndNode = newChildren[newEndIdx];
490
+ while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
491
+ if (!oldStartNode) {
492
+ oldStartNode = oldChildren[++oldStartIdx];
493
+ } else if (!oldEndNode) {
494
+ oldEndNode = oldChildren[--oldEndIdx];
495
+ } else if (isSameNode(oldStartNode, newStartNode)) {
496
+ patch(parent, oldStartNode, newStartNode);
497
+ newChildren[newStartIdx] = oldStartNode;
498
+ oldStartNode = oldChildren[++oldStartIdx];
499
+ newStartNode = newChildren[++newStartIdx];
500
+ } else {
501
+ break;
502
+ }
503
+ }
504
+ while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
505
+ if (!oldStartNode) {
506
+ oldStartNode = oldChildren[++oldStartIdx];
507
+ } else if (!oldEndNode) {
508
+ oldEndNode = oldChildren[--oldEndIdx];
509
+ } else if (isSameNode(oldEndNode, newEndNode)) {
510
+ patch(parent, oldEndNode, newEndNode);
511
+ newChildren[newEndIdx] = oldEndNode;
512
+ oldEndNode = oldChildren[--oldEndIdx];
513
+ newEndNode = newChildren[--newEndIdx];
514
+ } else {
515
+ break;
516
+ }
517
+ }
518
+ if (oldStartIdx > oldEndIdx) {
519
+ if (newStartIdx <= newEndIdx) {
520
+ const anchorNode = newEndIdx + 1 < newChildren.length ? getFirstDOMNode(newChildren[newEndIdx + 1]) : anchor;
521
+ for (let i = newStartIdx; i <= newEndIdx; i++) {
522
+ insertNode(parent, newChildren[i], anchorNode);
523
+ }
524
+ }
525
+ } else if (newStartIdx > newEndIdx) {
526
+ for (let i = oldStartIdx; i <= oldEndIdx; i++) {
527
+ const node = oldChildren[i];
528
+ if (node) {
529
+ removeNode(node);
530
+ }
531
+ }
239
532
  } else {
240
- setGenericAttribute(element, attr, value);
533
+ patchUnknownSequence(
534
+ parent,
535
+ oldChildren,
536
+ newChildren,
537
+ oldStartIdx,
538
+ oldEndIdx,
539
+ newStartIdx,
540
+ newEndIdx,
541
+ anchor
542
+ );
241
543
  }
544
+ return newChildren;
242
545
  }
243
- function setClassAttribute(element, value) {
244
- if (typeof value === "string") {
245
- element.className = value;
246
- } else if (shared.isArray(value)) {
247
- element.className = value.join(" ");
248
- } else if (value && typeof value === "object") {
249
- element.className = Object.entries(value).reduce((acc, [key, value2]) => acc + (value2 ? ` ${key}` : ""), "").trim();
546
+ function patchUnknownSequence(parent, oldChildren, newChildren, oldStartIdx, oldEndIdx, newStartIdx, newEndIdx, anchor) {
547
+ const newLength = newEndIdx - newStartIdx + 1;
548
+ const newChildrenLen = newChildren.length;
549
+ let keyToNewIndexMap;
550
+ for (let i = newStartIdx; i <= newEndIdx; i++) {
551
+ const key = getNodeKey(newChildren[i]);
552
+ if (key !== void 0) {
553
+ if (!keyToNewIndexMap) {
554
+ keyToNewIndexMap = /* @__PURE__ */ Object.create(null);
555
+ }
556
+ keyToNewIndexMap[key] = i;
557
+ }
250
558
  }
251
- }
252
- function setStyleAttribute(element, value) {
253
- if (typeof value === "string") {
254
- element.style.cssText = value;
255
- } else if (value && typeof value === "object") {
256
- const obj = value;
257
- Object.entries(obj).forEach(([key, value2]) => {
258
- element.style.setProperty(shared.kebabCase(key), String(value2));
259
- });
559
+ const newIndexToOldIndexMap = new Int32Array(newLength);
560
+ let moved = false;
561
+ let maxNewIndexSoFar = 0;
562
+ let patched = 0;
563
+ for (let i = oldStartIdx; i <= oldEndIdx; i++) {
564
+ const oldNode = oldChildren[i];
565
+ if (!oldNode) continue;
566
+ if (patched >= newLength) {
567
+ removeNode(oldNode);
568
+ continue;
569
+ }
570
+ let newIndex;
571
+ const oldKey = getNodeKey(oldNode);
572
+ if (oldKey !== void 0 && keyToNewIndexMap && oldKey in keyToNewIndexMap) {
573
+ newIndex = keyToNewIndexMap[oldKey];
574
+ } else {
575
+ for (let j2 = newStartIdx; j2 <= newEndIdx; j2++) {
576
+ if (newIndexToOldIndexMap[j2 - newStartIdx] === 0 && oldKey === void 0 && getNodeKey(newChildren[j2]) === void 0 && isSameNode(oldNode, newChildren[j2])) {
577
+ newIndex = j2;
578
+ break;
579
+ }
580
+ }
581
+ }
582
+ if (newIndex === void 0) {
583
+ removeNode(oldNode);
584
+ } else {
585
+ newIndexToOldIndexMap[newIndex - newStartIdx] = i + 1;
586
+ if (newIndex >= maxNewIndexSoFar) {
587
+ maxNewIndexSoFar = newIndex;
588
+ } else {
589
+ moved = true;
590
+ }
591
+ patch(parent, oldNode, newChildren[newIndex]);
592
+ newChildren[newIndex] = oldNode;
593
+ patched++;
594
+ }
595
+ }
596
+ const increasingNewIndexSequence = moved ? getSequence(newIndexToOldIndexMap) : [];
597
+ let j = increasingNewIndexSequence.length - 1;
598
+ for (let i = newLength - 1; i >= 0; i--) {
599
+ const nextIndex = newStartIdx + i;
600
+ const nextNode = newChildren[nextIndex];
601
+ const nextAnchor = nextIndex + 1 < newChildrenLen ? getFirstDOMNode(newChildren[nextIndex + 1]) : anchor;
602
+ if (newIndexToOldIndexMap[i] === 0) {
603
+ insertNode(parent, nextNode, nextAnchor);
604
+ } else if (moved) {
605
+ if (j < 0 || i !== increasingNewIndexSequence[j]) {
606
+ const domNode = getFirstDOMNode(nextNode);
607
+ if (domNode && domNode.parentNode === parent) {
608
+ insertNode(parent, domNode, nextAnchor);
609
+ }
610
+ } else {
611
+ j--;
612
+ }
613
+ }
260
614
  }
261
615
  }
262
- function setGenericAttribute(element, attr, value) {
263
- if (shared.isFalsy(value)) {
264
- element.removeAttribute(attr);
265
- } else if (value === true) {
266
- element.setAttribute(attr, "");
267
- } else {
268
- if (element instanceof HTMLInputElement && attr === "value") {
269
- element.value = String(value);
270
- } else {
271
- element.setAttribute(attr, String(value));
616
+ function getSequence(arr) {
617
+ const len = arr.length;
618
+ if (len === 0) return [];
619
+ if (len === 1) return arr[0] !== 0 ? [0] : [];
620
+ const result = [];
621
+ const p = new Int32Array(len);
622
+ let i;
623
+ let j;
624
+ let u;
625
+ let v;
626
+ let c;
627
+ for (i = 0; i < len; i++) {
628
+ const arrI = arr[i];
629
+ if (arrI !== 0) {
630
+ j = result[result.length - 1];
631
+ if (result.length === 0 || arr[j] < arrI) {
632
+ p[i] = j;
633
+ result.push(i);
634
+ continue;
635
+ }
636
+ u = 0;
637
+ v = result.length - 1;
638
+ while (u < v) {
639
+ c = u + v >> 1;
640
+ if (arr[result[c]] < arrI) {
641
+ u = c + 1;
642
+ } else {
643
+ v = c;
644
+ }
645
+ }
646
+ if (arrI < arr[result[u]]) {
647
+ if (u > 0) {
648
+ p[i] = result[u - 1];
649
+ }
650
+ result[u] = i;
651
+ }
272
652
  }
273
653
  }
654
+ u = result.length;
655
+ v = result[u - 1];
656
+ while (u-- > 0) {
657
+ result[u] = v;
658
+ v = p[v];
659
+ }
660
+ return result;
661
+ }
662
+
663
+ // src/binding.ts
664
+ function addEventListener(element, event, handler, options) {
665
+ element.addEventListener(event, handler, options);
666
+ const context = getActiveContext();
667
+ if (context) {
668
+ context.cleanup.add(() => {
669
+ element.removeEventListener(event, handler, options);
670
+ });
671
+ }
274
672
  }
275
- function bindNode(node, setter) {
276
- if (node instanceof HTMLInputElement) {
673
+ function bindElement(node, key, defaultValue, setter) {
674
+ if (isHtmlInputElement(node)) {
277
675
  switch (node.type) {
278
676
  case "checkbox":
279
- return addEventListener(node, "change", () => {
677
+ addEventListener(node, "change", () => {
280
678
  setter(Boolean(node.checked));
281
679
  });
282
- case "date":
283
- return addEventListener(node, "change", () => {
284
- setter(node.value ? node.value : "");
680
+ break;
681
+ case "radio":
682
+ addEventListener(node, "change", () => {
683
+ setter(node.checked ? node.value : "");
285
684
  });
685
+ break;
286
686
  case "file":
287
- return addEventListener(node, "change", () => {
288
- if (node.files) {
289
- setter(node.files);
290
- }
687
+ addEventListener(node, "change", () => {
688
+ setter(node.files);
291
689
  });
690
+ break;
292
691
  case "number":
293
- return addEventListener(node, "input", () => {
294
- const value = Number.parseFloat(node.value);
295
- setter(Number.isNaN(value) ? "" : String(value));
692
+ case "range":
693
+ addEventListener(node, "input", () => {
694
+ setter(node.value || "");
296
695
  });
297
- case "radio":
298
- return addEventListener(node, "change", () => {
299
- setter(node.checked ? node.value : "");
696
+ break;
697
+ case "date":
698
+ case "datetime-local":
699
+ case "month":
700
+ case "time":
701
+ case "week":
702
+ addEventListener(node, "change", () => {
703
+ setter(node.value || "");
300
704
  });
301
- case "text":
302
- return addEventListener(node, "input", () => {
705
+ break;
706
+ default:
707
+ addEventListener(node, "input", () => {
303
708
  setter(node.value);
304
709
  });
710
+ break;
305
711
  }
306
- }
307
- if (node instanceof HTMLSelectElement) {
308
- return addEventListener(node, "change", () => {
309
- setter(node.value);
712
+ } else if (isHtmlSelectElement(node)) {
713
+ addEventListener(node, "change", () => {
714
+ if (node.multiple) {
715
+ const values = Array.from(node.options).filter((option) => option.selected).map((option) => option.value);
716
+ setter(values);
717
+ } else {
718
+ setter(node.value);
719
+ }
310
720
  });
311
- }
312
- if (node instanceof HTMLTextAreaElement) {
313
- return addEventListener(node, "input", () => {
721
+ } else if (isHtmlTextAreaElement(node)) {
722
+ addEventListener(node, "input", () => {
314
723
  setter(node.value);
315
724
  });
316
725
  }
317
726
  }
318
- function addEventListener(node, eventName, handler) {
319
- node.addEventListener(eventName, handler);
320
- return () => node.removeEventListener(eventName, handler);
321
- }
322
- function closeHtmlTags(input) {
323
- const tagStack = [];
324
- const output = [];
325
- const tagPattern = /<\/?([\da-z-]+)([^>]*)>/gi;
326
- let lastIndex = 0;
327
- while (true) {
328
- const match = tagPattern.exec(input);
329
- if (!match) break;
330
- const [fullMatch, tagName] = match;
331
- const isEndTag = fullMatch[1] === "/";
332
- output.push(input.slice(lastIndex, match.index));
333
- lastIndex = match.index + fullMatch.length;
334
- if (isEndTag) {
335
- while (tagStack.length > 0 && tagStack[tagStack.length - 1] !== tagName) {
336
- const unclosedTag = tagStack.pop();
337
- if (unclosedTag) {
338
- output.push(`</${unclosedTag}>`);
339
- }
340
- }
341
- if (tagStack.length > 0) {
342
- tagStack.pop();
727
+ function insert(parent, nodeFactory, before, options) {
728
+ if (!parent) return;
729
+ const context = getActiveContext();
730
+ if (!context) return;
731
+ let renderedNodes = [];
732
+ const cleanup = signals.effect(() => {
733
+ const rawNodes = shared.isFunction(nodeFactory) ? nodeFactory() : nodeFactory;
734
+ const nodes = shared.coerceArray(rawNodes).map(normalizeNode);
735
+ renderedNodes = patchChildren(parent, renderedNodes, nodes, before);
736
+ });
737
+ context.cleanup.add(() => {
738
+ cleanup();
739
+ if (!(options == null ? void 0 : options.preserveOnCleanup)) {
740
+ renderedNodes.forEach((node) => removeNode(node));
741
+ }
742
+ renderedNodes.length = 0;
743
+ });
744
+ }
745
+ function mapNodes(template2, indexes) {
746
+ const len = indexes.length;
747
+ const tree = new Array(len);
748
+ const indexSet = new Set(indexes);
749
+ let index = 1;
750
+ let found = 0;
751
+ const walk = (node) => {
752
+ if (node.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {
753
+ if (indexSet.has(index)) {
754
+ tree[found++] = node;
755
+ if (found === len) return true;
343
756
  }
344
- } else if (!SELF_CLOSING_TAGS.includes(tagName)) {
345
- tagStack.push(tagName);
757
+ index++;
346
758
  }
347
- output.push(fullMatch);
348
- }
349
- output.push(input.slice(lastIndex));
350
- while (tagStack.length > 0) {
351
- const unclosedTag = tagStack.pop();
352
- if (unclosedTag) {
353
- output.push(`</${unclosedTag}>`);
759
+ let child = node.firstChild;
760
+ while (child) {
761
+ if (walk(child)) return true;
762
+ child = child.nextSibling;
354
763
  }
355
- }
356
- return output.join("");
357
- }
358
- function convertToHtmlTag(tagName) {
359
- return SELF_CLOSING_TAGS.includes(tagName) ? `<${tagName}/>` : `<${tagName}></${tagName}>`;
764
+ return false;
765
+ };
766
+ walk(template2);
767
+ return tree;
360
768
  }
361
- function extractSignal(signal$1) {
362
- if (signal.isSignal(signal$1)) {
363
- return signal$1.value;
364
- } else {
365
- return signal$1;
366
- }
367
- }
368
- var ComponentNode = class extends LifecycleContext {
369
- constructor(template, props, key) {
370
- super();
371
- this.template = template;
769
+
770
+ // src/component.ts
771
+ var _a;
772
+ _a = "normal" /* NORMAL */;
773
+ var Component = class {
774
+ constructor(component, props) {
775
+ this.component = component;
372
776
  this.props = props;
373
- this.key = key;
374
- this.emitter = /* @__PURE__ */ new Set();
375
- this.rootNode = null;
376
- this.trackMap = /* @__PURE__ */ new Map();
377
- this.key || (this.key = props && props.key);
378
- this.proxyProps = this.createProxyProps(props);
379
- }
380
- createProxyProps(props) {
381
- if (!props) return {};
382
- return signal.signalObject(
383
- props,
384
- (key) => shared.startsWith(key, EVENT_PREFIX) || shared.startsWith(key, UPDATE_PREFIX) || key === CHILDREN_PROP
385
- );
777
+ // component rendered node
778
+ this.renderedNode = null;
779
+ // component context
780
+ this.componentContext = null;
781
+ // component parent node
782
+ this.parentNode = null;
783
+ // component before node
784
+ this.beforeNode = null;
785
+ // component props
786
+ this.reactiveProps = {};
787
+ this._propSnapshots = {};
788
+ // component state
789
+ this.state = 0 /* INITIAL */;
790
+ // component context
791
+ this.context = null;
792
+ // component parent context
793
+ this.parentContext = null;
794
+ // component type
795
+ // @ts-ignore
796
+ this[_a] = true;
797
+ this.key = (props == null ? void 0 : props.key) ? normalizeKey(props.key) : getComponentKey(component);
798
+ this.reactiveProps = signals.shallowReactive(__spreadValues({}, this.props || {}));
799
+ this.parentContext = getActiveContext();
800
+ if (this.props) {
801
+ for (const key in this.props) {
802
+ const val = this.props[key];
803
+ if (shared.isObject(val) && val !== null) {
804
+ this._propSnapshots[key] = Array.isArray(val) ? [...val] : __spreadValues({}, val);
805
+ }
806
+ }
807
+ }
808
+ }
809
+ get isConnected() {
810
+ return this.state === 2 /* MOUNTED */;
386
811
  }
387
812
  get firstChild() {
388
- var _a, _b;
389
- return (_b = (_a = this.rootNode) == null ? void 0 : _a.firstChild) != null ? _b : null;
813
+ var _a2;
814
+ return (_a2 = this.renderedNode) != null ? _a2 : null;
815
+ }
816
+ mount(parentNode, beforeNode) {
817
+ this.parentNode = parentNode;
818
+ this.beforeNode = beforeNode || null;
819
+ this.state = 1 /* MOUNTING */;
820
+ if (this.renderedNode) {
821
+ insertNode(parentNode, this.renderedNode, beforeNode);
822
+ return this.renderedNode;
823
+ }
824
+ this.componentContext = createContext(this.parentContext);
825
+ pushContextStack(this.componentContext);
826
+ let result = this.component(this.reactiveProps);
827
+ if (shared.isFunction(result)) {
828
+ result = result(this.reactiveProps);
829
+ }
830
+ if (signals.isSignal(result) || signals.isComputed(result)) {
831
+ result = result.value;
832
+ }
833
+ this.renderedNode = result;
834
+ insertNode(parentNode, this.renderedNode, beforeNode);
835
+ this.applyProps(this.props || {});
836
+ this.state = 2 /* MOUNTED */;
837
+ if (this.componentContext) {
838
+ this.componentContext.isMount = true;
839
+ }
840
+ triggerLifecycleHook(LIFECYCLE.mount);
841
+ return this.renderedNode;
390
842
  }
391
- get isConnected() {
392
- var _a, _b;
393
- return (_b = (_a = this.rootNode) == null ? void 0 : _a.isConnected) != null ? _b : false;
394
- }
395
- mount(parent, before) {
396
- var _a, _b, _c, _d;
397
- if (!shared.isFunction(this.template)) {
398
- throw new Error("Template must be a function");
399
- }
400
- if (this.isConnected) {
401
- return (_b = (_a = this.rootNode) == null ? void 0 : _a.mount(parent, before)) != null ? _b : [];
402
- }
403
- this.initRef();
404
- this.rootNode = this.template(signal.useReactive(this.proxyProps, [CHILDREN_PROP]));
405
- const mountedNode = (_d = (_c = this.rootNode) == null ? void 0 : _c.mount(parent, before)) != null ? _d : [];
406
- this.callMountHooks();
407
- this.patchProps(this.props);
408
- this.removeRef();
409
- return mountedNode;
410
- }
411
- unmount() {
412
- var _a;
413
- this.callDestroyHooks();
414
- this.clearHooks();
415
- (_a = this.rootNode) == null ? void 0 : _a.unmount();
416
- this.rootNode = null;
417
- this.proxyProps = {};
418
- this.clearEmitter();
419
- }
420
- callMountHooks() {
421
- this.hooks.mounted.forEach((handler) => handler());
422
- }
423
- callDestroyHooks() {
424
- this.hooks.destroy.forEach((handler) => handler());
425
- }
426
- clearEmitter() {
427
- for (const cleanup of this.emitter) {
428
- cleanup();
429
- }
430
- this.emitter.clear();
431
- }
432
- inheritNode(node) {
433
- Object.assign(this.proxyProps, node.proxyProps);
434
- this.rootNode = node.rootNode;
435
- this.trackMap = node.trackMap;
436
- this.hooks = node.hooks;
437
- const props = this.props;
438
- this.props = node.props;
439
- this.patchProps(props);
440
- }
441
- getNodeTrack(trackKey) {
442
- let track = this.trackMap.get(trackKey);
443
- if (!track) {
444
- track = { cleanup: () => {
445
- } };
446
- this.trackMap.set(trackKey, track);
447
- }
448
- track.cleanup();
449
- return track;
450
- }
451
- patchProps(props) {
452
- var _a;
843
+ update(prevNode) {
844
+ if (this.key !== prevNode.key) {
845
+ this.mount(prevNode.parentNode, prevNode.beforeNode);
846
+ return this;
847
+ }
848
+ this.parentNode = prevNode.parentNode;
849
+ this.beforeNode = prevNode.beforeNode;
850
+ this.componentContext = prevNode.componentContext;
851
+ this.renderedNode = prevNode.renderedNode;
852
+ this.state = prevNode.state;
853
+ this.reactiveProps = prevNode.reactiveProps;
854
+ this._propSnapshots = prevNode._propSnapshots;
855
+ if (this.props) {
856
+ for (const key in this.props) {
857
+ if (key === "key") continue;
858
+ const newValue = this.props[key];
859
+ const oldValue = this.reactiveProps[key];
860
+ if (shared.isObject(newValue) && newValue !== null) {
861
+ const snapshot = this._propSnapshots[key];
862
+ if (!snapshot || !shallowCompare(newValue, snapshot)) {
863
+ const newSnapshot = Array.isArray(newValue) ? newValue.slice() : Object.assign({}, newValue);
864
+ this.reactiveProps[key] = newSnapshot;
865
+ this._propSnapshots[key] = newSnapshot;
866
+ }
867
+ } else {
868
+ if (shared.hasChanged(newValue, oldValue)) {
869
+ this.reactiveProps[key] = newValue;
870
+ if (this._propSnapshots[key]) {
871
+ delete this._propSnapshots[key];
872
+ }
873
+ }
874
+ }
875
+ }
876
+ }
877
+ if (!this.isConnected && this.parentNode) {
878
+ this.mount(this.parentNode, this.beforeNode);
879
+ }
880
+ if (this.componentContext) {
881
+ pushContextStack(this.componentContext);
882
+ this.applyProps(this.props || {});
883
+ triggerLifecycleHook(LIFECYCLE.update);
884
+ popContextStack();
885
+ }
886
+ return this;
887
+ }
888
+ forceUpdate() {
889
+ return __async(this, null, function* () {
890
+ if (this.state === 5 /* DESTROYED */ || !this.parentNode || !this.componentContext) {
891
+ return;
892
+ }
893
+ const prevNode = this.renderedNode;
894
+ let newNode;
895
+ try {
896
+ if (this.componentContext) {
897
+ pushContextStack(this.componentContext);
898
+ }
899
+ newNode = this.component(this.reactiveProps);
900
+ if (shared.isFunction(newNode)) {
901
+ newNode = newNode(this.reactiveProps);
902
+ }
903
+ if (signals.isSignal(newNode) || signals.isComputed(newNode)) {
904
+ newNode = newNode.value;
905
+ }
906
+ if (prevNode && newNode && prevNode !== newNode) {
907
+ if (this.parentNode) {
908
+ replaceNode(this.parentNode, newNode, prevNode);
909
+ this.renderedNode = newNode;
910
+ }
911
+ }
912
+ yield triggerLifecycleHook(LIFECYCLE.update);
913
+ } catch (_error) {
914
+ shared.error("Force update failed:", _error);
915
+ throw _error;
916
+ } finally {
917
+ if (this.componentContext) {
918
+ popContextStack();
919
+ }
920
+ }
921
+ });
922
+ }
923
+ /**
924
+ * Destroy component
925
+ */
926
+ destroy() {
927
+ if (this.state === 4 /* DESTROYING */ || this.state === 5 /* DESTROYED */) {
928
+ return;
929
+ }
930
+ this.state = 4 /* DESTROYING */;
931
+ const context = this.componentContext;
932
+ if (context) {
933
+ pushContextStack(context);
934
+ triggerLifecycleHook(LIFECYCLE.destroy);
935
+ destroyContext(context);
936
+ this.componentContext = null;
937
+ popContextStack();
938
+ }
939
+ const rendered = this.renderedNode;
940
+ if (rendered) {
941
+ removeNode(rendered);
942
+ }
943
+ this.renderedNode = null;
944
+ this.parentNode = null;
945
+ this.beforeNode = null;
946
+ this.reactiveProps = {};
947
+ this.props = void 0;
948
+ this.state = 5 /* DESTROYED */;
949
+ }
950
+ applyProps(props) {
453
951
  if (!props) {
454
952
  return;
455
953
  }
456
- for (const [key, prop] of Object.entries(props)) {
457
- if (shared.startsWith(key, EVENT_PREFIX) && ((_a = this.rootNode) == null ? void 0 : _a.firstChild)) {
458
- this.patchEventListener(key, prop);
459
- } else if (key === REF_KEY) {
460
- this.patchRef(prop);
461
- } else if (shared.startsWith(key, UPDATE_PREFIX)) {
462
- this.patchUpdateHandler(key, prop);
463
- } else if (key !== CHILDREN_PROP) {
464
- this.patchNormalProp(key, prop);
954
+ for (const [propName, propValue] of Object.entries(props)) {
955
+ if (shared.startsWith(propName, EVENT_PREFIX) && this.renderedNode) {
956
+ const eventName = propName.slice(2).toLowerCase();
957
+ if (shared.isHTMLElement(this.renderedNode)) {
958
+ addEventListener(this.renderedNode, eventName, propValue);
959
+ }
960
+ } else if (propName === REF_KEY && signals.isSignal(propValue)) {
961
+ propValue.value = this.renderedNode;
465
962
  }
466
963
  }
467
964
  this.props = props;
468
965
  }
469
- patchEventListener(key, prop) {
470
- const event = key.slice(2).toLowerCase();
471
- const cleanup = addEventListener(this.rootNode.nodes[0], event, prop);
472
- this.emitter.add(cleanup);
473
- }
474
- patchRef(prop) {
475
- var _a, _b;
476
- prop.value = (_b = (_a = this.rootNode) == null ? void 0 : _a.firstChild) != null ? _b : null;
477
- }
478
- patchUpdateHandler(key, prop) {
479
- this.props[key] = extractSignal(prop);
480
- }
481
- patchNormalProp(key, prop) {
482
- var _a, _b;
483
- const newValue = (_b = (_a = this.proxyProps)[key]) != null ? _b : _a[key] = signal.useSignal(prop);
484
- const track = this.getNodeTrack(key);
485
- track.cleanup = signal.useEffect(() => {
486
- newValue.value = shared.isFunction(prop) ? prop() : prop;
487
- });
488
- }
489
966
  };
967
+ function isComponent(node) {
968
+ return !!node && !!node["normal" /* NORMAL */];
969
+ }
970
+ function createComponent(componentFn, props) {
971
+ if (isComponent(componentFn)) {
972
+ return componentFn;
973
+ }
974
+ return new Component(componentFn, props);
975
+ }
490
976
 
491
- // src/patch.ts
492
- function patchChildren(parent, childrenMap, nextChildren, before) {
493
- const result = /* @__PURE__ */ new Map();
494
- const children = Array.from(childrenMap.values());
495
- if (children.length && nextChildren.length === 0) {
496
- clearChildren(parent, children, before);
497
- return result;
498
- }
499
- const replaces = [];
500
- const nextChildrenMap = mapKeys(nextChildren);
501
- let childIndex = 0;
502
- for (let [i, child] of nextChildren.entries()) {
503
- let currChild = children[childIndex];
504
- let currKey = getKey(currChild, i);
505
- while (currChild && !nextChildrenMap.has(currKey)) {
506
- removeChild(currChild);
507
- childrenMap.delete(currKey);
508
- currChild = children[++childIndex];
509
- currKey = getKey(currChild, i);
510
- }
511
- const key = getKey(child, i);
512
- const origChild = childrenMap.get(key);
513
- if (origChild) {
514
- child = patch(parent, origChild, child);
515
- }
516
- if (currChild) {
517
- if (currChild === origChild) {
518
- childIndex++;
519
- } else {
520
- const placeholder = document.createComment("");
521
- insertChild(parent, placeholder, currChild);
522
- replaces.push([placeholder, child]);
523
- }
524
- } else {
525
- insertChild(parent, child, before);
977
+ // src/renderer.ts
978
+ function template(html) {
979
+ let node;
980
+ const create = () => {
981
+ const template2 = document.createElement("template");
982
+ template2.innerHTML = html;
983
+ const firstChild = template2.content.firstChild;
984
+ if (!firstChild) {
985
+ throw new Error("Invalid template: empty content");
526
986
  }
527
- result.set(key, child);
987
+ return firstChild;
988
+ };
989
+ return () => (node || (node = create())).cloneNode(true);
990
+ }
991
+ function createApp(component, target) {
992
+ const container = shared.isString(target) ? document.querySelector(target) : target;
993
+ if (!container) {
994
+ shared.error(`Target element not found: ${target}`);
995
+ return;
996
+ }
997
+ const existingContext = container.innerHTML;
998
+ if (existingContext) {
999
+ shared.error(`Target element is not empty, it will be delete: ${target}`);
1000
+ container.innerHTML = "";
1001
+ }
1002
+ const rootComponent = createComponent(component);
1003
+ rootComponent.mount(container);
1004
+ return rootComponent;
1005
+ }
1006
+ function provide(key, value) {
1007
+ const context = getActiveContext();
1008
+ if (!context) {
1009
+ shared.error("provide must be called within a template");
1010
+ return;
1011
+ }
1012
+ context.provides.set(key, value);
1013
+ }
1014
+ function inject(key, defaultValue) {
1015
+ const context = getActiveContext();
1016
+ if (!context) {
1017
+ shared.error("inject must be called within a template");
1018
+ return defaultValue;
1019
+ }
1020
+ let currentContext = context;
1021
+ while (currentContext) {
1022
+ const value = currentContext.provides.get(key);
1023
+ if (!shared.isNil(value)) {
1024
+ return value;
1025
+ }
1026
+ currentContext = currentContext.parent;
528
1027
  }
529
- replaces.forEach(([placeholder, child]) => {
530
- replaceChild(parent, child, placeholder);
1028
+ return defaultValue;
1029
+ }
1030
+ function eventHandler(e) {
1031
+ let node = e.target;
1032
+ const key = `${e.type}`;
1033
+ const oriTarget = e.target;
1034
+ const oriCurrentTarget = e.currentTarget;
1035
+ const reTarget = (value) => Object.defineProperty(e, "target", {
1036
+ configurable: true,
1037
+ value
531
1038
  });
532
- childrenMap.forEach((child, key) => {
533
- if (child.isConnected && !result.has(key)) {
534
- removeChild(child);
1039
+ const handleNode = () => {
1040
+ const handler = node[`_$${key}`];
1041
+ if (handler && shared.isFunction(handler) && !node.disabled) {
1042
+ const data = node[`${key}Data`];
1043
+ data ? handler.call(node, data, e) : handler.call(node, e);
1044
+ if (e.cancelBubble) return false;
1045
+ }
1046
+ if (node.host && !shared.isString(node.host) && !node.host._$host && shared.isFunction(node.contains) && node.contains(e.target)) {
1047
+ reTarget(node.host);
1048
+ }
1049
+ return true;
1050
+ };
1051
+ const walkUpTree = () => {
1052
+ while (handleNode() && (node = node._$host || node.parentNode || node.host)) ;
1053
+ };
1054
+ Object.defineProperty(e, "currentTarget", {
1055
+ configurable: true,
1056
+ get() {
1057
+ return node || document;
535
1058
  }
536
1059
  });
537
- return result;
1060
+ if (e.composedPath) {
1061
+ const path = e.composedPath();
1062
+ reTarget(path[0]);
1063
+ for (let i = 0; i < path.length - 2; i++) {
1064
+ node = path[i];
1065
+ if (!handleNode()) break;
1066
+ if (node._$host) {
1067
+ node = node._$host;
1068
+ walkUpTree();
1069
+ break;
1070
+ }
1071
+ if (node.parentNode === oriCurrentTarget) {
1072
+ break;
1073
+ }
1074
+ }
1075
+ } else walkUpTree();
1076
+ reTarget(oriTarget);
538
1077
  }
539
- function clearChildren(parent, children, before) {
540
- if (parent.childNodes.length === children.length + (before ? 1 : 0)) {
541
- parent.innerHTML = "";
542
- if (before) {
543
- insertChild(parent, before);
1078
+ var $EVENTS = Symbol("_$EVENTS");
1079
+ function delegateEvents(eventNames, document2 = window.document) {
1080
+ const docWithEvents = document2;
1081
+ const eventSet = docWithEvents[$EVENTS] || (docWithEvents[$EVENTS] = /* @__PURE__ */ new Set());
1082
+ for (const name of eventNames) {
1083
+ if (!eventSet.has(name)) {
1084
+ eventSet.add(name);
1085
+ document2.addEventListener(name, eventHandler);
544
1086
  }
1087
+ }
1088
+ }
1089
+ function patchClass(el, prev, next, isSVG = false) {
1090
+ if (prev === next) {
1091
+ return;
1092
+ }
1093
+ const normalizedNext = normalizeClass(next);
1094
+ const normalizedPrev = normalizeClass(prev);
1095
+ if (normalizedNext && normalizedPrev === normalizedNext) {
1096
+ return;
1097
+ }
1098
+ if (!normalizedNext) {
1099
+ el.removeAttribute("class");
1100
+ } else if (isSVG) {
1101
+ el.setAttribute("class", normalizedNext);
545
1102
  } else {
546
- const range = document.createRange();
547
- const child = children[0];
548
- const start = isJsxElement(child) ? child.firstChild : child;
549
- range.setStartBefore(start);
550
- if (before) {
551
- range.setEndBefore(before);
552
- } else {
553
- range.setEndAfter(parent);
554
- }
555
- range.deleteContents();
1103
+ el.className = normalizedNext;
556
1104
  }
557
- children.forEach((node) => {
558
- if (isJsxElement(node)) {
559
- node.unmount();
560
- }
561
- });
562
1105
  }
563
- function patch(parent, node, next) {
564
- if (node === next) {
565
- return node;
1106
+ function normalizeClass(value) {
1107
+ if (value == null) {
1108
+ return "";
1109
+ }
1110
+ if (typeof value === "string") {
1111
+ return value.trim();
566
1112
  }
567
- if (isJsxElement(node) && isJsxElement(next) && node.template === next.template) {
568
- next.inheritNode(node);
569
- return next;
1113
+ if (shared.isArray(value)) {
1114
+ return value.map(normalizeClass).filter(Boolean).join(" ");
570
1115
  }
571
- if (node instanceof Text && next instanceof Text) {
572
- if (node.textContent !== next.textContent) {
573
- node.textContent = next.textContent;
1116
+ if (shared.isObject(value)) {
1117
+ const result = [];
1118
+ for (const key in value) {
1119
+ if (value[key]) {
1120
+ result.push(key);
1121
+ }
574
1122
  }
575
- return node;
1123
+ return result.join(" ");
576
1124
  }
577
- replaceChild(parent, next, node);
578
- return next;
1125
+ return String(value).trim();
579
1126
  }
580
- function mapKeys(children) {
581
- const result = /* @__PURE__ */ new Map();
582
- for (const [i, child] of children.entries()) {
583
- const key = getKey(child, i);
584
- result.set(key, child);
1127
+ var importantRE = /\s*!important$/;
1128
+ var prefixes = ["Webkit", "Moz", "ms"];
1129
+ var prefixCache = {};
1130
+ function patchStyle(el, prev, next) {
1131
+ const style = el.style;
1132
+ const isCssString = shared.isString(next);
1133
+ if (next && isCssString) {
1134
+ if (prev !== next) {
1135
+ style.cssText = next;
1136
+ }
1137
+ return;
585
1138
  }
586
- return result;
587
- }
588
- function getKey(node, index) {
589
- if (isJsxElement(node)) {
590
- const jsxKey = node.key;
591
- if (jsxKey !== void 0 && jsxKey !== null) {
592
- return String(jsxKey);
1139
+ if (!next) {
1140
+ if (prev) {
1141
+ el.removeAttribute("style");
593
1142
  }
1143
+ return;
594
1144
  }
595
- return `_$${index}$`;
596
- }
597
-
598
- // src/templateNode.ts
599
- var TemplateNode = class {
600
- constructor(template, props, key) {
601
- this.template = template;
602
- this.props = props;
603
- this.key = key;
604
- // Private properties for managing the node's state
605
- this.treeMap = /* @__PURE__ */ new Map();
606
- this.mounted = false;
607
- this.nodes = [];
608
- this.trackMap = /* @__PURE__ */ new Map();
609
- this.bindValueKeys = [];
610
- this.parent = null;
611
- this.key || (this.key = props && props.key);
612
- if (renderContext.isSSR) {
613
- this.componentIndex = getComponentIndex(this.template);
1145
+ if (prev && !shared.isString(prev)) {
1146
+ for (const key in prev) {
1147
+ if (!next || next[key] == null) {
1148
+ setStyle(style, key, "");
1149
+ }
1150
+ }
1151
+ } else if (prev && shared.isString(prev)) {
1152
+ const prevStyles = prev.split(";");
1153
+ for (const stylePart of prevStyles) {
1154
+ const colonIndex = stylePart.indexOf(":");
1155
+ if (colonIndex > 0) {
1156
+ const key = stylePart.slice(0, colonIndex).trim();
1157
+ if (next && shared.isObject(next) && next[key] == null) {
1158
+ setStyle(style, key, "");
1159
+ }
1160
+ }
614
1161
  }
615
1162
  }
616
- get firstChild() {
617
- var _a;
618
- return (_a = this.nodes[0]) != null ? _a : null;
1163
+ if (next && !shared.isString(next)) {
1164
+ for (const key in next) {
1165
+ const value = next[key];
1166
+ if ((!prev || shared.isString(prev) || prev[key] !== value) && value != null) {
1167
+ setStyle(style, key, value);
1168
+ }
1169
+ }
619
1170
  }
620
- get isConnected() {
621
- return this.mounted;
1171
+ }
1172
+ function setStyle(style, name, val) {
1173
+ if (shared.isArray(val)) {
1174
+ for (const element of val) {
1175
+ setStyle(style, name, element);
1176
+ }
1177
+ return;
622
1178
  }
623
- addEventListener() {
1179
+ if (val == null || val === "") {
1180
+ val = "";
624
1181
  }
625
- removeEventListener() {
1182
+ if (name.startsWith("--")) {
1183
+ style.setProperty(name, val);
1184
+ return;
626
1185
  }
627
- mount(parent, before) {
628
- var _a;
629
- this.parent = parent;
630
- if (this.isConnected) {
631
- this.nodes.forEach((node) => insertChild(parent, node, before));
632
- return this.nodes;
633
- }
634
- if (shared.isArray(this.template)) {
635
- this.template = createTemplate(this.template.join(""));
1186
+ const prefixed = autoPrefix(style, name);
1187
+ if (typeof val === "string" && importantRE.test(val)) {
1188
+ style.setProperty(shared.camelCase(prefixed), val.replace(importantRE, ""), "important");
1189
+ } else {
1190
+ style[prefixed] = val;
1191
+ }
1192
+ }
1193
+ function autoPrefix(style, rawName) {
1194
+ const cached = prefixCache[rawName];
1195
+ if (cached) {
1196
+ return cached;
1197
+ }
1198
+ let name = shared.camelCase(rawName);
1199
+ if (name !== "filter" && name in style) {
1200
+ return prefixCache[rawName] = name;
1201
+ }
1202
+ name = shared.capitalize(name);
1203
+ for (const prefix of prefixes) {
1204
+ const prefixed = prefix + name;
1205
+ if (prefixed in style) {
1206
+ return prefixCache[rawName] = prefixed;
636
1207
  }
637
- const cloneNode = this.template.content.cloneNode(true);
638
- const firstChild = cloneNode.firstChild;
639
- if ((_a = firstChild == null ? void 0 : firstChild.hasAttribute) == null ? void 0 : _a.call(firstChild, "_svg_")) {
640
- firstChild.remove();
641
- firstChild.childNodes.forEach((node) => {
642
- cloneNode.append(node);
643
- });
1208
+ }
1209
+ return rawName;
1210
+ }
1211
+ function patchAttr(el, key, prev, next) {
1212
+ if (key === REF_KEY) {
1213
+ prev.value = el;
1214
+ return;
1215
+ }
1216
+ if (key === KEY_PROP) {
1217
+ if (next == null) {
1218
+ setNodeKey(el, void 0);
1219
+ } else {
1220
+ setNodeKey(el, String(next));
644
1221
  }
645
- this.nodes = Array.from(cloneNode.childNodes);
646
- if (renderContext.isSSR) {
647
- this.mapSSGNodeTree(parent);
1222
+ return;
1223
+ }
1224
+ const elementIsSVG = (el == null ? void 0 : el.namespaceURI) === SVG_NAMESPACE;
1225
+ const isXlink = elementIsSVG && key.startsWith("xlink:");
1226
+ const isXmlns = elementIsSVG && key.startsWith("xmlns:");
1227
+ const isBoolean = shared.isSpecialBooleanAttr(key) || shared.isBooleanAttr(key);
1228
+ if (prev === next) {
1229
+ return;
1230
+ }
1231
+ const lowerKey = key.toLowerCase();
1232
+ if (/^on[a-z]+/.test(lowerKey)) {
1233
+ return;
1234
+ }
1235
+ if (lowerKey === "innerhtml") {
1236
+ return;
1237
+ }
1238
+ if (next == null) {
1239
+ if (isXlink) {
1240
+ el.removeAttributeNS(XLINK_NAMESPACE, key.slice(6));
1241
+ } else if (isXmlns) {
1242
+ const localName = key.slice(6);
1243
+ el.removeAttributeNS(XMLNS_NAMESPACE, localName);
648
1244
  } else {
649
- this.mapNodeTree(parent, cloneNode);
1245
+ el.removeAttribute(key);
650
1246
  }
651
- insertChild(parent, cloneNode, before);
652
- this.patchProps(this.props);
653
- this.mounted = true;
654
- return this.nodes;
1247
+ return;
655
1248
  }
656
- unmount() {
657
- var _a, _b;
658
- this.trackMap.forEach((track) => {
659
- track.cleanup && track.cleanup();
660
- });
661
- this.trackMap.clear();
662
- this.treeMap.clear();
663
- this.nodes.forEach((node) => removeChild(node));
664
- if (!this.template.innerHTML && !this.nodes.length) {
665
- const children = (_b = (_a = this.props) == null ? void 0 : _a[FRAGMENT_PROP_KEY]) == null ? void 0 : _b.children;
666
- if (children) {
667
- if (shared.isArray(children)) {
668
- children.forEach((child) => {
669
- this.deleteFragmentTextNode(child);
670
- });
671
- } else {
672
- this.deleteFragmentTextNode(children);
673
- }
674
- }
675
- }
676
- this.nodes = [];
677
- this.mounted = false;
1249
+ if (isXlink) {
1250
+ el.setAttributeNS(XLINK_NAMESPACE, key, String(next));
1251
+ return;
678
1252
  }
679
- deleteFragmentTextNode(child) {
680
- if (shared.isPrimitive(child)) {
681
- if (this.parent && this.parent.childNodes.length) {
682
- this.parent.childNodes.forEach((node) => {
683
- if (node.nodeType === Node.TEXT_NODE && node.textContent === `${child}`) {
684
- this.parent.removeChild(node);
685
- }
686
- });
687
- }
688
- } else {
689
- removeChild(child);
690
- }
691
- }
692
- inheritNode(node) {
693
- this.mounted = node.mounted;
694
- this.nodes = node.nodes;
695
- this.trackMap = node.trackMap;
696
- this.treeMap = node.treeMap;
697
- const props = this.props;
698
- this.props = node.props;
699
- this.patchProps(props);
700
- }
701
- mapSSGNodeTree(parent) {
702
- this.treeMap.set(0, parent);
703
- this.walkNodeTree(parent, this.handleSSGNode.bind(this));
704
- }
705
- // Private method to map node tree
706
- mapNodeTree(parent, tree) {
707
- let index = 1;
708
- this.treeMap.set(0, parent);
709
- const handleNode = (node) => {
710
- if (node.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {
711
- this.treeMap.set(index++, node);
712
- }
713
- };
714
- this.walkNodeTree(tree, handleNode);
1253
+ if (isXmlns) {
1254
+ el.setAttributeNS(XMLNS_NAMESPACE, key, String(next));
1255
+ return;
715
1256
  }
716
- walkNodeTree(node, handler) {
717
- if (node.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {
718
- handler(node);
1257
+ if (isBoolean) {
1258
+ if (shared.includeBooleanAttr(next)) {
1259
+ el.setAttribute(key, "");
1260
+ } else {
1261
+ el.removeAttribute(key);
719
1262
  }
720
- let child = node.firstChild;
721
- while (child) {
722
- this.walkNodeTree(child, handler);
723
- child = child.nextSibling;
1263
+ return;
1264
+ }
1265
+ const attrValue = shared.isSymbol(next) ? String(next) : next;
1266
+ const isUrlAttr = lowerKey === "href" || lowerKey === "src" || lowerKey === "xlink:href";
1267
+ if (isUrlAttr && typeof attrValue === "string") {
1268
+ const v = attrValue.trim().toLowerCase();
1269
+ if (v.startsWith("javascript:") || v.startsWith("data:")) {
1270
+ return;
724
1271
  }
725
1272
  }
726
- handleSSGNode(node) {
727
- var _a;
728
- if (node.nodeType === Node.COMMENT_NODE) {
729
- const [type, index] = ((_a = node.textContent) == null ? void 0 : _a.split("-")) || [];
730
- if (0 /* TEXT */ === +type && +index === this.componentIndex) {
731
- const textNode = node.nextSibling;
732
- this.treeMap.set(+index, textNode);
733
- }
734
- } else if (node.nodeType !== Node.TEXT_NODE) {
735
- const { ci = "-1", hk } = (node == null ? void 0 : node.dataset) || {};
736
- if (hk && +ci === this.componentIndex) {
737
- this.treeMap.set(+hk, node);
1273
+ if (elementIsSVG) {
1274
+ el.setAttribute(key, String(attrValue));
1275
+ } else {
1276
+ if (key in el) {
1277
+ try {
1278
+ el[key] = attrValue;
1279
+ } catch (e) {
1280
+ el.setAttribute(key, String(attrValue));
738
1281
  }
1282
+ } else {
1283
+ el.setAttribute(key, String(attrValue));
739
1284
  }
740
1285
  }
741
- patchProps(props) {
742
- if (!props) return;
743
- Object.entries(props).forEach(([key, value]) => {
744
- const index = Number(key);
745
- const node = this.treeMap.get(index);
746
- if (node) {
747
- this.patchProp(key, node, value, index === 0);
1286
+ }
1287
+
1288
+ // src/operations/event.ts
1289
+ function addEvent(el, event, handler, options) {
1290
+ if (!(options == null ? void 0 : options.delegate)) {
1291
+ el.addEventListener(event, handler, options);
1292
+ return () => el.removeEventListener(event, handler, options);
1293
+ }
1294
+ const selector = options.delegate;
1295
+ const wrappedHandler = (e) => {
1296
+ const target = e.target;
1297
+ if (target.matches(selector) || target.closest(selector)) {
1298
+ handler.call(el, e);
1299
+ }
1300
+ };
1301
+ const cleanOptions = __spreadValues({}, options);
1302
+ cleanOptions.delegate = void 0;
1303
+ el.addEventListener(event, wrappedHandler, cleanOptions);
1304
+ return () => {
1305
+ el.removeEventListener(event, wrappedHandler, cleanOptions);
1306
+ };
1307
+ }
1308
+
1309
+ // src/components/Fragment.ts
1310
+ function Fragment(props) {
1311
+ if (typeof document === "undefined") {
1312
+ const children2 = props.children;
1313
+ if (!children2) return "";
1314
+ const childArray = Array.isArray(children2) ? children2 : [children2];
1315
+ return childArray.map((child) => String(child || "")).join("");
1316
+ }
1317
+ const fragment = document.createDocumentFragment();
1318
+ const children = props.children;
1319
+ if (children) {
1320
+ const childArray = Array.isArray(children) ? children : [children];
1321
+ childArray.forEach((child) => {
1322
+ if (child != null) {
1323
+ const normalized = normalizeNode(child);
1324
+ if (normalized) {
1325
+ insertNode(fragment, normalized);
1326
+ }
748
1327
  }
749
1328
  });
750
- this.props = props;
751
1329
  }
752
- patchProp(key, node, props, isRoot) {
753
- if (!props) return;
754
- Object.entries(props).forEach(([attr, value]) => {
755
- if (attr === CHILDREN_PROP && value) {
756
- this.patchChildren(key, node, value, isRoot);
757
- } else if (attr === REF_KEY) {
758
- props[attr].value = node;
759
- } else if (shared.startsWith(attr, EVENT_PREFIX)) {
760
- this.patchEventListener(key, node, attr, value);
761
- } else {
762
- if (this.bindValueKeys.includes(attr)) return;
763
- const updateFn = this.getBindUpdateValue(props, key, attr);
764
- this.patchAttribute(key, node, attr, value, updateFn);
1330
+ return fragment;
1331
+ }
1332
+ Fragment["fragment" /* FRAGMENT */] = true;
1333
+ function isFragment(node) {
1334
+ return !!node && !!node["fragment" /* FRAGMENT */];
1335
+ }
1336
+ function Portal(props) {
1337
+ if (typeof document === "undefined") {
1338
+ const children = props.children;
1339
+ if (!children) return "";
1340
+ const childArray = shared.isArray(children) ? children : [children];
1341
+ return childArray.map((child) => String(child || "")).join("");
1342
+ }
1343
+ const placeholder = document.createComment("portal");
1344
+ placeholder["portal" /* PORTAL */] = true;
1345
+ onMount(() => {
1346
+ const targetElement = shared.isString(props.target) ? document.querySelector(props.target) : props.target;
1347
+ if (!targetElement) {
1348
+ {
1349
+ shared.warn(`[Portal] Target element not found: ${props.target}`);
765
1350
  }
766
- });
767
- }
768
- getBindUpdateValue(props, key, attr) {
769
- const updateKey = `${UPDATE_PREFIX}${shared.capitalize(attr)}`;
770
- if (updateKey && props[updateKey] && shared.isFunction(props[updateKey])) {
771
- this.bindValueKeys.push(updateKey);
772
- return props[updateKey];
1351
+ return;
773
1352
  }
774
- }
775
- patchChildren(key, node, children, isRoot) {
776
- if (!shared.isArray(children)) {
777
- const trackKey = `${key}:${CHILDREN_PROP}:0`;
778
- const track = this.getNodeTrack(trackKey, true, isRoot);
779
- this.patchChild(track, node, children, null);
780
- } else {
781
- children.filter(Boolean).forEach((item, index) => {
782
- var _a;
783
- const [child, path] = shared.isArray(item) ? item : [item, null];
784
- const before = shared.isNil(path) ? null : (_a = this.treeMap.get(path)) != null ? _a : null;
785
- const trackKey = `${key}:${CHILDREN_PROP}:${index}`;
786
- const track = this.getNodeTrack(trackKey, true, isRoot);
787
- this.patchChild(track, node, child, before);
1353
+ const children = props.children;
1354
+ if (children) {
1355
+ const childArray = shared.isArray(children) ? children : [children];
1356
+ childArray.forEach((child) => {
1357
+ if (child != null) {
1358
+ const normalized = normalizeNode(child);
1359
+ if (normalized) {
1360
+ insertNode(targetElement, normalized);
1361
+ }
1362
+ }
788
1363
  });
789
1364
  }
790
- }
791
- patchEventListener(key, node, attr, listener) {
792
- const eventName = attr.slice(2).toLowerCase();
793
- const track = this.getNodeTrack(`${key}:${attr}`);
794
- track.cleanup = addEventListener(node, eventName, listener);
795
- }
796
- patchAttribute(key, element, attr, value, updateFn) {
797
- const track = this.getNodeTrack(`${key}:${attr}`);
798
- const val = shared.isFunction(value) ? value() : value;
799
- const triggerValue = signal.isSignal(val) ? val : signal.shallowSignal(val);
800
- setAttribute(element, attr, triggerValue.value);
801
- const cleanup = signal.useEffect(() => {
802
- const val2 = shared.isFunction(value) ? value() : value;
803
- if (shared.isPlainObject(val2) && shared.isPlainObject(triggerValue.peek()) && JSON.stringify(triggerValue.value) === JSON.stringify(val2))
804
- return;
805
- triggerValue.value = signal.isSignal(val2) ? val2.value : val2;
806
- setAttribute(element, attr, triggerValue.value);
807
- });
808
- let cleanupBind;
809
- if (updateFn && shared.isHTMLElement(element)) {
810
- cleanupBind = bindNode(element, (value2) => {
811
- updateFn(value2);
812
- });
1365
+ });
1366
+ return placeholder;
1367
+ }
1368
+ Portal["portal" /* PORTAL */] = true;
1369
+ function isPortal(node) {
1370
+ return !!node && !!node["portal" /* PORTAL */];
1371
+ }
1372
+ var SuspenseContext = Symbol("SuspenseContext");
1373
+ function Suspense(props) {
1374
+ if (shared.isUndefined(document)) {
1375
+ const fallback = props.fallback;
1376
+ if (fallback) {
1377
+ return String(fallback || "");
813
1378
  }
814
- track.cleanup = () => {
815
- cleanup && cleanup();
816
- cleanupBind && cleanupBind();
817
- };
818
- }
819
- getNodeTrack(trackKey, trackLastNodes, isRoot) {
820
- let track = this.trackMap.get(trackKey);
821
- if (!track) {
822
- track = { cleanup: () => {
823
- } };
824
- if (trackLastNodes) {
825
- track.lastNodes = /* @__PURE__ */ new Map();
1379
+ return "";
1380
+ }
1381
+ const container = document.createElement("div");
1382
+ container.style.display = "contents";
1383
+ let isMounted = true;
1384
+ let pendingCount = 0;
1385
+ let isShowingFallback = false;
1386
+ let resolvedChildren = null;
1387
+ const showFallback = () => {
1388
+ if (isShowingFallback) return;
1389
+ isShowingFallback = true;
1390
+ while (container.firstChild) {
1391
+ container.removeChild(container.firstChild);
1392
+ }
1393
+ if (props.fallback != null) {
1394
+ const normalized = normalizeNode(props.fallback);
1395
+ if (normalized) {
1396
+ insertNode(container, normalized);
826
1397
  }
827
- if (isRoot) {
828
- track.isRoot = true;
1398
+ }
1399
+ };
1400
+ const showChildren = () => {
1401
+ if (!isShowingFallback) return;
1402
+ const hasContent = resolvedChildren || props.children != null && !shared.isPromise(props.children);
1403
+ if (!hasContent) {
1404
+ return;
1405
+ }
1406
+ isShowingFallback = false;
1407
+ while (container.firstChild) {
1408
+ container.removeChild(container.firstChild);
1409
+ }
1410
+ if (resolvedChildren) {
1411
+ renderChildren(resolvedChildren);
1412
+ } else if (props.children != null && !shared.isPromise(props.children)) {
1413
+ renderChildren(props.children);
1414
+ }
1415
+ };
1416
+ const renderChildren = (children2) => {
1417
+ while (container.firstChild) {
1418
+ container.removeChild(container.firstChild);
1419
+ }
1420
+ if (children2 == null) return;
1421
+ const currentContext = getActiveContext();
1422
+ const childArray = shared.isArray(children2) ? children2 : [children2];
1423
+ childArray.forEach((child) => {
1424
+ if (child != null) {
1425
+ if (isComponent(child)) {
1426
+ child.parentContext = currentContext;
1427
+ }
1428
+ const normalized = normalizeNode(child);
1429
+ if (normalized) {
1430
+ insertNode(container, normalized);
1431
+ }
1432
+ }
1433
+ });
1434
+ if (isShowingFallback) {
1435
+ while (container.firstChild) {
1436
+ container.removeChild(container.firstChild);
1437
+ }
1438
+ if (props.fallback != null) {
1439
+ const normalized = normalizeNode(props.fallback);
1440
+ if (normalized) {
1441
+ insertNode(container, normalized);
1442
+ }
829
1443
  }
830
- this.trackMap.set(trackKey, track);
831
1444
  }
832
- track.cleanup && track.cleanup();
833
- return track;
834
- }
835
- patchChild(track, parent, child, before) {
836
- if (shared.isFunction(child)) {
837
- track.cleanup = signal.useEffect(() => {
838
- const nextNodes = shared.coerceArray(child()).map(coerceNode);
839
- if (renderContext.isSSR) {
840
- track.lastNodes = this.reconcileChildren(parent, nextNodes, before);
841
- } else {
842
- track.lastNodes = patchChildren(parent, track.lastNodes, nextNodes, before);
1445
+ };
1446
+ const suspenseContext = {
1447
+ register: (promise) => {
1448
+ pendingCount++;
1449
+ showFallback();
1450
+ promise.then(() => {
1451
+ if (!isMounted) return;
1452
+ pendingCount--;
1453
+ if (pendingCount === 0) {
1454
+ showChildren();
843
1455
  }
844
- });
845
- } else {
846
- shared.coerceArray(child).forEach((node, index) => {
847
- const newNode = coerceNode(node);
848
- const key = getKey(newNode, index);
849
- if (renderContext.isSSR) {
850
- track.lastNodes = this.reconcileChildren(parent, [newNode], before);
851
- } else {
852
- track.lastNodes.set(key, newNode);
853
- insertChild(parent, newNode, before);
1456
+ }).catch((error10) => {
1457
+ {
1458
+ shared.warn("[Suspense] Resource failed:", error10);
1459
+ }
1460
+ if (!isMounted) return;
1461
+ pendingCount--;
1462
+ if (pendingCount === 0) {
1463
+ showChildren();
854
1464
  }
855
1465
  });
1466
+ },
1467
+ increment: () => {
1468
+ pendingCount++;
1469
+ showFallback();
1470
+ },
1471
+ decrement: () => {
1472
+ pendingCount--;
1473
+ if (pendingCount === 0) {
1474
+ showChildren();
1475
+ }
856
1476
  }
1477
+ };
1478
+ provide(SuspenseContext, suspenseContext);
1479
+ const children = props.children;
1480
+ if (shared.isPromise(children)) {
1481
+ children.then((resolved) => {
1482
+ resolvedChildren = resolved;
1483
+ }).catch(() => {
1484
+ });
1485
+ suspenseContext.register(children);
1486
+ } else if (children != null) {
1487
+ renderChildren(children);
1488
+ } else {
1489
+ showFallback();
857
1490
  }
858
- reconcileChildren(parent, nextNodes, before) {
859
- const result = /* @__PURE__ */ new Map();
860
- const textNodes = Array.from(parent.childNodes).filter(
861
- (node) => {
862
- var _a, _b;
863
- return node.nodeType === Node.TEXT_NODE && ((_a = node.previousSibling) == null ? void 0 : _a.nodeType) === Node.COMMENT_NODE && ((_b = node.nextSibling) == null ? void 0 : _b.nodeType) === Node.COMMENT_NODE;
1491
+ onDestroy(() => {
1492
+ isMounted = false;
1493
+ while (container.firstChild) {
1494
+ container.removeChild(container.firstChild);
1495
+ }
1496
+ });
1497
+ return container;
1498
+ }
1499
+ Suspense["suspense" /* SUSPENSE */] = true;
1500
+ function isSuspense(node) {
1501
+ return !!node && !!node["suspense" /* SUSPENSE */];
1502
+ }
1503
+ function createResource(fetcher, options) {
1504
+ const value = signals.signal(options == null ? void 0 : options.initialValue);
1505
+ const loading = signals.signal(true);
1506
+ const error10 = signals.signal(null);
1507
+ const state = signals.signal("pending");
1508
+ let fetchId = 0;
1509
+ let currentPromise = null;
1510
+ const fetch = () => __async(null, null, function* () {
1511
+ const currentFetchId = ++fetchId;
1512
+ loading.value = true;
1513
+ state.value = "pending";
1514
+ error10.value = null;
1515
+ const promise = fetcher();
1516
+ currentPromise = promise.then(() => {
1517
+ });
1518
+ try {
1519
+ const result = yield promise;
1520
+ if (currentFetchId === fetchId) {
1521
+ value.value = result;
1522
+ state.value = "ready";
1523
+ loading.value = false;
864
1524
  }
865
- );
866
- nextNodes.forEach((node, index) => {
867
- const key = getKey(node, index);
868
- if (node.nodeType === Node.TEXT_NODE) {
869
- textNodes.forEach((ne) => {
870
- if (node.textContent === ne.textContent) {
871
- parent.replaceChild(node, ne);
872
- }
873
- });
874
- } else {
875
- insertChild(parent, node, before);
1525
+ } catch (error_) {
1526
+ if (currentFetchId === fetchId) {
1527
+ error10.value = error_ instanceof Error ? error_ : new Error(String(error_));
1528
+ state.value = "errored";
1529
+ loading.value = false;
876
1530
  }
877
- result.set(key, node);
878
- });
879
- return result;
1531
+ }
1532
+ });
1533
+ fetch();
1534
+ const resource = (() => {
1535
+ if (loading.value && currentPromise) {
1536
+ const suspenseContext = inject(SuspenseContext, null);
1537
+ if (suspenseContext) {
1538
+ suspenseContext.register(currentPromise);
1539
+ }
1540
+ }
1541
+ return value.value;
1542
+ });
1543
+ resource.loading = loading;
1544
+ resource.error = error10;
1545
+ resource.state = state;
1546
+ const actions = {
1547
+ mutate: (newValue) => {
1548
+ value.value = newValue;
1549
+ state.value = "ready";
1550
+ loading.value = false;
1551
+ error10.value = null;
1552
+ },
1553
+ refetch: () => __async(null, null, function* () {
1554
+ yield fetch();
1555
+ })
1556
+ };
1557
+ return [resource, actions];
1558
+ }
1559
+ var hydrationCounter = 0;
1560
+ function getHydrationKey() {
1561
+ return `${hydrationCounter++}`;
1562
+ }
1563
+ function resetHydrationKey() {
1564
+ hydrationCounter = 0;
1565
+ }
1566
+ function endHydration() {
1567
+ }
1568
+ function convertToString(content, isSvg = false) {
1569
+ if (shared.isNil(content)) {
1570
+ return "";
880
1571
  }
881
- };
882
-
883
- // src/jsxRenderer.ts
884
- function h(template, props, key) {
885
- if (shared.isString(template)) {
886
- const isEmptyTemplate = template === EMPTY_TEMPLATE;
887
- const htmlTemplate = isEmptyTemplate ? EMPTY_TEMPLATE : convertToHtmlTag(template);
888
- props = { [isEmptyTemplate ? FRAGMENT_PROP_KEY : SINGLE_PROP_KEY]: props };
889
- return new TemplateNode(createTemplate(htmlTemplate), props, key);
1572
+ if (shared.isString(content)) {
1573
+ return content;
890
1574
  }
891
- if (shared.isFunction(template)) {
892
- return new ComponentNode(template, props, key);
1575
+ if (shared.isArray(content)) {
1576
+ return content.map((item) => convertToString(item, isSvg)).join("");
893
1577
  }
894
- return new TemplateNode(template, props, key);
895
- }
896
- function isComponent(node) {
897
- return node instanceof ComponentNode;
1578
+ if (shared.isFunction(content)) {
1579
+ return convertToString(content(), isSvg);
1580
+ }
1581
+ return String(content);
898
1582
  }
899
- function isJsxElement(node) {
900
- return node instanceof ComponentNode || node instanceof TemplateNode;
1583
+ function addAttributes(htmlContent, hydrationId) {
1584
+ const rootElementRegex = /^<([a-z]+)(\s*)([^>]*)>/i;
1585
+ const indexAttributeRegex = /data-idx="(\d+)"/g;
1586
+ const commentRegex = /<!--(.*?)-->/g;
1587
+ const enhancedHtml = htmlContent.replace(rootElementRegex, `<$1$2$3 data-hk="${hydrationId}">`).replaceAll(indexAttributeRegex, `data-idx="${hydrationId}-$1"`).replaceAll(commentRegex, `<!--${hydrationId}-$1-->`);
1588
+ return enhancedHtml;
901
1589
  }
902
- function createTemplate(html) {
903
- const template = document.createElement("template");
904
- template.innerHTML = closeHtmlTags(html);
905
- return template;
1590
+
1591
+ // src/server/render.ts
1592
+ function renderToString(component, props) {
1593
+ if (!shared.isFunction(component)) {
1594
+ shared.error("Component must be a function");
1595
+ return "";
1596
+ }
1597
+ resetHydrationKey();
1598
+ const result = component(props);
1599
+ return convertToString(result);
906
1600
  }
907
- function Fragment(props) {
908
- return h(createTemplate(EMPTY_TEMPLATE), {
909
- [FRAGMENT_PROP_KEY]: {
910
- children: shared.isArray(props.children) ? props.children.filter(Boolean) : [props.children]
1601
+ function render(templates, hydrationKey, ...components) {
1602
+ let content = "";
1603
+ let index = 0;
1604
+ for (const template2 of templates) {
1605
+ content += template2;
1606
+ if (index < components.length) {
1607
+ const component = components[index++];
1608
+ if (component) {
1609
+ content += convertToString(component);
1610
+ }
911
1611
  }
912
- });
913
- }
914
- function onMount(cb) {
915
- assertInsideComponent("onMounted");
916
- LifecycleContext.ref && LifecycleContext.ref.addHook("mounted", cb);
1612
+ }
1613
+ const result = addAttributes(content, hydrationKey);
1614
+ return result;
917
1615
  }
918
- function onDestroy(cb) {
919
- assertInsideComponent("onDestroy");
920
- LifecycleContext.ref && LifecycleContext.ref.addHook("destroy", cb);
1616
+ function createSSGComponent(component, props = {}) {
1617
+ if (!shared.isFunction(component)) {
1618
+ shared.error("create ssg component: Component is not a function");
1619
+ return "";
1620
+ }
1621
+ const result = component(props);
1622
+ return convertToString(result);
921
1623
  }
922
- function assertInsideComponent(hookName, key) {
923
- if (!LifecycleContext.ref && true) {
924
- console.error(
925
- `"${hookName}"(key: ${shared.isSymbol(key) ? key.toString() : key}) can only be called within the component function body
926
- and cannot be used in asynchronous or deferred calls.`
927
- );
1624
+ function normalizeStyle(styleValue) {
1625
+ if (shared.isArray(styleValue)) {
1626
+ const normalizedStyleObject = {};
1627
+ for (const styleItem of styleValue) {
1628
+ const normalizedItem = shared.isString(styleItem) ? parseStyleString(styleItem) : normalizeStyle(styleItem);
1629
+ if (normalizedItem) {
1630
+ for (const key in normalizedItem) {
1631
+ normalizedStyleObject[key] = normalizedItem[key];
1632
+ }
1633
+ }
1634
+ }
1635
+ return normalizedStyleObject;
928
1636
  }
1637
+ if (shared.isString(styleValue) || shared.isObject(styleValue)) {
1638
+ return styleValue;
1639
+ }
1640
+ return void 0;
1641
+ }
1642
+ var styleSeparatorRegex = /;(?![^(]*\))/g;
1643
+ var propertyValueSeparatorRegex = /:([\s\S]+)/;
1644
+ var styleCommentRegex = /\/\*[\s\S]*?\*\//g;
1645
+ function parseStyleString(cssText) {
1646
+ const styleObject = {};
1647
+ cssText.replaceAll(styleCommentRegex, "").split(styleSeparatorRegex).forEach((styleItem) => {
1648
+ if (styleItem) {
1649
+ const parts = styleItem.split(propertyValueSeparatorRegex);
1650
+ if (parts.length > 1) {
1651
+ styleObject[parts[0].trim()] = parts[1].trim();
1652
+ }
1653
+ }
1654
+ });
1655
+ return styleObject;
929
1656
  }
930
- function useProvide(key, value) {
931
- assertInsideComponent("useProvide", key);
932
- LifecycleContext.ref && LifecycleContext.ref.setContext(key, value);
1657
+ function styleObjectToString(styleValue) {
1658
+ if (!styleValue) {
1659
+ return "";
1660
+ }
1661
+ if (shared.isString(styleValue)) {
1662
+ return styleValue;
1663
+ }
1664
+ let cssText = "";
1665
+ for (const propName in styleValue) {
1666
+ const propValue = styleValue[propName];
1667
+ if (shared.isString(propValue) || shared.isNumber(propValue)) {
1668
+ const normalizedPropName = propName.startsWith("--") ? propName : shared.kebabCase(propName);
1669
+ cssText += `${normalizedPropName}:${propValue};`;
1670
+ }
1671
+ }
1672
+ return cssText;
933
1673
  }
934
- function useInject(key, defaultValue) {
935
- var _a;
936
- assertInsideComponent("useInject", key);
937
- return (_a = LifecycleContext.ref && LifecycleContext.ref.getContext(key)) != null ? _a : defaultValue;
1674
+ function normalizeClassName(classValue) {
1675
+ let resultClassName = "";
1676
+ if (shared.isString(classValue)) {
1677
+ resultClassName = classValue;
1678
+ } else if (shared.isArray(classValue)) {
1679
+ for (const item of classValue) {
1680
+ const normalizedItem = normalizeClassName(item);
1681
+ if (normalizedItem) {
1682
+ resultClassName += `${normalizedItem} `;
1683
+ }
1684
+ }
1685
+ } else if (shared.isObject(classValue)) {
1686
+ for (const className in classValue) {
1687
+ if (classValue[className]) {
1688
+ resultClassName += `${className} `;
1689
+ }
1690
+ }
1691
+ }
1692
+ return resultClassName.trim();
938
1693
  }
939
- function useRef() {
940
- return signal.shallowSignal(null);
1694
+ function setSSGAttr(attrName, attrValue, hydrationId) {
1695
+ if (signals.isSignal(attrValue) || signals.isComputed(attrValue)) {
1696
+ return setSSGAttr(attrName, attrValue.value);
1697
+ }
1698
+ if (!attrValue && attrValue !== 0) {
1699
+ return "";
1700
+ }
1701
+ if (attrName === "style") {
1702
+ const normalizedStyle = normalizeStyle(attrValue);
1703
+ if (!normalizedStyle) {
1704
+ return "";
1705
+ }
1706
+ if (shared.isString(normalizedStyle)) {
1707
+ return ` style="${normalizedStyle}"`;
1708
+ }
1709
+ return ` style="${styleObjectToString(normalizedStyle)}"`;
1710
+ }
1711
+ if (attrName === "class") {
1712
+ const normalizedClassName = normalizeClassName(attrValue);
1713
+ return normalizedClassName ? ` class="${normalizedClassName}"` : "";
1714
+ }
1715
+ if (attrName.startsWith("on")) {
1716
+ return "";
1717
+ }
1718
+ if (attrValue === true) {
1719
+ return ` ${attrName}`;
1720
+ }
1721
+ return ` ${attrName}="${attrValue}"`;
941
1722
  }
942
-
943
- // src/server.ts
944
- function renderToString(component, props) {
945
- renderContext.setSSG();
946
- const ssrNode = new SSGNode(component, props || {});
947
- const html = ssrNode.mount();
948
- renderContext.setClient();
949
- return html;
1723
+ function getRenderedElement(temp) {
1724
+ return () => {
1725
+ const key = getHydrationKey();
1726
+ const node = document.querySelector(`[data-hk="${key}"]`);
1727
+ return node || template(temp)();
1728
+ };
950
1729
  }
951
- function hydrate(component, container) {
952
- const rootElement = typeof container === "string" ? document.querySelector(container) : container;
953
- if (!rootElement) {
954
- throw new Error(`Could not find container: ${container}`);
1730
+ function mapSSRNodes(template2, idx) {
1731
+ const hk = template2.dataset.hk;
1732
+ if (!hk) {
1733
+ return mapNodes(template2, idx);
1734
+ }
1735
+ const nodesList = [];
1736
+ const elements = template2.querySelectorAll(`[data-idx^="${hk}"]`);
1737
+ if (elements.length > 0) {
1738
+ nodesList.push(
1739
+ ...Array.from(elements).filter((item) => {
1740
+ const idxAttr = item.dataset.idx;
1741
+ return idxAttr !== null && DATA_IDX_REGEX.test(idxAttr);
1742
+ }).map((item) => {
1743
+ const idxAttr = item.dataset.idx || "";
1744
+ const [hkPart, idxPart] = idxAttr.split("-");
1745
+ return {
1746
+ hk: hkPart,
1747
+ idx: idxPart,
1748
+ node: item
1749
+ };
1750
+ })
1751
+ );
955
1752
  }
956
- renderContext.setSSR();
957
- h(component).mount(rootElement);
958
- renderContext.setClient();
1753
+ const commentNodes = [];
1754
+ const walkNodes = (node) => {
1755
+ if (node.nodeType === Node.COMMENT_NODE && node.textContent && DATA_IDX_REGEX.test(node.textContent)) {
1756
+ const [hkPart, idxPart] = node.textContent.split("-");
1757
+ commentNodes.push({
1758
+ hk: hkPart,
1759
+ idx: idxPart,
1760
+ node
1761
+ });
1762
+ }
1763
+ let child = node.firstChild;
1764
+ while (child) {
1765
+ walkNodes(child);
1766
+ child = child.nextSibling;
1767
+ }
1768
+ };
1769
+ walkNodes(template2);
1770
+ nodesList.push(...commentNodes);
1771
+ const nodes = [template2];
1772
+ idx.forEach((indexValue) => {
1773
+ const node = nodesList.find((item) => item.idx === String(indexValue));
1774
+ if (node) {
1775
+ nodes.push(node.node);
1776
+ }
1777
+ });
1778
+ return nodes;
959
1779
  }
960
- function ssg(component, props) {
961
- if (renderContext.isSSG) {
962
- return new SSGNode(component, props);
1780
+ function hydrate(component, container, props = {}) {
1781
+ resetHydrationKey();
1782
+ try {
1783
+ const rootElement = shared.isString(container) ? document.querySelector(container) : container;
1784
+ if (!rootElement) {
1785
+ shared.error("Hydration error: Root element not found");
1786
+ return void 0;
1787
+ }
1788
+ const rootComponent = createComponent(component, props);
1789
+ rootComponent.mount(rootElement);
1790
+ endHydration();
1791
+ return rootComponent;
1792
+ } catch (error_) {
1793
+ shared.error("Hydration error:", error_);
1794
+ return void 0;
963
1795
  }
964
- return h(component, props);
965
1796
  }
966
1797
 
1798
+ Object.defineProperty(exports, "escapeHTML", {
1799
+ enumerable: true,
1800
+ get: function () { return shared.escapeHTML; }
1801
+ });
1802
+ exports.Component = Component;
967
1803
  exports.Fragment = Fragment;
968
- exports.h = h;
1804
+ exports.Portal = Portal;
1805
+ exports.Suspense = Suspense;
1806
+ exports.SuspenseContext = SuspenseContext;
1807
+ exports.addEvent = addEvent;
1808
+ exports.addEventListener = addEventListener;
1809
+ exports.bindElement = bindElement;
1810
+ exports.createApp = createApp;
1811
+ exports.createComponent = createComponent;
1812
+ exports.createResource = createResource;
1813
+ exports.createSSGComponent = createSSGComponent;
1814
+ exports.delegateEvents = delegateEvents;
1815
+ exports.getHydrationKey = getHydrationKey;
1816
+ exports.getRenderedElement = getRenderedElement;
969
1817
  exports.hydrate = hydrate;
1818
+ exports.inject = inject;
1819
+ exports.insert = insert;
970
1820
  exports.isComponent = isComponent;
971
- exports.isJsxElement = isJsxElement;
1821
+ exports.isFragment = isFragment;
1822
+ exports.isPortal = isPortal;
1823
+ exports.isSuspense = isSuspense;
1824
+ exports.mapNodes = mapNodes;
1825
+ exports.mapSSRNodes = mapSSRNodes;
1826
+ exports.normalizeClass = normalizeClass;
972
1827
  exports.onDestroy = onDestroy;
973
1828
  exports.onMount = onMount;
1829
+ exports.onUpdate = onUpdate;
1830
+ exports.patchAttr = patchAttr;
1831
+ exports.patchClass = patchClass;
1832
+ exports.patchStyle = patchStyle;
1833
+ exports.provide = provide;
1834
+ exports.render = render;
974
1835
  exports.renderToString = renderToString;
975
- exports.ssg = ssg;
976
- exports.template = createTemplate;
977
- exports.useInject = useInject;
978
- exports.useProvide = useProvide;
979
- exports.useRef = useRef;
1836
+ exports.setSSGAttr = setSSGAttr;
1837
+ exports.setStyle = setStyle;
1838
+ exports.template = template;