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