@sigx/runtime-terminal 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,1356 @@
1
+ //#region ../runtime-core/src/plugins.ts
2
+ const plugins = [];
3
+ /**
4
+ * Get all registered plugins (internal use)
5
+ */
6
+ function getComponentPlugins() {
7
+ return plugins;
8
+ }
9
+
10
+ //#endregion
11
+ //#region ../runtime-core/src/app.ts
12
+ let defaultMountFn = null;
13
+ /**
14
+ * Set the default mount function for the platform.
15
+ * Called by platform packages (runtime-dom, runtime-terminal) on import.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * // In @sigx/runtime-dom
20
+ * import { setDefaultMount } from '@sigx/runtime-core';
21
+ * setDefaultMount(domMount);
22
+ * ```
23
+ */
24
+ function setDefaultMount(mountFn) {
25
+ defaultMountFn = mountFn;
26
+ }
27
+ /**
28
+ * Notify all app hooks that a component was created.
29
+ * Called by the renderer after setup() returns.
30
+ */
31
+ function notifyComponentCreated(context, instance) {
32
+ if (!context) return;
33
+ for (const hooks of context.hooks) try {
34
+ hooks.onComponentCreated?.(instance);
35
+ } catch (err) {
36
+ handleHookError(context, err, instance, "onComponentCreated");
37
+ }
38
+ }
39
+ /**
40
+ * Notify all app hooks that a component was mounted.
41
+ * Called by the renderer after mount hooks run.
42
+ */
43
+ function notifyComponentMounted(context, instance) {
44
+ if (!context) return;
45
+ for (const hooks of context.hooks) try {
46
+ hooks.onComponentMounted?.(instance);
47
+ } catch (err) {
48
+ handleHookError(context, err, instance, "onComponentMounted");
49
+ }
50
+ }
51
+ /**
52
+ * Notify all app hooks that a component was unmounted.
53
+ * Called by the renderer before cleanup.
54
+ */
55
+ function notifyComponentUnmounted(context, instance) {
56
+ if (!context) return;
57
+ for (const hooks of context.hooks) try {
58
+ hooks.onComponentUnmounted?.(instance);
59
+ } catch (err) {
60
+ handleHookError(context, err, instance, "onComponentUnmounted");
61
+ }
62
+ }
63
+ /**
64
+ * Notify all app hooks that a component updated.
65
+ * Called by the renderer after re-render.
66
+ */
67
+ function notifyComponentUpdated(context, instance) {
68
+ if (!context) return;
69
+ for (const hooks of context.hooks) try {
70
+ hooks.onComponentUpdated?.(instance);
71
+ } catch (err) {
72
+ handleHookError(context, err, instance, "onComponentUpdated");
73
+ }
74
+ }
75
+ /**
76
+ * Handle an error in a component. Returns true if the error was handled.
77
+ * Called by the renderer when an error occurs in setup or render.
78
+ */
79
+ function handleComponentError(context, err, instance, info) {
80
+ if (!context) return false;
81
+ for (const hooks of context.hooks) try {
82
+ if (hooks.onComponentError?.(err, instance, info) === true) return true;
83
+ } catch (hookErr) {
84
+ console.error("Error in onComponentError hook:", hookErr);
85
+ }
86
+ if (context.config.errorHandler) try {
87
+ if (context.config.errorHandler(err, instance, info) === true) return true;
88
+ } catch (handlerErr) {
89
+ console.error("Error in app.config.errorHandler:", handlerErr);
90
+ }
91
+ return false;
92
+ }
93
+ /**
94
+ * Handle errors that occur in hooks themselves
95
+ */
96
+ function handleHookError(context, err, instance, hookName) {
97
+ console.error(`Error in ${hookName} hook:`, err);
98
+ if (context.config.errorHandler) try {
99
+ context.config.errorHandler(err, instance, `plugin hook: ${hookName}`);
100
+ } catch {}
101
+ }
102
+
103
+ //#endregion
104
+ //#region ../runtime-core/src/component.ts
105
+ let currentComponentContext = null;
106
+ function getCurrentInstance() {
107
+ return currentComponentContext;
108
+ }
109
+ function setCurrentInstance(ctx) {
110
+ const prev = currentComponentContext;
111
+ currentComponentContext = ctx;
112
+ return prev;
113
+ }
114
+ function onMount(fn) {
115
+ if (currentComponentContext) currentComponentContext.onMount(fn);
116
+ else console.warn("onMount called outside of component setup");
117
+ }
118
+ function onCleanup(fn) {
119
+ if (currentComponentContext) currentComponentContext.onCleanup(fn);
120
+ else console.warn("onCleanup called outside of component setup");
121
+ }
122
+ const componentRegistry = /* @__PURE__ */ new Map();
123
+ /**
124
+ * Define a component. Returns a JSX factory function.
125
+ *
126
+ * @param setup - Setup function that receives context and returns a render function
127
+ * @param options - Optional configuration (e.g., name for DevTools)
128
+ *
129
+ * @example
130
+ * ```tsx
131
+ * type CardProps = DefineProp<"title", string> & DefineSlot<"header">;
132
+ *
133
+ * export const Card = defineComponent<CardProps>((ctx) => {
134
+ * const { title } = ctx.props;
135
+ * const { slots } = ctx;
136
+ *
137
+ * return () => (
138
+ * <div class="card">
139
+ * {slots.header?.() ?? <h2>{title}</h2>}
140
+ * {slots.default()}
141
+ * </div>
142
+ * );
143
+ * });
144
+ * ```
145
+ */
146
+ function defineComponent(setup, options) {
147
+ const factory = function(props) {
148
+ return {
149
+ type: factory,
150
+ props: props || {},
151
+ key: props?.key || null,
152
+ children: [],
153
+ dom: null
154
+ };
155
+ };
156
+ factory.__setup = setup;
157
+ factory.__name = options?.name;
158
+ factory.__props = null;
159
+ factory.__events = null;
160
+ factory.__ref = null;
161
+ factory.__slots = null;
162
+ componentRegistry.set(factory, {
163
+ name: options?.name,
164
+ setup
165
+ });
166
+ getComponentPlugins().forEach((p) => p.onDefine?.(options?.name, factory, setup));
167
+ return factory;
168
+ }
169
+
170
+ //#endregion
171
+ //#region ../reactivity/src/index.ts
172
+ let activeEffect = null;
173
+ let batchDepth = 0;
174
+ const pendingEffects = /* @__PURE__ */ new Set();
175
+ function batch(fn) {
176
+ batchDepth++;
177
+ try {
178
+ fn();
179
+ } finally {
180
+ batchDepth--;
181
+ if (batchDepth === 0) {
182
+ const effects = Array.from(pendingEffects);
183
+ pendingEffects.clear();
184
+ for (const effect$1 of effects) effect$1();
185
+ }
186
+ }
187
+ }
188
+ function runEffect(fn) {
189
+ const effect$1 = function() {
190
+ cleanup(effect$1);
191
+ activeEffect = effect$1;
192
+ fn();
193
+ activeEffect = null;
194
+ };
195
+ effect$1.deps = [];
196
+ effect$1();
197
+ return () => cleanup(effect$1);
198
+ }
199
+ function cleanup(effect$1) {
200
+ if (!effect$1.deps) return;
201
+ for (const dep of effect$1.deps) dep.delete(effect$1);
202
+ effect$1.deps.length = 0;
203
+ }
204
+ function track(depSet) {
205
+ if (!activeEffect) return;
206
+ depSet.add(activeEffect);
207
+ activeEffect.deps.push(depSet);
208
+ }
209
+ function trigger(depSet) {
210
+ const effects = Array.from(depSet);
211
+ for (const effect$1 of effects) if (batchDepth > 0) pendingEffects.add(effect$1);
212
+ else effect$1();
213
+ }
214
+ let accessObserver = null;
215
+ function detectAccess(selector) {
216
+ let result = null;
217
+ const prev = accessObserver;
218
+ accessObserver = (target, key) => {
219
+ result = [target, key];
220
+ };
221
+ try {
222
+ selector();
223
+ } finally {
224
+ accessObserver = prev;
225
+ }
226
+ return result;
227
+ }
228
+ function untrack(fn) {
229
+ const prev = activeEffect;
230
+ activeEffect = null;
231
+ try {
232
+ return fn();
233
+ } finally {
234
+ activeEffect = prev;
235
+ }
236
+ }
237
+ function signal(target) {
238
+ const depsMap = /* @__PURE__ */ new Map();
239
+ const reactiveCache = /* @__PURE__ */ new WeakMap();
240
+ return new Proxy(target, {
241
+ get(obj, prop, receiver) {
242
+ if (prop === "$set") return (newValue) => {
243
+ batch(() => {
244
+ if (Array.isArray(obj) && Array.isArray(newValue)) {
245
+ const len = newValue.length;
246
+ for (let i = 0; i < len; i++) Reflect.set(receiver, String(i), newValue[i]);
247
+ Reflect.set(receiver, "length", len);
248
+ } else {
249
+ const newKeys = Object.keys(newValue);
250
+ const oldKeys = Object.keys(obj);
251
+ for (const key of newKeys) Reflect.set(receiver, key, newValue[key]);
252
+ for (const key of oldKeys) if (!(key in newValue)) Reflect.deleteProperty(receiver, key);
253
+ }
254
+ });
255
+ };
256
+ if (Array.isArray(obj) && typeof prop === "string" && arrayInstrumentations.hasOwnProperty(prop)) return arrayInstrumentations[prop];
257
+ const value = Reflect.get(obj, prop);
258
+ if (accessObserver) accessObserver(receiver, prop);
259
+ let dep = depsMap.get(prop);
260
+ if (!dep) {
261
+ dep = /* @__PURE__ */ new Set();
262
+ depsMap.set(prop, dep);
263
+ }
264
+ track(dep);
265
+ if (value && typeof value === "object") {
266
+ let cached = reactiveCache.get(value);
267
+ if (!cached) {
268
+ cached = signal(value);
269
+ reactiveCache.set(value, cached);
270
+ }
271
+ return cached;
272
+ }
273
+ return value;
274
+ },
275
+ set(obj, prop, newValue) {
276
+ const oldLength = Array.isArray(obj) ? obj.length : 0;
277
+ const oldValue = Reflect.get(obj, prop);
278
+ const result = Reflect.set(obj, prop, newValue);
279
+ if (!Object.is(oldValue, newValue)) {
280
+ const dep = depsMap.get(prop);
281
+ if (dep) trigger(dep);
282
+ if (Array.isArray(obj)) {
283
+ if (prop !== "length" && obj.length !== oldLength) {
284
+ const lengthDep = depsMap.get("length");
285
+ if (lengthDep) trigger(lengthDep);
286
+ }
287
+ if (prop === "length" && typeof newValue === "number" && newValue < oldLength) for (let i = newValue; i < oldLength; i++) {
288
+ const idxDep = depsMap.get(String(i));
289
+ if (idxDep) trigger(idxDep);
290
+ }
291
+ }
292
+ }
293
+ return result;
294
+ },
295
+ deleteProperty(obj, prop) {
296
+ const hasKey = Object.prototype.hasOwnProperty.call(obj, prop);
297
+ const result = Reflect.deleteProperty(obj, prop);
298
+ if (result && hasKey) {
299
+ const dep = depsMap.get(prop);
300
+ if (dep) trigger(dep);
301
+ }
302
+ return result;
303
+ }
304
+ });
305
+ }
306
+ function effect(fn) {
307
+ return runEffect(fn);
308
+ }
309
+ const arrayInstrumentations = {};
310
+ [
311
+ "push",
312
+ "pop",
313
+ "shift",
314
+ "unshift",
315
+ "splice",
316
+ "sort",
317
+ "reverse"
318
+ ].forEach((method) => {
319
+ arrayInstrumentations[method] = function(...args) {
320
+ let res;
321
+ batch(() => {
322
+ res = Array.prototype[method].apply(this, args);
323
+ });
324
+ return res;
325
+ };
326
+ });
327
+
328
+ //#endregion
329
+ //#region ../runtime-core/src/jsx-runtime.ts
330
+ const Fragment$1 = Symbol.for("sigx.Fragment");
331
+ const Text$1 = Symbol.for("sigx.Text");
332
+
333
+ //#endregion
334
+ //#region ../runtime-core/src/renderer.ts
335
+ /**
336
+ * Check if a vnode type is a component (has __setup)
337
+ */
338
+ function isComponent(type) {
339
+ return typeof type === "function" && "__setup" in type;
340
+ }
341
+ function createRenderer(options) {
342
+ const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, cloneNode: hostCloneNode, insertStaticContent: hostInsertStaticContent } = options;
343
+ let isPatching = false;
344
+ let currentAppContext = null;
345
+ function render$1(element, container, appContext) {
346
+ if (appContext) currentAppContext = appContext;
347
+ const oldVNode = container._vnode;
348
+ let vnode = null;
349
+ if (element != null && element !== false && element !== true) if (typeof element === "string" || typeof element === "number") vnode = {
350
+ type: Text$1,
351
+ props: {},
352
+ key: null,
353
+ children: [],
354
+ dom: null,
355
+ text: element
356
+ };
357
+ else vnode = element;
358
+ if (vnode) {
359
+ if (oldVNode) patch(oldVNode, vnode, container);
360
+ else mount(vnode, container);
361
+ container._vnode = vnode;
362
+ } else if (oldVNode) {
363
+ unmount(oldVNode, container);
364
+ container._vnode = null;
365
+ }
366
+ }
367
+ function mount(vnode, container, before = null) {
368
+ if (vnode.type === Text$1) {
369
+ const node = hostCreateText(String(vnode.text));
370
+ vnode.dom = node;
371
+ node.__vnode = vnode;
372
+ hostInsert(node, container, before);
373
+ return;
374
+ }
375
+ if (vnode.type === Fragment$1) {
376
+ const anchor = hostCreateComment("");
377
+ vnode.dom = anchor;
378
+ hostInsert(anchor, container, before);
379
+ vnode.children.forEach((child) => mount(child, container, anchor));
380
+ return;
381
+ }
382
+ if (isComponent(vnode.type)) {
383
+ mountComponent(vnode, container, before, vnode.type.__setup);
384
+ return;
385
+ }
386
+ const element = hostCreateElement(vnode.type);
387
+ vnode.dom = element;
388
+ element.__vnode = vnode;
389
+ if (vnode.props) {
390
+ for (const key in vnode.props) if (key !== "children" && key !== "key" && key !== "ref") hostPatchProp(element, key, null, vnode.props[key]);
391
+ }
392
+ if (vnode.props.ref) {
393
+ if (typeof vnode.props.ref === "function") vnode.props.ref(element);
394
+ else if (vnode.props.ref && typeof vnode.props.ref === "object") vnode.props.ref.current = element;
395
+ }
396
+ vnode.children.forEach((child) => {
397
+ child.parent = vnode;
398
+ mount(child, element);
399
+ });
400
+ hostInsert(element, container, before);
401
+ }
402
+ function unmount(vnode, container) {
403
+ if (vnode._effect) vnode._effect();
404
+ if (vnode.cleanup) vnode.cleanup();
405
+ if (isComponent(vnode.type)) {
406
+ const subTree = vnode._subTree;
407
+ if (subTree) unmount(subTree, container);
408
+ if (vnode.dom) hostRemove(vnode.dom);
409
+ if (vnode.props?.ref) {
410
+ if (typeof vnode.props.ref === "function") vnode.props.ref(null);
411
+ else if (typeof vnode.props.ref === "object") vnode.props.ref.current = null;
412
+ }
413
+ return;
414
+ }
415
+ if (vnode.type === Fragment$1) {
416
+ vnode.children.forEach((child) => unmount(child, container));
417
+ if (vnode.dom) hostRemove(vnode.dom);
418
+ return;
419
+ }
420
+ if (vnode.props?.ref) {
421
+ if (typeof vnode.props.ref === "function") vnode.props.ref(null);
422
+ else if (vnode.props.ref && typeof vnode.props.ref === "object") vnode.props.ref.current = null;
423
+ }
424
+ if (vnode.children && vnode.children.length > 0) vnode.children.forEach((child) => unmount(child, vnode.dom));
425
+ if (vnode.dom) hostRemove(vnode.dom);
426
+ }
427
+ function patch(oldVNode, newVNode, container) {
428
+ if (oldVNode === newVNode) return;
429
+ if (!isSameVNode(oldVNode, newVNode)) {
430
+ const parent = hostParentNode(oldVNode.dom) || container;
431
+ const nextSibling = hostNextSibling(oldVNode.dom);
432
+ unmount(oldVNode, parent);
433
+ mount(newVNode, parent, nextSibling);
434
+ return;
435
+ }
436
+ if (oldVNode._effect) {
437
+ newVNode.dom = oldVNode.dom;
438
+ newVNode._effect = oldVNode._effect;
439
+ newVNode._subTree = oldVNode._subTree;
440
+ newVNode._slots = oldVNode._slots;
441
+ const props = oldVNode._componentProps;
442
+ newVNode._componentProps = props;
443
+ if (props) {
444
+ const newProps$1 = newVNode.props || {};
445
+ untrack(() => {
446
+ for (const key in newProps$1) if (key !== "children" && key !== "key" && key !== "ref") {
447
+ if (props[key] !== newProps$1[key]) props[key] = newProps$1[key];
448
+ }
449
+ for (const key in props) if (!(key in newProps$1) && key !== "children" && key !== "key" && key !== "ref") delete props[key];
450
+ });
451
+ }
452
+ const slotsRef = oldVNode._slots;
453
+ const newChildren = newVNode.props?.children;
454
+ const newSlotsFromProps = newVNode.props?.slots;
455
+ if (slotsRef) {
456
+ if (newChildren !== void 0) slotsRef._children = newChildren;
457
+ if (newSlotsFromProps !== void 0) slotsRef._slotsFromProps = newSlotsFromProps;
458
+ if (!isPatching) {
459
+ isPatching = true;
460
+ try {
461
+ untrack(() => {
462
+ slotsRef._version.v++;
463
+ });
464
+ } finally {
465
+ isPatching = false;
466
+ }
467
+ }
468
+ }
469
+ return;
470
+ }
471
+ if (newVNode.type === Text$1) {
472
+ newVNode.dom = oldVNode.dom;
473
+ if (oldVNode.text !== newVNode.text) hostSetText(newVNode.dom, String(newVNode.text));
474
+ return;
475
+ }
476
+ if (newVNode.type === Fragment$1) {
477
+ patchChildren(oldVNode, newVNode, container);
478
+ return;
479
+ }
480
+ const element = newVNode.dom = oldVNode.dom;
481
+ const oldProps = oldVNode.props || {};
482
+ const newProps = newVNode.props || {};
483
+ for (const key in oldProps) if (!(key in newProps) && key !== "children" && key !== "key" && key !== "ref") hostPatchProp(element, key, oldProps[key], null);
484
+ for (const key in newProps) {
485
+ const oldValue = oldProps[key];
486
+ const newValue = newProps[key];
487
+ if (key !== "children" && key !== "key" && key !== "ref" && oldValue !== newValue) hostPatchProp(element, key, oldValue, newValue);
488
+ }
489
+ patchChildren(oldVNode, newVNode, element);
490
+ }
491
+ function patchChildren(oldVNode, newVNode, container) {
492
+ const oldChildren = oldVNode.children;
493
+ const newChildren = newVNode.children;
494
+ newChildren.forEach((c) => c.parent = newVNode);
495
+ reconcileChildrenArray(container, oldChildren, newChildren);
496
+ }
497
+ function reconcileChildrenArray(parent, oldChildren, newChildren) {
498
+ let oldStartIdx = 0;
499
+ let oldEndIdx = oldChildren.length - 1;
500
+ let oldStartVNode = oldChildren[0];
501
+ let oldEndVNode = oldChildren[oldEndIdx];
502
+ let newStartIdx = 0;
503
+ let newEndIdx = newChildren.length - 1;
504
+ let newStartVNode = newChildren[0];
505
+ let newEndVNode = newChildren[newEndIdx];
506
+ let oldKeyToIdx;
507
+ while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) if (oldStartVNode == null) oldStartVNode = oldChildren[++oldStartIdx];
508
+ else if (oldEndVNode == null) oldEndVNode = oldChildren[--oldEndIdx];
509
+ else if (isSameVNode(oldStartVNode, newStartVNode)) {
510
+ patch(oldStartVNode, newStartVNode, parent);
511
+ oldStartVNode = oldChildren[++oldStartIdx];
512
+ newStartVNode = newChildren[++newStartIdx];
513
+ } else if (isSameVNode(oldEndVNode, newEndVNode)) {
514
+ patch(oldEndVNode, newEndVNode, parent);
515
+ oldEndVNode = oldChildren[--oldEndIdx];
516
+ newEndVNode = newChildren[--newEndIdx];
517
+ } else if (isSameVNode(oldStartVNode, newEndVNode)) {
518
+ patch(oldStartVNode, newEndVNode, parent);
519
+ const nodeToMove = oldStartVNode.dom;
520
+ const anchor = hostNextSibling(oldEndVNode.dom);
521
+ if (nodeToMove) hostInsert(nodeToMove, parent, anchor);
522
+ oldStartVNode = oldChildren[++oldStartIdx];
523
+ newEndVNode = newChildren[--newEndIdx];
524
+ } else if (isSameVNode(oldEndVNode, newStartVNode)) {
525
+ patch(oldEndVNode, newStartVNode, parent);
526
+ const nodeToMove = oldEndVNode.dom;
527
+ const anchor = oldStartVNode.dom;
528
+ if (nodeToMove) hostInsert(nodeToMove, parent, anchor);
529
+ oldEndVNode = oldChildren[--oldEndIdx];
530
+ newStartVNode = newChildren[++newStartIdx];
531
+ } else {
532
+ if (!oldKeyToIdx) oldKeyToIdx = createKeyToKeyIndexMap(oldChildren, oldStartIdx, oldEndIdx);
533
+ const idxInOld = newStartVNode.key != null ? oldKeyToIdx.get(String(newStartVNode.key)) : findIndexInOld(oldChildren, newStartVNode, oldStartIdx, oldEndIdx);
534
+ if (idxInOld != null) {
535
+ const vnodeToMove = oldChildren[idxInOld];
536
+ patch(vnodeToMove, newStartVNode, parent);
537
+ oldChildren[idxInOld] = void 0;
538
+ if (vnodeToMove.dom && oldStartVNode.dom) hostInsert(vnodeToMove.dom, parent, oldStartVNode.dom);
539
+ } else mount(newStartVNode, parent, oldStartVNode.dom);
540
+ newStartVNode = newChildren[++newStartIdx];
541
+ }
542
+ if (oldStartIdx > oldEndIdx) {
543
+ if (newStartIdx <= newEndIdx) {
544
+ const anchor = newChildren[newEndIdx + 1] == null ? null : newChildren[newEndIdx + 1].dom;
545
+ for (let i = newStartIdx; i <= newEndIdx; i++) mount(newChildren[i], parent, anchor);
546
+ }
547
+ } else if (newStartIdx > newEndIdx) {
548
+ for (let i = oldStartIdx; i <= oldEndIdx; i++) if (oldChildren[i]) unmount(oldChildren[i], parent);
549
+ }
550
+ }
551
+ function isSameVNode(n1, n2) {
552
+ const k1 = n1.key == null ? null : n1.key;
553
+ const k2 = n2.key == null ? null : n2.key;
554
+ if (n1.type !== n2.type) return false;
555
+ if (k1 === k2) return true;
556
+ return String(k1) === String(k2);
557
+ }
558
+ function createKeyToKeyIndexMap(children, beginIdx, endIdx) {
559
+ const map = /* @__PURE__ */ new Map();
560
+ for (let i = beginIdx; i <= endIdx; i++) {
561
+ const key = children[i]?.key;
562
+ if (key != null) map.set(String(key), i);
563
+ }
564
+ return map;
565
+ }
566
+ function findIndexInOld(children, newChild, beginIdx, endIdx) {
567
+ for (let i = beginIdx; i <= endIdx; i++) if (children[i] && isSameVNode(children[i], newChild)) return i;
568
+ return null;
569
+ }
570
+ function mountComponent(vnode, container, before, setup) {
571
+ const anchor = hostCreateComment("");
572
+ vnode.dom = anchor;
573
+ anchor.__vnode = vnode;
574
+ hostInsert(anchor, container, before);
575
+ let exposed = null;
576
+ let exposeCalled = false;
577
+ const { children, slots: slotsFromProps, ...propsData } = vnode.props || {};
578
+ const reactiveProps = signal(propsData);
579
+ vnode._componentProps = reactiveProps;
580
+ const slots = createSlots(children, slotsFromProps);
581
+ vnode._slots = slots;
582
+ const mountHooks = [];
583
+ const cleanupHooks = [];
584
+ const parentInstance = getCurrentInstance();
585
+ const componentName = vnode.type.__name;
586
+ const ctx = {
587
+ el: container,
588
+ signal,
589
+ props: reactiveProps,
590
+ slots,
591
+ emit: (event, ...args) => {
592
+ const handler = reactiveProps[`on${event[0].toUpperCase() + event.slice(1)}`];
593
+ if (handler && typeof handler === "function") handler(...args);
594
+ },
595
+ parent: parentInstance,
596
+ onMount: (fn) => {
597
+ mountHooks.push(fn);
598
+ },
599
+ onCleanup: (fn) => {
600
+ cleanupHooks.push(fn);
601
+ },
602
+ expose: (exposedValue) => {
603
+ exposed = exposedValue;
604
+ exposeCalled = true;
605
+ }
606
+ };
607
+ ctx.__name = componentName;
608
+ if (currentAppContext) ctx._appContext = currentAppContext;
609
+ const componentInstance = {
610
+ name: componentName,
611
+ ctx,
612
+ vnode
613
+ };
614
+ const prev = setCurrentInstance(ctx);
615
+ let renderFn;
616
+ try {
617
+ renderFn = setup(ctx);
618
+ notifyComponentCreated(currentAppContext, componentInstance);
619
+ } catch (err) {
620
+ if (!handleComponentError(currentAppContext, err, componentInstance, "setup")) throw err;
621
+ } finally {
622
+ setCurrentInstance(prev);
623
+ }
624
+ if (vnode.props.ref) {
625
+ const refValue = exposeCalled ? exposed : null;
626
+ if (typeof vnode.props.ref === "function") vnode.props.ref(refValue);
627
+ else if (vnode.props.ref && typeof vnode.props.ref === "object") vnode.props.ref.current = refValue;
628
+ }
629
+ if (renderFn) vnode._effect = effect(() => {
630
+ const prevInstance = setCurrentInstance(ctx);
631
+ try {
632
+ const subTreeResult = renderFn();
633
+ if (subTreeResult == null) return;
634
+ const subTree = normalizeSubTree(subTreeResult);
635
+ const prevSubTree = vnode._subTree;
636
+ if (prevSubTree) {
637
+ patch(prevSubTree, subTree, container);
638
+ notifyComponentUpdated(currentAppContext, componentInstance);
639
+ } else mount(subTree, container, anchor);
640
+ vnode._subTree = subTree;
641
+ } catch (err) {
642
+ if (!handleComponentError(currentAppContext, err, componentInstance, "render")) throw err;
643
+ } finally {
644
+ setCurrentInstance(prevInstance);
645
+ }
646
+ });
647
+ const mountCtx = { el: container };
648
+ mountHooks.forEach((hook) => hook(mountCtx));
649
+ notifyComponentMounted(currentAppContext, componentInstance);
650
+ vnode.cleanup = () => {
651
+ notifyComponentUnmounted(currentAppContext, componentInstance);
652
+ cleanupHooks.forEach((hook) => hook(mountCtx));
653
+ };
654
+ }
655
+ /**
656
+ * Create slots object from children and slots prop.
657
+ * Uses a version signal to trigger re-renders when children change.
658
+ * Supports named slots via:
659
+ * - `slots` prop object (e.g., slots={{ header: () => <div>...</div> }})
660
+ * - `slot` prop on children (e.g., <div slot="header">...</div>)
661
+ */
662
+ function createSlots(children, slotsFromProps) {
663
+ const versionSignal = signal({ v: 0 });
664
+ function extractNamedSlotsFromChildren(c) {
665
+ const defaultChildren = [];
666
+ const namedSlots = {};
667
+ if (c == null) return {
668
+ defaultChildren,
669
+ namedSlots
670
+ };
671
+ const items = Array.isArray(c) ? c : [c];
672
+ for (const child of items) if (child && typeof child === "object" && child.props && child.props.slot) {
673
+ const slotName = child.props.slot;
674
+ if (!namedSlots[slotName]) namedSlots[slotName] = [];
675
+ namedSlots[slotName].push(child);
676
+ } else defaultChildren.push(child);
677
+ return {
678
+ defaultChildren,
679
+ namedSlots
680
+ };
681
+ }
682
+ const slotsObj = {
683
+ _children: children,
684
+ _slotsFromProps: slotsFromProps || {},
685
+ _version: versionSignal,
686
+ default: function() {
687
+ this._version.v;
688
+ const c = this._children;
689
+ const { defaultChildren } = extractNamedSlotsFromChildren(c);
690
+ return defaultChildren;
691
+ }
692
+ };
693
+ return new Proxy(slotsObj, { get(target, prop) {
694
+ if (prop in target) return target[prop];
695
+ if (typeof prop === "string") return function(scopedProps) {
696
+ target._version.v;
697
+ if (target._slotsFromProps && typeof target._slotsFromProps[prop] === "function") {
698
+ const result = target._slotsFromProps[prop](scopedProps);
699
+ if (result == null) return [];
700
+ return Array.isArray(result) ? result : [result];
701
+ }
702
+ const { namedSlots } = extractNamedSlotsFromChildren(target._children);
703
+ return namedSlots[prop] || [];
704
+ };
705
+ } });
706
+ }
707
+ /**
708
+ * Normalize render result to a VNode (wrapping arrays in Fragment)
709
+ */
710
+ function normalizeSubTree(result) {
711
+ if (Array.isArray(result)) return {
712
+ type: Fragment$1,
713
+ props: {},
714
+ key: null,
715
+ children: result,
716
+ dom: null
717
+ };
718
+ if (typeof result === "string" || typeof result === "number") return {
719
+ type: Text$1,
720
+ props: {},
721
+ key: null,
722
+ children: [],
723
+ dom: null,
724
+ text: result
725
+ };
726
+ return result;
727
+ }
728
+ return {
729
+ render: render$1,
730
+ createApp: (rootComponent) => {
731
+ return { mount(selectorOrContainer) {
732
+ let container = null;
733
+ if (typeof selectorOrContainer === "string") {
734
+ if (options.querySelector) container = options.querySelector(selectorOrContainer);
735
+ } else container = selectorOrContainer;
736
+ if (!container) {
737
+ console.warn(`Container not found: ${selectorOrContainer}`);
738
+ return;
739
+ }
740
+ render$1(rootComponent, container);
741
+ } };
742
+ }
743
+ };
744
+ }
745
+
746
+ //#endregion
747
+ //#region src/focus.ts
748
+ const focusableIds = /* @__PURE__ */ new Set();
749
+ const focusState = signal({ activeId: null });
750
+ function registerFocusable(id) {
751
+ focusableIds.add(id);
752
+ if (focusState.activeId === null) focusState.activeId = id;
753
+ }
754
+ function unregisterFocusable(id) {
755
+ focusableIds.delete(id);
756
+ if (focusState.activeId === id) {
757
+ focusState.activeId = null;
758
+ if (focusableIds.size > 0) focusState.activeId = focusableIds.values().next().value || null;
759
+ }
760
+ }
761
+ function focus(id) {
762
+ if (focusableIds.has(id)) focusState.activeId = id;
763
+ }
764
+ function focusNext() {
765
+ if (focusableIds.size === 0) return;
766
+ const ids = Array.from(focusableIds);
767
+ focusState.activeId = ids[((focusState.activeId ? ids.indexOf(focusState.activeId) : -1) + 1) % ids.length];
768
+ }
769
+ function focusPrev() {
770
+ if (focusableIds.size === 0) return;
771
+ const ids = Array.from(focusableIds);
772
+ focusState.activeId = ids[((focusState.activeId ? ids.indexOf(focusState.activeId) : -1) - 1 + ids.length) % ids.length];
773
+ }
774
+
775
+ //#endregion
776
+ //#region src/utils.ts
777
+ function getColorCode(color) {
778
+ switch (color) {
779
+ case "red": return "\x1B[31m";
780
+ case "green": return "\x1B[32m";
781
+ case "blue": return "\x1B[34m";
782
+ case "yellow": return "\x1B[33m";
783
+ case "cyan": return "\x1B[36m";
784
+ case "white": return "\x1B[37m";
785
+ case "black": return "\x1B[30m";
786
+ default: return "";
787
+ }
788
+ }
789
+ function getBackgroundColorCode(color) {
790
+ switch (color) {
791
+ case "red": return "\x1B[41m";
792
+ case "green": return "\x1B[42m";
793
+ case "blue": return "\x1B[44m";
794
+ case "yellow": return "\x1B[43m";
795
+ case "cyan": return "\x1B[46m";
796
+ case "white": return "\x1B[47m";
797
+ case "black": return "\x1B[40m";
798
+ default: return "";
799
+ }
800
+ }
801
+ function stripAnsi(str) {
802
+ return str.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, "");
803
+ }
804
+
805
+ //#endregion
806
+ //#region ../runtime-core/dist/index.js
807
+ let platformSyncProcessor = null;
808
+ /**
809
+ * Get the current platform sync processor (for internal use).
810
+ */
811
+ function getPlatformSyncProcessor() {
812
+ return platformSyncProcessor;
813
+ }
814
+ const Fragment = Symbol.for("sigx.Fragment");
815
+ const Text = Symbol.for("sigx.Text");
816
+ function normalizeChildren(children) {
817
+ if (children == null || children === false || children === true) return [];
818
+ if (Array.isArray(children)) return children.flatMap((c) => normalizeChildren(c));
819
+ if (typeof children === "string" || typeof children === "number") return [{
820
+ type: Text,
821
+ props: {},
822
+ key: null,
823
+ children: [],
824
+ dom: null,
825
+ text: children
826
+ }];
827
+ if (children.type) return [children];
828
+ return [];
829
+ }
830
+ /**
831
+ * Check if a type is a sigx component (has __setup)
832
+ */
833
+ function isComponent$1(type) {
834
+ return typeof type === "function" && "__setup" in type;
835
+ }
836
+ /**
837
+ * Create a JSX element - this is the core function called by TSX transpilation
838
+ */
839
+ function jsx(type, props, key) {
840
+ const processedProps = { ...props || {} };
841
+ if (props) {
842
+ for (const propKey in props) if (propKey === "sync") {
843
+ let syncBinding = props[propKey];
844
+ if (typeof syncBinding === "function") {
845
+ const detected = detectAccess(syncBinding);
846
+ if (detected) syncBinding = detected;
847
+ }
848
+ if (Array.isArray(syncBinding) && syncBinding.length === 2) {
849
+ const [stateObj, key$1] = syncBinding;
850
+ let handled = false;
851
+ const platformProcessor = getPlatformSyncProcessor();
852
+ if (typeof type === "string" && platformProcessor) handled = platformProcessor(type, processedProps, [stateObj, key$1], props);
853
+ if (!handled) {
854
+ processedProps.value = stateObj[key$1];
855
+ const existingHandler = processedProps["onUpdate:value"];
856
+ processedProps["onUpdate:value"] = (v) => {
857
+ stateObj[key$1] = v;
858
+ if (existingHandler) existingHandler(v);
859
+ };
860
+ }
861
+ delete processedProps.sync;
862
+ }
863
+ } else if (propKey.startsWith("sync:")) {
864
+ const syncBinding = props[propKey];
865
+ if (Array.isArray(syncBinding) && syncBinding.length === 2) {
866
+ const [stateObj, key$1] = syncBinding;
867
+ const name = propKey.slice(5);
868
+ processedProps[name] = stateObj[key$1];
869
+ const eventName = `onUpdate:${name}`;
870
+ const existingHandler = processedProps[eventName];
871
+ processedProps[eventName] = (v) => {
872
+ stateObj[key$1] = v;
873
+ if (existingHandler) existingHandler(v);
874
+ };
875
+ delete processedProps[propKey];
876
+ }
877
+ }
878
+ }
879
+ if (isComponent$1(type)) {
880
+ const { children: children$1, ...rest$1 } = processedProps;
881
+ return {
882
+ type,
883
+ props: {
884
+ ...rest$1,
885
+ children: children$1
886
+ },
887
+ key: key || rest$1.key || null,
888
+ children: [],
889
+ dom: null
890
+ };
891
+ }
892
+ if (typeof type === "function" && type !== Fragment) return type(processedProps);
893
+ const { children, ...rest } = processedProps;
894
+ return {
895
+ type,
896
+ props: rest,
897
+ key: key || rest.key || null,
898
+ children: normalizeChildren(children),
899
+ dom: null
900
+ };
901
+ }
902
+ /**
903
+ * JSX Factory for fragments
904
+ */
905
+ function jsxs(type, props, key) {
906
+ return jsx(type, props, key);
907
+ }
908
+
909
+ //#endregion
910
+ //#region src/components/Input.tsx
911
+ /** @jsxImportSource @sigx/runtime-core */
912
+ const Input = defineComponent(({ props, emit }) => {
913
+ const id = Math.random().toString(36).slice(2);
914
+ const isFocused = () => focusState.activeId === id;
915
+ const handleKey = (key) => {
916
+ if (!isFocused()) return;
917
+ if (key === "\r") {
918
+ emit("submit", props.value || "");
919
+ return;
920
+ }
921
+ if (key === "\n") return;
922
+ if (key === "" || key === "\b") {
923
+ const val = props.value || "";
924
+ if (val.length > 0) {
925
+ const newValue$1 = val.slice(0, -1);
926
+ emit("update:value", newValue$1);
927
+ emit("input", newValue$1);
928
+ }
929
+ return;
930
+ }
931
+ if (key.length > 1) return;
932
+ const newValue = (props.value || "") + key;
933
+ emit("update:value", newValue);
934
+ emit("input", newValue);
935
+ };
936
+ let keyCleanup = null;
937
+ onMount(() => {
938
+ registerFocusable(id);
939
+ if (props.autofocus) focus(id);
940
+ keyCleanup = onKey(handleKey);
941
+ });
942
+ onCleanup(() => {
943
+ if (keyCleanup) keyCleanup();
944
+ unregisterFocusable(id);
945
+ });
946
+ return () => {
947
+ const val = (props.value || "").replace(/[\r\n]+/g, " ");
948
+ const placeholder = (props.placeholder || "").replace(/[\r\n]+/g, " ");
949
+ const showCursor = isFocused();
950
+ return /* @__PURE__ */ jsxs("box", {
951
+ border: "single",
952
+ borderColor: showCursor ? "green" : "white",
953
+ label: props.label,
954
+ children: [/* @__PURE__ */ jsx("text", { children: val || placeholder }), showCursor && /* @__PURE__ */ jsx("text", {
955
+ color: "cyan",
956
+ children: "_"
957
+ })]
958
+ });
959
+ };
960
+ }, { name: "Input" });
961
+
962
+ //#endregion
963
+ //#region src/components/ProgressBar.tsx
964
+ /** @jsxImportSource @sigx/runtime-core */
965
+ const ProgressBar = defineComponent(({ props }) => {
966
+ return () => {
967
+ const value = props.value || 0;
968
+ const max = props.max || 100;
969
+ const width = props.width || 20;
970
+ const barChar = props.char || "█";
971
+ const emptyChar = props.emptyChar || "░";
972
+ const color = props.color;
973
+ const colorCode = color ? getColorCode(color) : "";
974
+ const reset = color ? "\x1B[0m" : "";
975
+ const percentage = Math.min(Math.max(value / max, 0), 1);
976
+ const filledLen = Math.round(width * percentage);
977
+ const emptyLen = width - filledLen;
978
+ return /* @__PURE__ */ jsx("box", { children: /* @__PURE__ */ jsx("text", { children: colorCode + barChar.repeat(filledLen) + emptyChar.repeat(emptyLen) + reset + ` ${Math.round(percentage * 100)}%` }) });
979
+ };
980
+ }, { name: "ProgressBar" });
981
+
982
+ //#endregion
983
+ //#region src/components/Button.tsx
984
+ /** @jsxImportSource @sigx/runtime-core */
985
+ const Button = defineComponent(({ props, emit }) => {
986
+ const id = Math.random().toString(36).slice(2);
987
+ const isFocused = () => focusState.activeId === id;
988
+ const pressed = signal({ value: false });
989
+ const handleKey = (key) => {
990
+ if (!isFocused()) return;
991
+ if (key === "\r" || key === " ") {
992
+ pressed.value = true;
993
+ if (pressTimer) clearTimeout(pressTimer);
994
+ pressTimer = setTimeout(() => {
995
+ pressed.value = false;
996
+ pressTimer = null;
997
+ }, 120);
998
+ emit("click");
999
+ }
1000
+ };
1001
+ let keyCleanup = null;
1002
+ let pressTimer = null;
1003
+ onMount(() => {
1004
+ registerFocusable(id);
1005
+ keyCleanup = onKey(handleKey);
1006
+ });
1007
+ onCleanup(() => {
1008
+ if (keyCleanup) keyCleanup();
1009
+ unregisterFocusable(id);
1010
+ if (pressTimer) clearTimeout(pressTimer);
1011
+ });
1012
+ return () => {
1013
+ const focused = isFocused();
1014
+ const label = props.label || "Button";
1015
+ const isPressed = pressed.value;
1016
+ return /* @__PURE__ */ jsx("box", {
1017
+ border: "single",
1018
+ borderColor: isPressed ? "yellow" : focused ? "green" : "white",
1019
+ backgroundColor: isPressed ? "red" : focused ? "blue" : void 0,
1020
+ dropShadow: props.dropShadow,
1021
+ children: /* @__PURE__ */ jsx("text", {
1022
+ color: focused ? "white" : void 0,
1023
+ children: label
1024
+ })
1025
+ });
1026
+ };
1027
+ }, { name: "Button" });
1028
+
1029
+ //#endregion
1030
+ //#region src/components/Checkbox.tsx
1031
+ /** @jsxImportSource @sigx/runtime-core */
1032
+ const Checkbox = defineComponent(({ props, emit }) => {
1033
+ const id = Math.random().toString(36).slice(2);
1034
+ const isFocused = () => focusState.activeId === id;
1035
+ const checked = () => !!props.value;
1036
+ const handleKey = (key) => {
1037
+ if (!isFocused()) return;
1038
+ if (props.disabled) return;
1039
+ if (key === "\r" || key === " ") {
1040
+ const next = !checked();
1041
+ emit("update:value", next);
1042
+ emit("change", next);
1043
+ }
1044
+ };
1045
+ let keyCleanup = null;
1046
+ onMount(() => {
1047
+ registerFocusable(id);
1048
+ if (props.autofocus) focus(id);
1049
+ keyCleanup = onKey(handleKey);
1050
+ });
1051
+ onCleanup(() => {
1052
+ if (keyCleanup) keyCleanup();
1053
+ unregisterFocusable(id);
1054
+ });
1055
+ return () => {
1056
+ const label = props.label || "";
1057
+ const focused = isFocused();
1058
+ const isChecked = checked();
1059
+ const disabled = !!props.disabled;
1060
+ return /* @__PURE__ */ jsxs("box", { children: [
1061
+ /* @__PURE__ */ jsx("text", {
1062
+ color: focused ? "cyan" : "white",
1063
+ children: focused ? ">" : " "
1064
+ }),
1065
+ /* @__PURE__ */ jsxs("text", {
1066
+ color: disabled ? "white" : isChecked ? "green" : focused ? "cyan" : "white",
1067
+ children: [
1068
+ "[",
1069
+ isChecked ? "x" : " ",
1070
+ "]"
1071
+ ]
1072
+ }),
1073
+ label && /* @__PURE__ */ jsxs("text", {
1074
+ color: disabled ? "white" : focused ? "cyan" : void 0,
1075
+ children: [" ", label]
1076
+ })
1077
+ ] });
1078
+ };
1079
+ }, { name: "Checkbox" });
1080
+
1081
+ //#endregion
1082
+ //#region src/index.ts
1083
+ const renderer = createRenderer({
1084
+ patchProp: (el, key, prev, next) => {
1085
+ el.props[key] = next;
1086
+ scheduleRender();
1087
+ },
1088
+ insert: (child, parent, anchor) => {
1089
+ child.parentNode = parent;
1090
+ const index = anchor ? parent.children.indexOf(anchor) : -1;
1091
+ if (index > -1) parent.children.splice(index, 0, child);
1092
+ else parent.children.push(child);
1093
+ scheduleRender();
1094
+ },
1095
+ remove: (child) => {
1096
+ if (child.parentNode) {
1097
+ const index = child.parentNode.children.indexOf(child);
1098
+ if (index > -1) child.parentNode.children.splice(index, 1);
1099
+ child.parentNode = null;
1100
+ }
1101
+ scheduleRender();
1102
+ },
1103
+ createElement: (tag) => {
1104
+ return {
1105
+ type: "element",
1106
+ tag,
1107
+ props: {},
1108
+ children: []
1109
+ };
1110
+ },
1111
+ createText: (text) => {
1112
+ return {
1113
+ type: "text",
1114
+ text,
1115
+ props: {},
1116
+ children: []
1117
+ };
1118
+ },
1119
+ createComment: (text) => {
1120
+ return {
1121
+ type: "comment",
1122
+ text,
1123
+ props: {},
1124
+ children: []
1125
+ };
1126
+ },
1127
+ setText: (node, text) => {
1128
+ node.text = text;
1129
+ scheduleRender();
1130
+ },
1131
+ setElementText: (node, text) => {
1132
+ node.children = [{
1133
+ type: "text",
1134
+ text,
1135
+ props: {},
1136
+ children: [],
1137
+ parentNode: node
1138
+ }];
1139
+ scheduleRender();
1140
+ },
1141
+ parentNode: (node) => node.parentNode || null,
1142
+ nextSibling: (node) => {
1143
+ if (!node.parentNode) return null;
1144
+ const idx = node.parentNode.children.indexOf(node);
1145
+ return node.parentNode.children[idx + 1] || null;
1146
+ },
1147
+ cloneNode: (node) => {
1148
+ return {
1149
+ ...node,
1150
+ children: []
1151
+ };
1152
+ }
1153
+ });
1154
+ const { render, createApp } = renderer;
1155
+ let rootNode = null;
1156
+ let isRendering = false;
1157
+ function scheduleRender() {
1158
+ if (isRendering) return;
1159
+ isRendering = true;
1160
+ setTimeout(() => {
1161
+ flushRender();
1162
+ isRendering = false;
1163
+ }, 10);
1164
+ }
1165
+ function flushRender() {
1166
+ if (!rootNode) return;
1167
+ process.stdout.write("\x1B[H");
1168
+ const lines = renderNodeToLines(rootNode);
1169
+ process.stdout.write(lines.join("\x1B[K\n") + "\x1B[K");
1170
+ process.stdout.write("\x1B[J");
1171
+ }
1172
+ /**
1173
+ * Check if a node has a box element as an immediate child.
1174
+ * This is used to determine if a component wrapper should be treated as a block element.
1175
+ */
1176
+ function hasBoxChild(node) {
1177
+ for (const child of node.children) if (child.tag === "box") return true;
1178
+ return false;
1179
+ }
1180
+ function renderNodeToLines(node) {
1181
+ if (node.type === "text") return [node.text || ""];
1182
+ if (node.type === "comment") return [];
1183
+ let lines = [""];
1184
+ const color = node.props.color;
1185
+ const reset = color ? "\x1B[0m" : "";
1186
+ const colorCode = getColorCode(color);
1187
+ for (const child of node.children) if (child.type === "text") lines[lines.length - 1] += colorCode + (child.text || "") + reset;
1188
+ else if (child.tag === "br") lines.push("");
1189
+ else {
1190
+ const childLines = renderNodeToLines(child);
1191
+ if (child.tag === "box" || hasBoxChild(child)) if (lines.length === 1 && lines[0] === "") lines = childLines;
1192
+ else lines.push(...childLines);
1193
+ else if (childLines.length > 0) if (childLines.length > 1) if (lines.length === 1 && lines[0] === "") lines = childLines;
1194
+ else lines.push(...childLines);
1195
+ else {
1196
+ lines[lines.length - 1] += childLines[0];
1197
+ for (let i = 1; i < childLines.length; i++) lines.push(childLines[i]);
1198
+ }
1199
+ }
1200
+ if (node.tag === "box" && node.props.border) return drawBox(lines, node.props.border, node.props.borderColor, node.props.backgroundColor, node.props.dropShadow, node.props.label);
1201
+ return lines;
1202
+ }
1203
+ function drawBox(contentLines, style, color, backgroundColor, dropShadow, label) {
1204
+ const borderChars = getBorderChars(style);
1205
+ const colorCode = color ? getColorCode(color) : "";
1206
+ const bgCode = backgroundColor ? getBackgroundColorCode(backgroundColor) : "";
1207
+ const reset = color || backgroundColor ? "\x1B[0m" : "";
1208
+ const width = contentLines.reduce((max, line) => Math.max(max, stripAnsi(line).length), 0);
1209
+ const labelText = label || "";
1210
+ const labelLength = stripAnsi(labelText).length;
1211
+ const boxInnerWidth = Math.max(width, labelLength + 2);
1212
+ let topInner = "";
1213
+ if (labelText) {
1214
+ const spaceForLabel = boxInnerWidth - labelLength - 2;
1215
+ const leftH = Math.floor(spaceForLabel / 2);
1216
+ const rightH = spaceForLabel - leftH;
1217
+ topInner = borderChars.h.repeat(leftH) + " " + labelText + " " + borderChars.h.repeat(rightH);
1218
+ } else topInner = borderChars.h.repeat(boxInnerWidth);
1219
+ const top = bgCode + colorCode + borderChars.tl + topInner + borderChars.tr + reset;
1220
+ const bottom = bgCode + colorCode + borderChars.bl + borderChars.h.repeat(boxInnerWidth) + borderChars.br + reset;
1221
+ const result = [];
1222
+ result.push(top);
1223
+ for (const line of contentLines) {
1224
+ const visibleLength = stripAnsi(line).length;
1225
+ const padding = " ".repeat(boxInnerWidth - visibleLength);
1226
+ const lineWithBg = bgCode + line.replace(/\x1b\[0m/g, `\x1b[0m${bgCode}`);
1227
+ result.push(bgCode + colorCode + borderChars.v + reset + lineWithBg + bgCode + padding + colorCode + borderChars.v + reset);
1228
+ }
1229
+ result.push(bottom);
1230
+ if (dropShadow) {
1231
+ const shadowBlock = "\x1B[90m▒\x1B[0m";
1232
+ for (let i = 1; i < result.length; i++) result[i] += shadowBlock;
1233
+ const bottomShadow = " " + shadowBlock.repeat(width + 2);
1234
+ result.push(bottomShadow);
1235
+ }
1236
+ return result;
1237
+ }
1238
+ function getBorderChars(style) {
1239
+ if (style === "double") return {
1240
+ tl: "╔",
1241
+ tr: "╗",
1242
+ bl: "╚",
1243
+ br: "╝",
1244
+ h: "═",
1245
+ v: "║"
1246
+ };
1247
+ if (style === "rounded") return {
1248
+ tl: "╭",
1249
+ tr: "╮",
1250
+ bl: "╰",
1251
+ br: "╯",
1252
+ h: "─",
1253
+ v: "│"
1254
+ };
1255
+ return {
1256
+ tl: "┌",
1257
+ tr: "┐",
1258
+ bl: "└",
1259
+ br: "┘",
1260
+ h: "─",
1261
+ v: "│"
1262
+ };
1263
+ }
1264
+ const keyHandlers = /* @__PURE__ */ new Set();
1265
+ function onKey(handler) {
1266
+ keyHandlers.add(handler);
1267
+ return () => keyHandlers.delete(handler);
1268
+ }
1269
+ function handleInput(key) {
1270
+ if (key === "") {
1271
+ process.stdout.write("\x1B[?25h");
1272
+ process.exit();
1273
+ }
1274
+ if (key === " ") {
1275
+ focusNext();
1276
+ return;
1277
+ }
1278
+ if (key === "\x1B[Z") {
1279
+ focusPrev();
1280
+ return;
1281
+ }
1282
+ for (const handler of keyHandlers) handler(key);
1283
+ }
1284
+ function renderTerminal(app, options = {}) {
1285
+ rootNode = {
1286
+ type: "root",
1287
+ props: {},
1288
+ children: []
1289
+ };
1290
+ const container = rootNode;
1291
+ if (process.stdin.isTTY) {
1292
+ process.stdin.setRawMode(true);
1293
+ process.stdin.resume();
1294
+ process.stdin.setEncoding("utf8");
1295
+ process.stdin.on("data", handleInput);
1296
+ }
1297
+ if (options.clearConsole) process.stdout.write("\x1B[2J\x1B[3J\x1B[H");
1298
+ process.stdout.write("\x1B[?25l");
1299
+ render(app, container);
1300
+ flushRender();
1301
+ return { unmount: () => {
1302
+ render(null, container);
1303
+ process.stdout.write("\x1B[?25h");
1304
+ if (process.stdin.isTTY) {
1305
+ process.stdin.setRawMode(false);
1306
+ process.stdin.pause();
1307
+ process.stdin.off("data", handleInput);
1308
+ }
1309
+ } };
1310
+ }
1311
+ /**
1312
+ * Mount function for Terminal environments.
1313
+ * Use this with defineApp().mount() to render to the terminal.
1314
+ *
1315
+ * @example
1316
+ * ```tsx
1317
+ * import { defineApp } from '@sigx/runtime-core';
1318
+ * import { terminalMount } from '@sigx/runtime-terminal';
1319
+ *
1320
+ * const app = defineApp(<Counter />);
1321
+ * app.use(loggingPlugin)
1322
+ * .mount({ clearConsole: true }, terminalMount);
1323
+ * ```
1324
+ */
1325
+ const terminalMount = (component, options, appContext) => {
1326
+ rootNode = {
1327
+ type: "root",
1328
+ props: {},
1329
+ children: []
1330
+ };
1331
+ const container = rootNode;
1332
+ if (process.stdin.isTTY) {
1333
+ process.stdin.setRawMode(true);
1334
+ process.stdin.resume();
1335
+ process.stdin.setEncoding("utf8");
1336
+ process.stdin.on("data", handleInput);
1337
+ }
1338
+ if (options?.clearConsole) process.stdout.write("\x1B[2J\x1B[3J\x1B[H");
1339
+ process.stdout.write("\x1B[?25l");
1340
+ render(component, container, appContext);
1341
+ flushRender();
1342
+ return () => {
1343
+ render(null, container);
1344
+ process.stdout.write("\x1B[?25h");
1345
+ if (process.stdin.isTTY) {
1346
+ process.stdin.setRawMode(false);
1347
+ process.stdin.pause();
1348
+ process.stdin.off("data", handleInput);
1349
+ }
1350
+ };
1351
+ };
1352
+ setDefaultMount(terminalMount);
1353
+
1354
+ //#endregion
1355
+ export { Button, Checkbox, Input, ProgressBar, createApp, focus, focusNext, focusPrev, focusState, onKey, registerFocusable, render, renderNodeToLines, renderTerminal, terminalMount, unregisterFocusable };
1356
+ //# sourceMappingURL=index.js.map