@ktjs/core 0.28.1 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1152 +0,0 @@
1
- var __ktjs_core__ = (function (exports) {
2
- 'use strict';
3
-
4
- // Cached native methods for performance optimization
5
- const $isArray = Array.isArray;
6
- const $is = Object.is;
7
- const $entries = Object.entries;
8
- const $random = Math.random;
9
- const $isThenable = (o) => typeof o?.then === 'function';
10
-
11
- if (typeof Symbol === 'undefined') {
12
- window.Symbol = function Symbol(description) {
13
- return `@@SYMBOL_${description || ''}_${$random().toString(36).slice(2)}`;
14
- };
15
- }
16
-
17
- // Shared constants
18
- // Empty for now - can be extended with framework-wide constants
19
- /**
20
- * Mark the attribute as SVG to handle special cases during rendering.
21
- */
22
- const SVG_ATTR_FLAG = '__kt_svg__';
23
- /**
24
- * Mark the attribute as MathML to handle special cases during rendering.
25
- */
26
- const MATHML_ATTR_FLAG = '__kt_mathml__';
27
-
28
- // DOM manipulation utilities
29
- // # dom natives
30
- const $isNode = (x) => x?.nodeType > 0;
31
- /**
32
- * Safe replace `oldNode` With `newNode`
33
- */
34
- const $replaceNode = (oldNode, newNode) => {
35
- if ($isNode(oldNode) && $isNode(newNode)) {
36
- if (newNode.contains(oldNode)) {
37
- newNode.remove();
38
- }
39
- oldNode.replaceWith(newNode);
40
- }
41
- };
42
- /**
43
- * & Remove `bind` because it is shockingly slower than wrapper
44
- * & `window.document` is safe because it is not configurable and its setter is undefined
45
- */
46
- const $appendChild = HTMLElement.prototype.appendChild;
47
- const originAppend = HTMLElement.prototype.append;
48
- const $append = // for ie 9/10/11
49
- typeof originAppend === 'function'
50
- ? originAppend
51
- : function (...nodes) {
52
- if (nodes.length < 50) {
53
- for (let i = 0; i < nodes.length; i++) {
54
- const node = nodes[i];
55
- if (typeof node === 'string') {
56
- $appendChild.call(this, document.createTextNode(node));
57
- }
58
- else {
59
- $appendChild.call(this, node);
60
- }
61
- }
62
- }
63
- else {
64
- const fragment = document.createDocumentFragment();
65
- for (let i = 0; i < nodes.length; i++) {
66
- const node = nodes[i];
67
- if (typeof node === 'string') {
68
- $appendChild.call(fragment, document.createTextNode(node));
69
- }
70
- else {
71
- $appendChild.call(fragment, node);
72
- }
73
- }
74
- $appendChild.call(this, fragment);
75
- }
76
- };
77
- const { get: $buttonDisabledGetter, set: $buttonDisabledSetter } = Object.getOwnPropertyDescriptor(HTMLButtonElement.prototype, 'disabled');
78
- /**
79
- * Used for `k-model`
80
- */
81
- const $applyModel = (element, valueRef, propName, eventName) => {
82
- element[propName] = valueRef.value; // initialize
83
- valueRef.addOnChange((newValue) => (element[propName] = newValue));
84
- element.addEventListener(eventName, () => (valueRef.value = element[propName]));
85
- };
86
-
87
- // String manipulation utilities
88
- /**
89
- * Default empty function
90
- */
91
- const $emptyFn = (() => true);
92
- /**
93
- * Safe and quick forEach implementation that works with array-like objects and handles sparse arrays.
94
- */
95
- const $forEach = (array, callback) => {
96
- const len = array.length;
97
- for (let i = 0; i < len; i++) {
98
- callback(array[i], i, array);
99
- }
100
- };
101
-
102
- // incase that symbol is not supported
103
- Object.defineProperty(window, '__ktjs__', { value: '0.23.11' });
104
-
105
- var isKT = function (obj) { return obj === null || obj === void 0 ? void 0 : obj.isKT; };
106
- var isRef = function (obj) { return (obj === null || obj === void 0 ? void 0 : obj.ktType) === 1 /* KTReactiveType.REF */; };
107
- var isComputed = function (obj) { return (obj === null || obj === void 0 ? void 0 : obj.ktType) === 2 /* KTReactiveType.COMPUTED */; };
108
-
109
- var booleanHandler = function (element, key, value) {
110
- if (key in element) {
111
- element[key] = !!value;
112
- }
113
- else {
114
- element.setAttribute(key, value);
115
- }
116
- };
117
- var valueHandler = function (element, key, value) {
118
- if (key in element) {
119
- element[key] = value;
120
- }
121
- else {
122
- element.setAttribute(key, value);
123
- }
124
- };
125
- // Attribute handlers map for optimized lookup
126
- var handlers = {
127
- checked: booleanHandler,
128
- selected: booleanHandler,
129
- value: valueHandler,
130
- valueAsDate: valueHandler,
131
- valueAsNumber: valueHandler,
132
- defaultValue: valueHandler,
133
- defaultChecked: booleanHandler,
134
- defaultSelected: booleanHandler,
135
- disabled: booleanHandler,
136
- readOnly: booleanHandler,
137
- multiple: booleanHandler,
138
- required: booleanHandler,
139
- autofocus: booleanHandler,
140
- open: booleanHandler,
141
- controls: booleanHandler,
142
- autoplay: booleanHandler,
143
- loop: booleanHandler,
144
- muted: booleanHandler,
145
- defer: booleanHandler,
146
- async: booleanHandler,
147
- hidden: function (element, _key, value) { return (element.hidden = !!value); },
148
- };
149
-
150
- var defaultHandler = function (element, key, value) {
151
- return element.setAttribute(key, value);
152
- };
153
- var setElementStyle = function (element, style) {
154
- if (typeof style === 'string') {
155
- element.style.cssText = style;
156
- return;
157
- }
158
- for (var key in style) {
159
- element.style[key] = style[key];
160
- }
161
- };
162
- function attrIsObject(element, attr) {
163
- var classValue = attr.class || attr.className;
164
- if (classValue !== undefined) {
165
- if (isKT(classValue)) {
166
- element.setAttribute('class', classValue.value);
167
- classValue.addOnChange(function (v) { return element.setAttribute('class', v); });
168
- }
169
- else {
170
- element.setAttribute('class', classValue);
171
- }
172
- }
173
- var style = attr.style;
174
- if (style) {
175
- if (typeof style === 'string') {
176
- element.setAttribute('style', style);
177
- }
178
- else if (typeof style === 'object') {
179
- if (isKT(style)) {
180
- setElementStyle(element, style.value);
181
- style.addOnChange(function (v) { return setElementStyle(element, v); });
182
- }
183
- else {
184
- setElementStyle(element, style);
185
- }
186
- }
187
- }
188
- if ('k-html' in attr) {
189
- var html = attr['k-html'];
190
- if (isKT(html)) {
191
- element.innerHTML = html.value;
192
- html.addOnChange(function (v) { return (element.innerHTML = v); });
193
- }
194
- else {
195
- element.innerHTML = html;
196
- }
197
- }
198
- var _loop_1 = function (key) {
199
- if (key === 'k-if' ||
200
- key === 'k-model' ||
201
- key === 'ref' ||
202
- key === 'class' ||
203
- key === 'className' ||
204
- key === 'style' ||
205
- key === 'children' ||
206
- key === 'k-html') {
207
- return "continue";
208
- }
209
- var o = attr[key];
210
- // normal event handler
211
- if (key.startsWith('on:')) {
212
- element.addEventListener(key.slice(3), o); // chop off the `on:`
213
- }
214
- // normal attributes
215
- else {
216
- var handler_1 = handlers[key] || defaultHandler;
217
- if (isKT(o)) {
218
- handler_1(element, key, o.value);
219
- o.addOnChange(function (v) { return handler_1(element, key, v); });
220
- }
221
- else {
222
- handler_1(element, key, o);
223
- }
224
- }
225
- };
226
- for (var key in attr) {
227
- _loop_1(key);
228
- }
229
- }
230
- function applyAttr(element, attr) {
231
- if (!attr) {
232
- return;
233
- }
234
- if (typeof attr === 'object' && attr !== null) {
235
- attrIsObject(element, attr);
236
- }
237
- else {
238
- throw new Error('[kt.js error] attr must be an object.');
239
- }
240
- }
241
-
242
- var assureNode = function (o) { return ($isNode(o) ? o : document.createTextNode(o)); };
243
- function apdSingle(element, c) {
244
- // & JSX should ignore false, undefined, and null
245
- if (c === false || c === undefined || c === null) {
246
- return;
247
- }
248
- if (isKT(c)) {
249
- var node_1 = assureNode(c.value);
250
- $append.call(element, node_1);
251
- c.addOnChange(function (newValue, oldValue) {
252
- if ($isNode(newValue) && $isNode(oldValue)) {
253
- // & this case is handled automically in `class KTRef`
254
- return;
255
- }
256
- var oldNode = node_1;
257
- node_1 = assureNode(newValue);
258
- oldNode.replaceWith(node_1);
259
- });
260
- }
261
- else {
262
- $append.call(element, c);
263
- // Handle KTFor anchor
264
- // todo Maybe not needed anymore
265
- var list = c.__kt_for_list__;
266
- if ($isArray(list)) {
267
- apd(element, list);
268
- }
269
- }
270
- }
271
- function apd(element, c) {
272
- if ($isThenable(c)) {
273
- c.then(function (r) { return apd(element, r); });
274
- }
275
- else if ($isArray(c)) {
276
- var _loop_1 = function (i) {
277
- // & might be thenable here too
278
- var ci = c[i];
279
- if ($isThenable(ci)) {
280
- var comment_1 = document.createComment('ktjs-promise-placeholder');
281
- $append.call(element, comment_1);
282
- ci.then(function (awaited) { return comment_1.replaceWith(awaited); });
283
- }
284
- else {
285
- apdSingle(element, ci);
286
- }
287
- };
288
- for (var i = 0; i < c.length; i++) {
289
- _loop_1(i);
290
- }
291
- }
292
- else {
293
- // & here is thened, so must be a simple elementj
294
- apdSingle(element, c);
295
- }
296
- }
297
- function applyContent(element, content) {
298
- if ($isArray(content)) {
299
- for (var i = 0; i < content.length; i++) {
300
- apd(element, content[i]);
301
- }
302
- }
303
- else {
304
- apd(element, content);
305
- }
306
- }
307
-
308
- var KTRef = /** @class */ (function () {
309
- function KTRef(_value, _onChanges) {
310
- /**
311
- * Indicates that this is a KTRef instance
312
- */
313
- this.isKT = true;
314
- this.ktType = 1 /* KTReactiveType.REF */;
315
- this._value = _value;
316
- this._onChanges = _onChanges;
317
- }
318
- /**
319
- * @internal
320
- */
321
- KTRef.prototype._emit = function (newValue, oldValue) {
322
- for (var i = 0; i < this._onChanges.length; i++) {
323
- this._onChanges[i](newValue, oldValue);
324
- }
325
- };
326
- Object.defineProperty(KTRef.prototype, "value", {
327
- /**
328
- * If new value and old value are both nodes, the old one will be replaced in the DOM
329
- */
330
- get: function () {
331
- return this._value;
332
- },
333
- set: function (newValue) {
334
- if ($is(newValue, this._value)) {
335
- return;
336
- }
337
- var oldValue = this._value;
338
- $replaceNode(oldValue, newValue);
339
- this._value = newValue;
340
- this._emit(newValue, oldValue);
341
- },
342
- enumerable: false,
343
- configurable: true
344
- });
345
- /**
346
- * Force all listeners to run even when reference identity has not changed.
347
- * Useful for in-place array/object mutations.
348
- */
349
- KTRef.prototype.notify = function () {
350
- this._emit(this._value, this._value);
351
- };
352
- /**
353
- * Mutate current value in-place and notify listeners once.
354
- *
355
- * @example
356
- * const items = ref<number[]>([1, 2]);
357
- * items.mutate((list) => list.push(3));
358
- */
359
- KTRef.prototype.mutate = function (mutator) {
360
- if (typeof mutator !== 'function') {
361
- throw new Error('[kt.js error] KTRef.mutate: mutator must be a function');
362
- }
363
- var oldValue = this._value;
364
- var result = mutator(this._value);
365
- this._emit(this._value, oldValue);
366
- return result;
367
- };
368
- /**
369
- * Register a callback when the value changes
370
- * @param callback (newValue, oldValue) => xxx
371
- */
372
- KTRef.prototype.addOnChange = function (callback) {
373
- if (typeof callback !== 'function') {
374
- throw new Error('[kt.js error] KTRef.addOnChange: callback must be a function');
375
- }
376
- this._onChanges.push(callback);
377
- };
378
- KTRef.prototype.removeOnChange = function (callback) {
379
- for (var i = this._onChanges.length - 1; i >= 0; i--) {
380
- if (this._onChanges[i] === callback) {
381
- this._onChanges.splice(i, 1);
382
- return true;
383
- }
384
- }
385
- return false;
386
- };
387
- return KTRef;
388
- }());
389
- /**
390
- * Reference to the created HTML element.
391
- * - **Only** respond to `ref.value` changes, not reactive to internal changes of the element.
392
- * - can alse be used to store normal values, but it is not reactive.
393
- * - if the value is already a `KTRef`, it will be returned **directly**.
394
- * @param value mostly an HTMLElement
395
- */
396
- function ref(value, onChange) {
397
- return new KTRef(value, onChange ? [onChange] : []);
398
- }
399
- /**
400
- * Convert a value to `KTRef`.
401
- * - Returns the original value if it is already a `KTRef`.
402
- * - Throws error if the value is a `KTComputed`.
403
- * - Otherwise wraps the value with `ref()`.
404
- * @param o value to convert
405
- */
406
- var toRef = function (o) {
407
- if (isRef(o)) {
408
- return o;
409
- }
410
- else if (isComputed(o)) {
411
- throw new Error('[kt.js error] Computed values cannot be used as KTRef.');
412
- }
413
- else {
414
- return ref(o);
415
- }
416
- };
417
- function kcollect() {
418
- var newObj = {};
419
- var entries = $entries(this);
420
- for (var i = 0; i < entries.length; i++) {
421
- var key = entries[i][0];
422
- if (key === 'kcollect') {
423
- continue;
424
- }
425
- newObj[key] = entries[i][1].value;
426
- }
427
- return newObj;
428
- }
429
- /**
430
- * Make all first-level properties of the object a `KTRef`.
431
- * - `obj.a.b` is not reactive
432
- */
433
- var surfaceRef = function (obj) {
434
- var entries = $entries(obj);
435
- var newObj = { kcollect: kcollect };
436
- for (var i = 0; i < entries.length; i++) {
437
- newObj[entries[i][0]] = ref(entries[i][1]);
438
- }
439
- return newObj;
440
- };
441
- // # asserts
442
- /**
443
- * Assert k-model to be a ref object
444
- */
445
- var $modelOrRef = function (props, defaultValue) {
446
- // & props is an object. Won't use it in any other place
447
- if ('k-model' in props) {
448
- var kmodel = props['k-model'];
449
- if (isRef(kmodel)) {
450
- return kmodel;
451
- }
452
- else {
453
- throw new Error("[kt.js error] k-model data must be a KTRef object, please use 'ref(...)' to wrap it.");
454
- }
455
- }
456
- return ref(defaultValue);
457
- };
458
- var $setRef = function (props, node) {
459
- if ('ref' in props) {
460
- var r = props.ref;
461
- if (isRef(r)) {
462
- r.value = node;
463
- }
464
- else {
465
- throw new Error('[kt.js error] Fragment: ref must be a KTRef');
466
- }
467
- }
468
- };
469
-
470
- var KTComputed = /** @class */ (function () {
471
- function KTComputed(_calculator, reactives) {
472
- /**
473
- * Indicates that this is a KTRef instance
474
- */
475
- this.isKT = true;
476
- this.ktType = 2 /* KTReactiveType.COMPUTED */;
477
- /**
478
- * @internal
479
- */
480
- this._onChanges = [];
481
- this._calculator = _calculator;
482
- this._value = _calculator();
483
- this._subscribe(reactives);
484
- }
485
- /**
486
- * @internal
487
- */
488
- KTComputed.prototype._emit = function (newValue, oldValue) {
489
- for (var i = 0; i < this._onChanges.length; i++) {
490
- this._onChanges[i](newValue, oldValue);
491
- }
492
- };
493
- /**
494
- * @internal
495
- */
496
- KTComputed.prototype._recalculate = function (forceEmit) {
497
- if (forceEmit === void 0) { forceEmit = false; }
498
- var oldValue = this._value;
499
- var newValue = this._calculator();
500
- if (oldValue === newValue) {
501
- if (forceEmit) {
502
- this._emit(newValue, oldValue);
503
- }
504
- return;
505
- }
506
- this._value = newValue;
507
- $replaceNode(oldValue, newValue);
508
- this._emit(newValue, oldValue);
509
- };
510
- /**
511
- * @internal
512
- */
513
- KTComputed.prototype._subscribe = function (reactives) {
514
- var _this = this;
515
- for (var i = 0; i < reactives.length; i++) {
516
- var reactive = reactives[i];
517
- reactive.addOnChange(function () { return _this._recalculate(); });
518
- }
519
- };
520
- Object.defineProperty(KTComputed.prototype, "value", {
521
- /**
522
- * If new value and old value are both nodes, the old one will be replaced in the DOM
523
- */
524
- get: function () {
525
- return this._value;
526
- },
527
- set: function (_newValue) {
528
- throw new Error('[kt.js error] KTComputed: cannot set value of a computed value');
529
- },
530
- enumerable: false,
531
- configurable: true
532
- });
533
- /**
534
- * Force listeners to run once with the latest computed result.
535
- */
536
- KTComputed.prototype.notify = function () {
537
- this._recalculate(true);
538
- };
539
- /**
540
- * Computed values are derived from dependencies and should not be mutated manually.
541
- */
542
- KTComputed.prototype.mutate = function (_mutator) {
543
- console.warn('[kt.js warn]','KTComputed.mutate: computed is derived automatically; manual mutate is ignored. Use notify() instead');
544
- };
545
- /**
546
- * Register a callback when the value changes
547
- * @param callback (newValue, oldValue) => xxx
548
- */
549
- KTComputed.prototype.addOnChange = function (callback) {
550
- if (typeof callback !== 'function') {
551
- throw new Error('[kt.js error] KTRef.addOnChange: callback must be a function');
552
- }
553
- this._onChanges.push(callback);
554
- };
555
- /**
556
- * Unregister a callback
557
- * @param callback (newValue, oldValue) => xxx
558
- */
559
- KTComputed.prototype.removeOnChange = function (callback) {
560
- for (var i = this._onChanges.length - 1; i >= 0; i--) {
561
- if (this._onChanges[i] === callback) {
562
- this._onChanges.splice(i, 1);
563
- return true;
564
- }
565
- }
566
- return false;
567
- };
568
- return KTComputed;
569
- }());
570
- /**
571
- * Create a reactive computed value
572
- * @param computeFn
573
- * @param reactives refs and computeds that this computed depends on
574
- */
575
- function computed(computeFn, reactives) {
576
- if (reactives.some(function (v) { return !isKT(v); })) {
577
- throw new Error('[kt.js error] computed: all reactives must be KTRef or KTComputed instances');
578
- }
579
- return new KTComputed(computeFn, reactives);
580
- }
581
-
582
- /**
583
- * Register a reactive effect with options.
584
- * @param effectFn The effect function to run when dependencies change
585
- * @param reactives The reactive dependencies
586
- * @param options Effect options: lazy, onCleanup, debugName
587
- * @returns stop function to remove all listeners
588
- */
589
- function effect(effectFn, reactives, options) {
590
- var _a = Object(options), _b = _a.lazy, lazy = _b === void 0 ? false : _b, _c = _a.onCleanup, onCleanup = _c === void 0 ? $emptyFn : _c, _d = _a.debugName, debugName = _d === void 0 ? '' : _d;
591
- var active = true;
592
- var run = function () {
593
- if (!active) {
594
- return;
595
- }
596
- // cleanup before rerun
597
- onCleanup();
598
- try {
599
- effectFn();
600
- }
601
- catch (err) {
602
- console.debug('[kt.js debug]','effect error:', debugName, err);
603
- }
604
- };
605
- // subscribe to dependencies
606
- for (var i = 0; i < reactives.length; i++) {
607
- reactives[i].addOnChange(run);
608
- }
609
- // auto run unless lazy
610
- if (!lazy) {
611
- run();
612
- }
613
- // stop function
614
- return function () {
615
- if (!active) {
616
- return;
617
- }
618
- active = false;
619
- for (var i = 0; i < reactives.length; i++) {
620
- reactives[i].removeOnChange(run);
621
- }
622
- // final cleanup
623
- onCleanup();
624
- };
625
- }
626
-
627
- var toReactive = function (value, onChange) {
628
- if (isKT(value)) {
629
- if (onChange) {
630
- value.addOnChange(onChange);
631
- }
632
- return value;
633
- }
634
- else {
635
- return ref(value, onChange);
636
- }
637
- };
638
- /**
639
- * Extracts the value from a KTReactive, or returns the value directly if it's not reactive.
640
- */
641
- function dereactive(value) {
642
- return isKT(value) ? value.value : value;
643
- }
644
-
645
- function applyKModel(element, valueRef) {
646
- if (!isKT(valueRef)) {
647
- console.warn('[kt.js warn]','k-model value must be a KTRef.');
648
- return;
649
- }
650
- if (element instanceof HTMLInputElement) {
651
- if (element.type === 'radio' || element.type === 'checkbox') {
652
- $applyModel(element, valueRef, 'checked', 'change');
653
- }
654
- else {
655
- $applyModel(element, valueRef, 'value', 'input');
656
- }
657
- }
658
- else if (element instanceof HTMLSelectElement) {
659
- $applyModel(element, valueRef, 'value', 'change');
660
- }
661
- else if (element instanceof HTMLTextAreaElement) {
662
- $applyModel(element, valueRef, 'value', 'input');
663
- }
664
- else {
665
- console.warn('[kt.js warn]','not supported element for k-model:');
666
- }
667
- }
668
-
669
- var htmlCreator = function (tag) { return document.createElement(tag); };
670
- var svgCreator = function (tag) { return document.createElementNS('http://www.w3.org/2000/svg', tag); };
671
- var mathMLCreator = function (tag) { return document.createElementNS('http://www.w3.org/1998/Math/MathML', tag); };
672
- var creator = htmlCreator;
673
- /**
674
- * Create an enhanced HTMLElement.
675
- * - Only supports HTMLElements, **NOT** SVGElements or other Elements.
676
- * @param tag tag of an `HTMLElement`
677
- * @param attr attribute object or className
678
- * @param content a string or an array of HTMLEnhancedElement as child nodes
679
- *
680
- * ## About
681
- * @package @ktjs/core
682
- * @author Kasukabe Tsumugi <futami16237@gmail.com>
683
- * @version 0.28.1 (Last Update: 2026.02.10 11:23:01.128)
684
- * @license MIT
685
- * @link https://github.com/baendlorel/kt.js
686
- * @link https://baendlorel.github.io/ Welcome to my site!
687
- * @description Core functionality for kt.js - DOM manipulation utilities with JSX/TSX support
688
- * @copyright Copyright (c) 2026 Kasukabe Tsumugi. All rights reserved.
689
- */
690
- var h = function (tag, attr, content) {
691
- if (typeof tag !== 'string') {
692
- throw new Error('[kt.js error] tagName must be a string.');
693
- }
694
- if (attr) {
695
- if (SVG_ATTR_FLAG in attr) {
696
- delete attr[SVG_ATTR_FLAG];
697
- creator = svgCreator;
698
- }
699
- else if (MATHML_ATTR_FLAG in attr) {
700
- delete attr[MATHML_ATTR_FLAG];
701
- creator = mathMLCreator;
702
- }
703
- else {
704
- creator = htmlCreator;
705
- }
706
- }
707
- // * start creating the element
708
- var element = creator(tag);
709
- // * Handle content
710
- applyAttr(element, attr);
711
- applyContent(element, content);
712
- if (typeof attr === 'object' && attr !== null && 'k-model' in attr) {
713
- applyKModel(element, attr['k-model']);
714
- }
715
- return element;
716
- };
717
-
718
- /**
719
- * Fragment - Container component for managing arrays of child elements
720
- *
721
- * Features:
722
- * 1. Returns a comment anchor node, child elements are inserted after the anchor
723
- * 2. Supports reactive arrays, automatically updates DOM when array changes
724
- * 3. Basic version uses simple replacement algorithm (remove all old elements, insert all new elements)
725
- * 4. Future enhancement: key-based optimization
726
- *
727
- * Usage example:
728
- * ```tsx
729
- * const children = ref([<div>A</div>, <div>B</div>]);
730
- * const fragment = <Fragment children={children} />;
731
- * document.body.appendChild(fragment);
732
- *
733
- * // Automatic update
734
- * children.value = [<div>C</div>, <div>D</div>];
735
- * ```
736
- */
737
- function Fragment$1(props) {
738
- // key parameter reserved for future enhancement, currently unused
739
- // const { key: _key } = props;
740
- var redraw = function () {
741
- var newElements = childrenRef.value;
742
- var parent = anchor.parentNode;
743
- if (!parent) {
744
- // If anchor is not in DOM, only update internal state
745
- elements.length = 0;
746
- for (var i = 0; i < newElements.length; i++) {
747
- elements.push(newElements[i]);
748
- }
749
- return;
750
- }
751
- // Simple replacement algorithm: remove all old elements, insert all new elements
752
- // todo Future enhancement: key-based optimization
753
- // 1. Remove all old elements
754
- for (var i = 0; i < elements.length; i++) {
755
- elements[i].remove();
756
- }
757
- // 2. Insert all new elements
758
- var fragment = document.createDocumentFragment();
759
- elements.length = 0;
760
- for (var i = 0; i < newElements.length; i++) {
761
- var element = newElements[i];
762
- elements.push(element);
763
- fragment.appendChild(element);
764
- }
765
- // Insert after anchor
766
- parent.insertBefore(fragment, anchor.nextSibling);
767
- };
768
- var initialized = false;
769
- var childrenRef = toReactive(props.children, redraw);
770
- var elements = [];
771
- var anchor = document.createComment('kt-fragment');
772
- // Observe DOM insertion
773
- var observer = new MutationObserver(function () {
774
- if (anchor.isConnected && !initialized) {
775
- initialized = true;
776
- redraw();
777
- observer.disconnect();
778
- }
779
- });
780
- observer.observe(document.body, { childList: true, subtree: true });
781
- // Set ref reference
782
- $setRef(props, anchor);
783
- return anchor;
784
- }
785
- /**
786
- * Convert KTRawContent to HTMLElement array
787
- */
788
- function convertChildrenToElements(children) {
789
- var elements = [];
790
- var processChild = function (child) {
791
- if (child == null || child === false || child === true) {
792
- // Ignore null, undefined, false, true
793
- return;
794
- }
795
- if ($isArray(child)) {
796
- // Recursively process array
797
- $forEach(child, processChild);
798
- return;
799
- }
800
- if (typeof child === 'string' || typeof child === 'number') {
801
- // & Wrap text in span element? No! use text node instead
802
- var textNode = document.createTextNode(String(child));
803
- elements.push(textNode);
804
- return;
805
- }
806
- if (child instanceof HTMLElement) {
807
- elements.push(child);
808
- return;
809
- }
810
- if (isKT(child)) {
811
- processChild(child.value);
812
- return;
813
- }
814
- // Other types ignored or converted to string
815
- console.warn('[kt.js warn]','Fragment: unsupported child type', child);
816
- };
817
- processChild(children);
818
- return elements;
819
- }
820
-
821
- var create = function (tag, props) {
822
- if (typeof tag === 'function') {
823
- return tag(props);
824
- }
825
- else {
826
- return h(tag, props, props.children);
827
- }
828
- };
829
- var placeholder = function () { return document.createComment('k-if'); };
830
- /**
831
- * @param tag html tag or function component
832
- * @param props properties/attributes
833
- */
834
- function jsx(tag, props) {
835
- if (isComputed(props.ref)) {
836
- throw new Error('[kt.js error] Cannot assign a computed value to an element.');
837
- }
838
- var el;
839
- if ('k-if' in props) {
840
- var kif = props['k-if'];
841
- var condition = kif; // assume boolean by default
842
- // Handle reactive k-if
843
- if (isKT(kif)) {
844
- kif.addOnChange(function (newValue, oldValue) {
845
- if (newValue === oldValue) {
846
- return;
847
- }
848
- var oldEl = el;
849
- $setRef(props, (el = newValue ? create(tag, props) : placeholder()));
850
- $replaceNode(oldEl, el);
851
- });
852
- condition = kif.value;
853
- }
854
- if (!condition) {
855
- // & make comment placeholder in case that ref might be redrawn later
856
- $setRef(props, (el = placeholder()));
857
- return el;
858
- }
859
- }
860
- $setRef(props, (el = create(tag, props)));
861
- return el;
862
- }
863
- /**
864
- * Fragment support - returns an array of children
865
- * Enhanced Fragment component that manages arrays of elements
866
- */
867
- function Fragment(props) {
868
- var children = (props !== null && props !== void 0 ? props : {}).children;
869
- if (!children) {
870
- return document.createComment('kt-fragment-empty');
871
- }
872
- var elements = convertChildrenToElements(children);
873
- return Fragment$1({ children: elements });
874
- }
875
- /**
876
- * JSX Development runtime - same as jsx but with additional dev checks
877
- */
878
- var jsxDEV = function () {
879
- var args = [];
880
- for (var _i = 0; _i < arguments.length; _i++) {
881
- args[_i] = arguments[_i];
882
- }
883
- // console.log('JSX DEV called:', ...args);
884
- // console.log('children', (args[1] as any)?.children);
885
- return jsx.apply(void 0, args);
886
- };
887
- /**
888
- * JSX runtime for React 17+ automatic runtime
889
- * This is called when using jsx: "react-jsx" or "react-jsxdev"
890
- */
891
- var jsxs = jsx;
892
- /**
893
- * A helper to create redrawable elements
894
- * ```tsx
895
- * export function MyComponent() {
896
- * let aa = 10;
897
- * // ...
898
- * // aa might be changed
899
- * return createRedrawable(() => <div>{aa}</div>);
900
- * }
901
- * ```
902
- * Then the returned element has a `redraw` method to redraw itself with new values.
903
- * @param creator a simple creator function that returns an element
904
- * @returns created element's ref
905
- */
906
- function createRedrawable(creator) {
907
- var elRef = ref();
908
- var redraw = function () {
909
- elRef.value = creator(); // ref setter automatically calls replaceWith
910
- elRef.redraw = redraw;
911
- return elRef.value;
912
- };
913
- redraw();
914
- return elRef;
915
- }
916
-
917
- function KTAsync(props) {
918
- var _a;
919
- var raw = props.component(props);
920
- var comp = (_a = props.skeleton) !== null && _a !== void 0 ? _a : document.createComment('ktjs-suspense-placeholder');
921
- if ($isThenable(raw)) {
922
- raw.then(function (resolved) { return comp.replaceWith(resolved); });
923
- }
924
- else {
925
- comp = raw;
926
- }
927
- return comp;
928
- }
929
-
930
- /**
931
- * KTFor - List rendering component with key-based optimization
932
- * Returns a Comment anchor node with rendered elements in __kt_for_list__
933
- */
934
- function KTFor(props) {
935
- var redraw = function () {
936
- var newList = listRef.value;
937
- var parent = anchor.parentNode;
938
- if (!parent) {
939
- // If not in DOM yet, just rebuild the list
940
- var newElements_1 = [];
941
- nodeMap.clear();
942
- for (var index = 0; index < newList.length; index++) {
943
- var item = newList[index];
944
- var itemKey = currentKey(item, index, newList);
945
- var node = currentMap(item, index, newList);
946
- nodeMap.set(itemKey, node);
947
- newElements_1.push(node);
948
- }
949
- anchor.__kt_for_list__ = newElements_1;
950
- return anchor;
951
- }
952
- var oldLength = anchor.__kt_for_list__.length;
953
- var newLength = newList.length;
954
- // Fast path: empty list
955
- if (newLength === 0) {
956
- nodeMap.forEach(function (node) { return node.remove(); });
957
- nodeMap.clear();
958
- anchor.__kt_for_list__ = [];
959
- return anchor;
960
- }
961
- // Fast path: all new items
962
- if (oldLength === 0) {
963
- var newElements_2 = [];
964
- var fragment = document.createDocumentFragment();
965
- for (var i = 0; i < newLength; i++) {
966
- var item = newList[i];
967
- var itemKey = currentKey(item, i, newList);
968
- var node = currentMap(item, i, newList);
969
- nodeMap.set(itemKey, node);
970
- newElements_2.push(node);
971
- fragment.appendChild(node);
972
- }
973
- parent.insertBefore(fragment, anchor.nextSibling);
974
- anchor.__kt_for_list__ = newElements_2;
975
- return anchor;
976
- }
977
- // Build key index map and new elements array in one pass
978
- var newKeyToNewIndex = new Map();
979
- var newElements = new Array(newLength);
980
- var maxNewIndexSoFar = 0;
981
- var moved = false;
982
- for (var i = 0; i < newLength; i++) {
983
- var item = newList[i];
984
- var itemKey = currentKey(item, i, newList);
985
- newKeyToNewIndex.set(itemKey, i);
986
- if (nodeMap.has(itemKey)) {
987
- // Reuse existing node
988
- var node = nodeMap.get(itemKey);
989
- newElements[i] = node;
990
- // Track if items moved
991
- if (i < maxNewIndexSoFar) {
992
- moved = true;
993
- }
994
- else {
995
- maxNewIndexSoFar = i;
996
- }
997
- }
998
- else {
999
- // Create new node
1000
- newElements[i] = currentMap(item, i, newList);
1001
- }
1002
- }
1003
- // Remove nodes not in new list
1004
- var toRemove = [];
1005
- nodeMap.forEach(function (node, key) {
1006
- if (!newKeyToNewIndex.has(key)) {
1007
- toRemove.push(node);
1008
- }
1009
- });
1010
- for (var i = 0; i < toRemove.length; i++) {
1011
- toRemove[i].remove();
1012
- }
1013
- // Update DOM with minimal operations
1014
- if (moved) {
1015
- // Use longest increasing subsequence to minimize moves
1016
- var seq = getSequence(newElements.map(function (el, i) { return (nodeMap.has(currentKey(newList[i], i, newList)) ? i : -1); }));
1017
- var j = seq.length - 1;
1018
- var anchor_1 = null;
1019
- // Traverse from end to start for stable insertions
1020
- for (var i = newLength - 1; i >= 0; i--) {
1021
- var node = newElements[i];
1022
- if (j < 0 || i !== seq[j]) {
1023
- // Node needs to be moved or inserted
1024
- if (anchor_1) {
1025
- parent.insertBefore(node, anchor_1);
1026
- }
1027
- else {
1028
- // Insert at end
1029
- var nextSibling = anchor_1.nextSibling;
1030
- var temp = nextSibling;
1031
- while (temp && newElements.includes(temp)) {
1032
- temp = temp.nextSibling;
1033
- }
1034
- parent.insertBefore(node, temp);
1035
- }
1036
- }
1037
- else {
1038
- j--;
1039
- }
1040
- anchor_1 = node;
1041
- }
1042
- }
1043
- else {
1044
- // No moves needed, just insert new nodes
1045
- var currentNode = anchor.nextSibling;
1046
- for (var i = 0; i < newLength; i++) {
1047
- var node = newElements[i];
1048
- if (currentNode !== node) {
1049
- parent.insertBefore(node, currentNode);
1050
- }
1051
- else {
1052
- currentNode = currentNode.nextSibling;
1053
- }
1054
- }
1055
- }
1056
- // Update maps
1057
- nodeMap.clear();
1058
- for (var i = 0; i < newLength; i++) {
1059
- var itemKey = currentKey(newList[i], i, newList);
1060
- nodeMap.set(itemKey, newElements[i]);
1061
- }
1062
- anchor.__kt_for_list__ = newElements;
1063
- return anchor;
1064
- };
1065
- var _a = props.key, currentKey = _a === void 0 ? function (item) { return item; } : _a, currentMap = props.map;
1066
- var listRef = toReactive(props.list, redraw);
1067
- var anchor = document.createComment('kt-for');
1068
- // Map to track rendered nodes by key
1069
- var nodeMap = new Map();
1070
- // Render initial list
1071
- var elements = [];
1072
- for (var index = 0; index < listRef.value.length; index++) {
1073
- var item = listRef.value[index];
1074
- var itemKey = currentKey(item, index, listRef.value);
1075
- var node = currentMap(item, index, listRef.value);
1076
- nodeMap.set(itemKey, node);
1077
- elements.push(node);
1078
- }
1079
- anchor.__kt_for_list__ = elements;
1080
- $setRef(props, anchor);
1081
- return anchor;
1082
- }
1083
- // Longest Increasing Subsequence algorithm (optimized for diff)
1084
- function getSequence(arr) {
1085
- var p = arr.slice();
1086
- var result = [0];
1087
- var i, j, u, v, c;
1088
- var len = arr.length;
1089
- for (i = 0; i < len; i++) {
1090
- var arrI = arr[i];
1091
- if (arrI === -1)
1092
- continue;
1093
- j = result[result.length - 1];
1094
- if (arr[j] < arrI) {
1095
- p[i] = j;
1096
- result.push(i);
1097
- continue;
1098
- }
1099
- u = 0;
1100
- v = result.length - 1;
1101
- while (u < v) {
1102
- c = ((u + v) / 2) | 0;
1103
- if (arr[result[c]] < arrI) {
1104
- u = c + 1;
1105
- }
1106
- else {
1107
- v = c;
1108
- }
1109
- }
1110
- if (arrI < arr[result[u]]) {
1111
- if (u > 0) {
1112
- p[i] = result[u - 1];
1113
- }
1114
- result[u] = i;
1115
- }
1116
- }
1117
- u = result.length;
1118
- v = result[u - 1];
1119
- while (u-- > 0) {
1120
- result[u] = v;
1121
- v = p[v];
1122
- }
1123
- return result;
1124
- }
1125
-
1126
- exports.$modelOrRef = $modelOrRef;
1127
- exports.$setRef = $setRef;
1128
- exports.Fragment = Fragment;
1129
- exports.KTAsync = KTAsync;
1130
- exports.KTComputed = KTComputed;
1131
- exports.KTFor = KTFor;
1132
- exports.KTRef = KTRef;
1133
- exports.computed = computed;
1134
- exports.createElement = h;
1135
- exports.createRedrawable = createRedrawable;
1136
- exports.dereactive = dereactive;
1137
- exports.effect = effect;
1138
- exports.h = h;
1139
- exports.isComputed = isComputed;
1140
- exports.isKT = isKT;
1141
- exports.isRef = isRef;
1142
- exports.jsx = jsx;
1143
- exports.jsxDEV = jsxDEV;
1144
- exports.jsxs = jsxs;
1145
- exports.ref = ref;
1146
- exports.surfaceRef = surfaceRef;
1147
- exports.toReactive = toReactive;
1148
- exports.toRef = toRef;
1149
-
1150
- return exports;
1151
-
1152
- })({});