@nmakarov/cli-toolkit 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/screen.js ADDED
@@ -0,0 +1,1007 @@
1
+ // src/screen/screens.ts
2
+ import { useState as useState2, createElement as h3 } from "react";
3
+ import { render, useInput, Text as Text3 } from "ink";
4
+
5
+ // src/screen/components.ts
6
+ import { createElement as h } from "react";
7
+ import { Box, Text } from "ink";
8
+ function getScreenWidth(maxWidth = null) {
9
+ const terminalWidth = process.stdout.columns || 80;
10
+ const availableWidth = Math.max(20, terminalWidth - 4);
11
+ return maxWidth ? Math.min(availableWidth, maxWidth) : availableWidth;
12
+ }
13
+ function ScreenContainer({ children }) {
14
+ const width = getScreenWidth();
15
+ return h(Box, {
16
+ flexDirection: "column",
17
+ marginTop: 1,
18
+ borderStyle: "single",
19
+ borderColor: "cyan",
20
+ paddingX: 1,
21
+ width
22
+ // Use the calculated width directly
23
+ }, children);
24
+ }
25
+ function ScreenRow({ children }) {
26
+ return h(Box, { flexDirection: "column" }, children);
27
+ }
28
+ function ScreenTitle({ text }) {
29
+ return h(
30
+ ScreenRow,
31
+ {},
32
+ h(Text, { bold: true, color: "cyan" }, text)
33
+ );
34
+ }
35
+ function ScreenDivider({ width }) {
36
+ const dividerWidth = width || getScreenWidth() - 4;
37
+ return h(Text, { color: "cyan", dimColor: true }, "\u2500".repeat(dividerWidth));
38
+ }
39
+ function ScreenBody({ children, alignItems = "flex-start" }) {
40
+ return h(Box, { flexDirection: "column", alignItems }, children);
41
+ }
42
+ function ScreenFooter({ lines, textStyle }) {
43
+ const defaultTextStyle = {
44
+ dimColor: true,
45
+ color: "white"
46
+ };
47
+ const finalTextStyle = { ...defaultTextStyle, ...textStyle };
48
+ const flattenAndWrap = (items, keyPrefix = "") => {
49
+ const result = [];
50
+ let keyIndex = 0;
51
+ items.forEach((item, index) => {
52
+ if (Array.isArray(item)) {
53
+ const nested = flattenAndWrap(item, `${keyPrefix}-${index}`);
54
+ result.push(...nested);
55
+ } else if (typeof item === "string") {
56
+ result.push(
57
+ h(Text, { key: `${keyPrefix}-${keyIndex++}`, ...finalTextStyle }, item)
58
+ );
59
+ } else {
60
+ const element = item;
61
+ if (element.key === null || element.key === void 0) {
62
+ result.push(
63
+ h(Text, { key: `${keyPrefix}-${keyIndex++}`, ...finalTextStyle }, element)
64
+ );
65
+ } else {
66
+ result.push(element);
67
+ }
68
+ }
69
+ });
70
+ return result;
71
+ };
72
+ const wrappedItems = flattenAndWrap(lines);
73
+ return h(
74
+ Box,
75
+ { flexDirection: "column" },
76
+ h(Box, { flexDirection: "row" }, ...wrappedItems)
77
+ );
78
+ }
79
+
80
+ // src/screen/list-components.ts
81
+ import React2, { useState, useEffect, useRef, createElement } from "react";
82
+ import { Box as Box2, Text as Text2 } from "ink";
83
+ var h2 = createElement;
84
+ function MultiColumnListComponent({ items, ctx, selectedIndexRef }) {
85
+ const [, forceUpdate] = useState({});
86
+ const termWidth = (process.stdout.columns || 80) - 8;
87
+ const maxItemLength = Math.max(...items.map((w) => w.length));
88
+ const columnWidth = maxItemLength + 3;
89
+ const columns = Math.max(1, Math.floor(termWidth / columnWidth));
90
+ const itemsPerColumn = Math.ceil(items.length / columns);
91
+ useEffect(() => {
92
+ ctx.setAction("moveUp", () => {
93
+ selectedIndexRef.current = Math.max(0, selectedIndexRef.current - 1);
94
+ forceUpdate({});
95
+ });
96
+ ctx.setAction("moveDown", () => {
97
+ selectedIndexRef.current = Math.min(items.length - 1, selectedIndexRef.current + 1);
98
+ forceUpdate({});
99
+ });
100
+ ctx.setAction("moveLeft", () => {
101
+ if (selectedIndexRef.current === 0) {
102
+ ctx.goBack();
103
+ } else {
104
+ selectedIndexRef.current = Math.max(0, selectedIndexRef.current - itemsPerColumn);
105
+ forceUpdate({});
106
+ }
107
+ });
108
+ ctx.setAction("moveRight", () => {
109
+ selectedIndexRef.current = Math.min(items.length - 1, selectedIndexRef.current + itemsPerColumn);
110
+ forceUpdate({});
111
+ });
112
+ ctx.setKeyBinding([
113
+ { key: "leftArrow", caption: "navigate", action: "moveLeft", order: 0 },
114
+ { key: "rightArrow", caption: "navigate", action: "moveRight", order: 0 },
115
+ { key: "upArrow", caption: "navigate", action: "moveUp", order: 0 },
116
+ { key: "downArrow", caption: "navigate", action: "moveDown", order: 0 }
117
+ ]);
118
+ ctx.addFooter(`Total: ${items.length} items`);
119
+ }, []);
120
+ const selectedIndex = selectedIndexRef.current;
121
+ const rows = [];
122
+ for (let row = 0; row < itemsPerColumn; row++) {
123
+ const cols = [];
124
+ for (let col = 0; col < columns; col++) {
125
+ const index = col * itemsPerColumn + row;
126
+ if (index < items.length) {
127
+ const isSelected = index === selectedIndex;
128
+ cols.push(
129
+ h2(
130
+ Box2,
131
+ { key: index, width: columnWidth },
132
+ h2(Text2, {
133
+ color: isSelected ? "black" : "white",
134
+ backgroundColor: isSelected ? "cyan" : void 0,
135
+ bold: isSelected
136
+ }, items[index].padEnd(maxItemLength))
137
+ )
138
+ );
139
+ }
140
+ }
141
+ rows.push(
142
+ h2(ScreenRow, { key: row, children: h2(Box2, { flexDirection: "row" }, ...cols) })
143
+ );
144
+ }
145
+ return h2(Box2, { flexDirection: "column" }, ...rows);
146
+ }
147
+ function MultiColumnListWithPreviewComponent({
148
+ items,
149
+ getPreviewContent,
150
+ ctx,
151
+ selectedIndexRef
152
+ }) {
153
+ const [, forceUpdate] = useState({});
154
+ const termWidth = (process.stdout.columns || 80) - 8;
155
+ const maxItemLength = Math.max(...items.map((w) => w.length));
156
+ const columnWidth = maxItemLength + 3;
157
+ const columns = Math.max(1, Math.floor(termWidth / columnWidth));
158
+ const itemsPerColumn = Math.ceil(items.length / columns);
159
+ useEffect(() => {
160
+ ctx.setAction("moveUp", () => {
161
+ selectedIndexRef.current = Math.max(0, selectedIndexRef.current - 1);
162
+ forceUpdate({});
163
+ });
164
+ ctx.setAction("moveDown", () => {
165
+ selectedIndexRef.current = Math.min(items.length - 1, selectedIndexRef.current + 1);
166
+ forceUpdate({});
167
+ });
168
+ ctx.setAction("moveLeft", () => {
169
+ if (selectedIndexRef.current === 0) {
170
+ ctx.goBack();
171
+ } else {
172
+ selectedIndexRef.current = Math.max(0, selectedIndexRef.current - itemsPerColumn);
173
+ forceUpdate({});
174
+ }
175
+ });
176
+ ctx.setAction("moveRight", () => {
177
+ selectedIndexRef.current = Math.min(items.length - 1, selectedIndexRef.current + itemsPerColumn);
178
+ forceUpdate({});
179
+ });
180
+ ctx.setKeyBinding([
181
+ { key: "leftArrow", caption: "navigate", action: "moveLeft", order: 0 },
182
+ { key: "rightArrow", caption: "navigate", action: "moveRight", order: 0 },
183
+ { key: "upArrow", caption: "navigate", action: "moveUp", order: 0 },
184
+ { key: "downArrow", caption: "navigate", action: "moveDown", order: 0 }
185
+ ]);
186
+ ctx.addFooter(`Total: ${items.length} items`);
187
+ }, []);
188
+ const selectedIndex = selectedIndexRef.current;
189
+ const selectedItem = items[selectedIndex];
190
+ const rows = [];
191
+ for (let row = 0; row < itemsPerColumn; row++) {
192
+ const cols = [];
193
+ for (let col = 0; col < columns; col++) {
194
+ const index = col * itemsPerColumn + row;
195
+ if (index < items.length) {
196
+ const isSelected = index === selectedIndex;
197
+ cols.push(
198
+ h2(
199
+ Box2,
200
+ { key: index, width: columnWidth },
201
+ h2(Text2, {
202
+ color: isSelected ? "black" : "white",
203
+ backgroundColor: isSelected ? "cyan" : void 0,
204
+ bold: isSelected
205
+ }, items[index].padEnd(maxItemLength))
206
+ )
207
+ );
208
+ }
209
+ }
210
+ rows.push(
211
+ h2(ScreenRow, { key: row, children: h2(Box2, { flexDirection: "row" }, ...cols) })
212
+ );
213
+ }
214
+ const previewContent = getPreviewContent ? getPreviewContent(selectedItem) : selectedItem;
215
+ const previewRows = [];
216
+ if (typeof previewContent === "string") {
217
+ previewRows.push(h2(ScreenRow, { key: "preview-string", children: h2(Text2, { bold: true }, previewContent) }));
218
+ } else if (typeof previewContent === "object" && !React2.isValidElement(previewContent) && previewContent !== null) {
219
+ Object.entries(previewContent).forEach(([key, value], idx) => {
220
+ previewRows.push(h2(ScreenRow, { key: `preview-${key}-${idx}`, children: h2(Text2, {}, `${key}: ${value}`) }));
221
+ });
222
+ } else if (React2.isValidElement(previewContent)) {
223
+ previewRows.push(h2(ScreenRow, { key: "preview-element", children: previewContent }));
224
+ }
225
+ return h2(
226
+ Box2,
227
+ { flexDirection: "column" },
228
+ ...rows,
229
+ h2(ScreenRow, { key: "spacer-1", children: h2(Text2, {}, " ") }),
230
+ h2(ScreenDivider, { key: "divider" }),
231
+ h2(ScreenRow, { key: "spacer-2", children: h2(Text2, {}, " ") }),
232
+ ...previewRows
233
+ );
234
+ }
235
+ function ListComponent({ items, ctx, selectedIndexRef, renderItem, getTitle, sortable = false, maxHeight, sortHighlightStyle, selectionMarker = " " }) {
236
+ const [, forceUpdate] = useState({});
237
+ const [sortOrder, setSortOrder] = useState("none");
238
+ const [scrollOffset, setScrollOffset] = useState(0);
239
+ const scrollStateRef = useRef({ scrollOffset: 0, maxHeight: 0, totalItems: 0 });
240
+ const defaultGetTitle = (item) => {
241
+ return getTitle ? getTitle(item) : typeof item.value === "string" ? item.value : item.value?.title || item.name;
242
+ };
243
+ const titleGetter = getTitle || defaultGetTitle;
244
+ const displayItems = sortable && sortOrder !== "none" ? [...items].sort((a, b) => {
245
+ const titleA = titleGetter(a).toLowerCase();
246
+ const titleB = titleGetter(b).toLowerCase();
247
+ if (sortOrder === "asc") {
248
+ return titleA < titleB ? -1 : titleA > titleB ? 1 : 0;
249
+ } else {
250
+ return titleA > titleB ? -1 : titleA < titleB ? 1 : 0;
251
+ }
252
+ }) : items;
253
+ const effectiveMaxHeight = maxHeight || displayItems.length;
254
+ const canScroll = displayItems.length > effectiveMaxHeight;
255
+ const maxScrollOffset = Math.max(0, displayItems.length - effectiveMaxHeight);
256
+ const clampedScrollOffset = Math.min(Math.max(0, scrollOffset), maxScrollOffset);
257
+ const visibleItems = displayItems.slice(clampedScrollOffset, clampedScrollOffset + effectiveMaxHeight);
258
+ const canScrollUp = clampedScrollOffset > 0;
259
+ const canScrollDown = clampedScrollOffset < maxScrollOffset;
260
+ scrollStateRef.current = { scrollOffset, maxHeight: effectiveMaxHeight, totalItems: displayItems.length };
261
+ useEffect(() => {
262
+ ctx.setAction("moveUp", () => {
263
+ const newIndex = Math.max(0, selectedIndexRef.current - 1);
264
+ selectedIndexRef.current = newIndex;
265
+ const { scrollOffset: currentScrollOffset, maxHeight: currentMaxHeight, totalItems } = scrollStateRef.current;
266
+ const currentMaxScrollOffset = Math.max(0, totalItems - currentMaxHeight);
267
+ const currentClampedScrollOffset = Math.min(Math.max(0, currentScrollOffset), currentMaxScrollOffset);
268
+ if (newIndex < currentClampedScrollOffset) {
269
+ setScrollOffset(newIndex);
270
+ }
271
+ forceUpdate({});
272
+ });
273
+ ctx.setAction("moveDown", () => {
274
+ const currentItems = sortable && sortOrder !== "none" ? [...items].sort((a, b) => {
275
+ const titleA = titleGetter(a).toLowerCase();
276
+ const titleB = titleGetter(b).toLowerCase();
277
+ if (sortOrder === "asc") {
278
+ return titleA < titleB ? -1 : titleA > titleB ? 1 : 0;
279
+ } else {
280
+ return titleA > titleB ? -1 : titleA < titleB ? 1 : 0;
281
+ }
282
+ }) : items;
283
+ const maxIndex = currentItems.length - 1;
284
+ const newIndex = Math.min(maxIndex, selectedIndexRef.current + 1);
285
+ selectedIndexRef.current = newIndex;
286
+ const { scrollOffset: currentScrollOffset, maxHeight: currentMaxHeight, totalItems } = scrollStateRef.current;
287
+ const currentMaxScrollOffset = Math.max(0, totalItems - currentMaxHeight);
288
+ const currentClampedScrollOffset = Math.min(Math.max(0, currentScrollOffset), currentMaxScrollOffset);
289
+ if (newIndex >= currentClampedScrollOffset + currentMaxHeight) {
290
+ setScrollOffset(newIndex - currentMaxHeight + 1);
291
+ }
292
+ forceUpdate({});
293
+ });
294
+ ctx.setAction("scrollUp", () => {
295
+ const { scrollOffset: currentScrollOffset, maxHeight: currentMaxHeight, totalItems } = scrollStateRef.current;
296
+ const currentMaxScrollOffset = Math.max(0, totalItems - currentMaxHeight);
297
+ const newScrollOffset = Math.max(0, currentScrollOffset - 1);
298
+ setScrollOffset(newScrollOffset);
299
+ forceUpdate({});
300
+ });
301
+ ctx.setAction("scrollDown", () => {
302
+ const { scrollOffset: currentScrollOffset, maxHeight: currentMaxHeight, totalItems } = scrollStateRef.current;
303
+ const currentMaxScrollOffset = Math.max(0, totalItems - currentMaxHeight);
304
+ const newScrollOffset = Math.min(currentMaxScrollOffset, currentScrollOffset + 1);
305
+ setScrollOffset(newScrollOffset);
306
+ forceUpdate({});
307
+ });
308
+ if (sortable) {
309
+ ctx.setAction("toggleSort", () => {
310
+ const nextSort = sortOrder === "none" ? "asc" : sortOrder === "asc" ? "desc" : "none";
311
+ const currentSelectedItem = displayItems[selectedIndexRef.current];
312
+ setSortOrder(nextSort);
313
+ const newSortedItems = nextSort !== "none" ? [...items].sort((a, b) => {
314
+ const titleA = titleGetter(a).toLowerCase();
315
+ const titleB = titleGetter(b).toLowerCase();
316
+ if (nextSort === "asc") {
317
+ return titleA < titleB ? -1 : titleA > titleB ? 1 : 0;
318
+ } else {
319
+ return titleA > titleB ? -1 : titleA < titleB ? 1 : 0;
320
+ }
321
+ }) : items;
322
+ const newIndex = newSortedItems.findIndex((item) => item === currentSelectedItem);
323
+ if (newIndex !== -1) {
324
+ selectedIndexRef.current = newIndex;
325
+ setScrollOffset(newIndex);
326
+ } else {
327
+ selectedIndexRef.current = 0;
328
+ setScrollOffset(0);
329
+ }
330
+ forceUpdate({});
331
+ });
332
+ const defaultHighlightStyle = {
333
+ color: "black",
334
+ backgroundColor: "green",
335
+ bold: true
336
+ };
337
+ const highlightStyle = { ...defaultHighlightStyle, ...sortHighlightStyle };
338
+ const sortCaption = () => {
339
+ if (sortOrder === "none") {
340
+ return h2(Text2, {}, "s to toggle sort");
341
+ } else {
342
+ const sortLabel = sortOrder === "asc" ? "ASC" : "DESC";
343
+ return h2(
344
+ Text2,
345
+ {},
346
+ "s to toggle ",
347
+ h2(Text2, { color: "white", bold: true }, "sort"),
348
+ " ",
349
+ h2(Text2, highlightStyle, ` ${sortLabel} `)
350
+ );
351
+ }
352
+ };
353
+ ctx.setKeyBinding([
354
+ { key: "upArrow", caption: "navigate", action: "moveUp", order: 0 },
355
+ { key: "downArrow", caption: "navigate", action: "moveDown", order: 0 },
356
+ {
357
+ key: "s",
358
+ caption: sortCaption,
359
+ action: "toggleSort",
360
+ order: 5
361
+ }
362
+ ]);
363
+ ctx.update();
364
+ } else {
365
+ ctx.setKeyBinding([
366
+ { key: "upArrow", caption: "navigate", action: "moveUp", order: 0 },
367
+ { key: "downArrow", caption: "navigate", action: "moveDown", order: 0 }
368
+ ]);
369
+ }
370
+ }, [sortOrder, sortable]);
371
+ const selectedIndex = selectedIndexRef.current;
372
+ const defaultRenderItem = (item, isSelected, displayIndex, actualIndex) => {
373
+ const isFirstVisible = displayIndex === 0;
374
+ const isLastVisible = displayIndex === visibleItems.length - 1;
375
+ let arrowPrefix = "";
376
+ let selectionPrefix = "";
377
+ if (isFirstVisible && canScrollUp) {
378
+ arrowPrefix = "\u2191 ";
379
+ } else if (isLastVisible && canScrollDown) {
380
+ arrowPrefix = "\u2193 ";
381
+ } else {
382
+ arrowPrefix = " ";
383
+ }
384
+ if (isSelected) {
385
+ selectionPrefix = selectionMarker;
386
+ } else {
387
+ selectionPrefix = " ".repeat(selectionMarker.length);
388
+ }
389
+ return h2(
390
+ Box2,
391
+ { flexDirection: "row" },
392
+ // Arrow (clickable if functional, not highlighted)
393
+ h2(Text2, {
394
+ key: `arrow-${actualIndex}`,
395
+ color: "white"
396
+ }, arrowPrefix),
397
+ // Selection marker space (always same width, not highlighted)
398
+ h2(Text2, { key: `marker-${actualIndex}`, color: "white" }, selectionPrefix),
399
+ // Item name (highlighted if selected)
400
+ h2(Text2, {
401
+ key: `name-${actualIndex}`,
402
+ color: isSelected ? "black" : "white",
403
+ backgroundColor: isSelected ? "cyan" : void 0,
404
+ bold: isSelected
405
+ }, item.name)
406
+ );
407
+ };
408
+ const itemRenderer = renderItem || defaultRenderItem;
409
+ return h2(
410
+ Box2,
411
+ { flexDirection: "column" },
412
+ ...visibleItems.map((item, displayIndex) => {
413
+ const actualIndex = clampedScrollOffset + displayIndex;
414
+ const isSelected = actualIndex === selectedIndex;
415
+ if (renderItem) {
416
+ const isFirstVisible = displayIndex === 0;
417
+ const isLastVisible = displayIndex === visibleItems.length - 1;
418
+ let arrowPrefix = "";
419
+ let selectionPrefix = "";
420
+ if (isFirstVisible && canScrollUp) {
421
+ arrowPrefix = "\u2191 ";
422
+ } else if (isLastVisible && canScrollDown) {
423
+ arrowPrefix = "\u2193 ";
424
+ } else {
425
+ arrowPrefix = " ";
426
+ }
427
+ if (isSelected) {
428
+ selectionPrefix = selectionMarker;
429
+ } else {
430
+ selectionPrefix = " ".repeat(selectionMarker.length);
431
+ }
432
+ return h2(ScreenRow, {
433
+ key: `item-${actualIndex}`,
434
+ children: h2(
435
+ Box2,
436
+ { flexDirection: "row" },
437
+ // Arrow (clickable if functional, not highlighted)
438
+ h2(Text2, {
439
+ key: `arrow-${actualIndex}`,
440
+ color: "white"
441
+ }, arrowPrefix),
442
+ // Selection marker space (always same width, not highlighted)
443
+ h2(Text2, { key: `marker-${actualIndex}`, color: "white" }, selectionPrefix),
444
+ // Custom rendered content
445
+ renderItem(item, isSelected, displayIndex)
446
+ )
447
+ });
448
+ } else {
449
+ return h2(ScreenRow, {
450
+ key: `item-${actualIndex}`,
451
+ children: itemRenderer(item, isSelected, displayIndex, actualIndex)
452
+ });
453
+ }
454
+ })
455
+ );
456
+ }
457
+
458
+ // src/screen/screens.ts
459
+ function groupKeyBindings(bindings) {
460
+ const groups = {};
461
+ const enabledBindings = bindings.filter((b) => b.enabled !== false);
462
+ enabledBindings.forEach((binding) => {
463
+ const caption = typeof binding.caption === "string" ? binding.caption : "";
464
+ if (!groups[caption]) {
465
+ groups[caption] = {
466
+ keys: [],
467
+ caption,
468
+ order: binding.order || 999
469
+ };
470
+ }
471
+ groups[caption].keys.push(binding.key);
472
+ });
473
+ return Object.values(groups);
474
+ }
475
+ function formatKeyBindings(bindings, mode = "long") {
476
+ const resolvedBindings = bindings.map((binding) => {
477
+ let resolvedCaption = binding.caption;
478
+ if (typeof binding.caption === "function") {
479
+ resolvedCaption = binding.caption();
480
+ }
481
+ return {
482
+ ...binding,
483
+ resolvedCaption
484
+ };
485
+ });
486
+ const groups = groupKeyBindings(resolvedBindings.map((b) => ({
487
+ ...b,
488
+ caption: typeof b.resolvedCaption === "string" ? b.resolvedCaption : ""
489
+ })));
490
+ groups.sort((a, b) => a.order - b.order);
491
+ const items = [];
492
+ groups.forEach((group) => {
493
+ const bindingWithCustom = resolvedBindings.find(
494
+ (b) => group.keys.includes(b.key) && typeof b.resolvedCaption !== "string"
495
+ );
496
+ if (bindingWithCustom && bindingWithCustom.resolvedCaption) {
497
+ items.push(bindingWithCustom.resolvedCaption);
498
+ } else {
499
+ const keyStr = formatKeys(group.keys);
500
+ if (mode === "long") {
501
+ items.push(`${keyStr} to ${group.caption}`);
502
+ } else {
503
+ items.push(keyStr);
504
+ }
505
+ }
506
+ });
507
+ return items;
508
+ }
509
+ function formatKeys(keys) {
510
+ const keyMap = {
511
+ "escape": "esc",
512
+ "leftArrow": "\u2190",
513
+ "rightArrow": "\u2192",
514
+ "upArrow": "\u2191",
515
+ "downArrow": "\u2193",
516
+ "return": "enter"
517
+ };
518
+ return keys.map((k) => keyMap[k] || k).join("/");
519
+ }
520
+ async function showScreen(config) {
521
+ const {
522
+ title,
523
+ onRender,
524
+ parentData = {}
525
+ } = config;
526
+ return new Promise((resolve) => {
527
+ let instance;
528
+ const keyBindings = [];
529
+ const actions = {};
530
+ const customFooterItems = [];
531
+ let renderResult = null;
532
+ let initialized = false;
533
+ const Screen = () => {
534
+ const [updateCounter, setUpdateCounter] = useState2(0);
535
+ if (!initialized) {
536
+ const defaultBindings = [
537
+ { key: "escape", caption: "go back", action: "back", protected: true, order: 1 },
538
+ { key: "leftArrow", caption: "go back", action: "back", protected: false, order: 1 }
539
+ // Note: 'select' is not a default - components add it if needed
540
+ ];
541
+ defaultBindings.forEach((binding) => {
542
+ keyBindings.push(binding);
543
+ });
544
+ actions.back = () => {
545
+ cleanup(null);
546
+ };
547
+ initialized = true;
548
+ }
549
+ const context = {
550
+ setAction: (actionName, handlerFn) => {
551
+ actions[actionName] = handlerFn;
552
+ },
553
+ setKeyBinding: (bindingOrBindings) => {
554
+ const bindingsToSet = Array.isArray(bindingOrBindings) ? bindingOrBindings : [bindingOrBindings];
555
+ bindingsToSet.forEach((binding) => {
556
+ const existingIndex = keyBindings.findIndex((b) => b.key === binding.key);
557
+ if (existingIndex >= 0) {
558
+ const existing = keyBindings[existingIndex];
559
+ if (existing.protected) {
560
+ console.warn(`Cannot override protected key: ${binding.key}`);
561
+ return;
562
+ }
563
+ keyBindings[existingIndex] = {
564
+ ...existing,
565
+ ...binding,
566
+ order: binding.order !== void 0 ? binding.order : existing.order,
567
+ enabled: binding.enabled !== void 0 ? binding.enabled : existing.enabled !== void 0 ? existing.enabled : true
568
+ };
569
+ } else {
570
+ keyBindings.push({
571
+ protected: false,
572
+ order: 999,
573
+ enabled: true,
574
+ ...binding
575
+ });
576
+ }
577
+ });
578
+ },
579
+ updateKeyBinding: (keyName, updates) => {
580
+ const index = keyBindings.findIndex((b) => b.key === keyName);
581
+ if (index >= 0) {
582
+ keyBindings[index] = {
583
+ ...keyBindings[index],
584
+ ...updates
585
+ };
586
+ }
587
+ },
588
+ removeKeyBinding: (keyName) => {
589
+ const index = keyBindings.findIndex((b) => b.key === keyName);
590
+ if (index >= 0) {
591
+ if (keyBindings[index].protected) {
592
+ console.warn(`Cannot remove protected key: ${keyName}`);
593
+ return;
594
+ }
595
+ keyBindings.splice(index, 1);
596
+ }
597
+ },
598
+ addFooter: (item) => {
599
+ customFooterItems.push(item);
600
+ },
601
+ clearFooter: () => {
602
+ customFooterItems.length = 0;
603
+ },
604
+ setFooter: (items) => {
605
+ customFooterItems.length = 0;
606
+ const itemsArray = Array.isArray(items) ? items : [items];
607
+ customFooterItems.push(...itemsArray);
608
+ },
609
+ update: () => {
610
+ setUpdateCounter((c) => c + 1);
611
+ },
612
+ goBack: () => {
613
+ if (actions.back) {
614
+ actions.back();
615
+ }
616
+ },
617
+ close: (result) => {
618
+ cleanup(result);
619
+ },
620
+ parentData
621
+ };
622
+ if (!renderResult) {
623
+ renderResult = onRender(context);
624
+ }
625
+ useInput((input, key) => {
626
+ if (key.ctrl && input === "c") {
627
+ cleanup(null);
628
+ process.exit(0);
629
+ return;
630
+ }
631
+ let matchedBinding = null;
632
+ for (const binding of keyBindings) {
633
+ let keyMatches = false;
634
+ if (key[binding.key]) {
635
+ keyMatches = true;
636
+ } else if (input === binding.key) {
637
+ keyMatches = true;
638
+ }
639
+ if (keyMatches) {
640
+ if (binding.enabled === false) {
641
+ continue;
642
+ }
643
+ if (binding.condition && !binding.condition(context)) {
644
+ continue;
645
+ }
646
+ matchedBinding = binding;
647
+ break;
648
+ }
649
+ }
650
+ if (matchedBinding && actions[matchedBinding.action]) {
651
+ const actionResult = actions[matchedBinding.action]({
652
+ input,
653
+ key,
654
+ binding: matchedBinding
655
+ });
656
+ }
657
+ });
658
+ const footerLines = [];
659
+ const bindingItems = formatKeyBindings(keyBindings, "long");
660
+ if (bindingItems.length > 0) {
661
+ const bindingsLine = [];
662
+ bindingItems.forEach((item, idx) => {
663
+ if (idx > 0) {
664
+ bindingsLine.push(", ");
665
+ }
666
+ bindingsLine.push(item);
667
+ });
668
+ const allStrings = bindingItems.every((item) => typeof item === "string");
669
+ if (allStrings) {
670
+ footerLines.push(bindingsLine.join(""));
671
+ } else {
672
+ const wrappedBindingsLine = bindingsLine.map(
673
+ (item) => typeof item === "string" ? h3(Text3, {}, item) : item
674
+ );
675
+ footerLines.push(wrappedBindingsLine);
676
+ }
677
+ }
678
+ customFooterItems.forEach((item) => {
679
+ if (typeof item === "string") {
680
+ footerLines.push(item);
681
+ } else {
682
+ footerLines.push(item);
683
+ }
684
+ });
685
+ return h3(
686
+ ScreenContainer,
687
+ {},
688
+ h3(ScreenTitle, { text: title }),
689
+ h3(ScreenDivider),
690
+ h3(ScreenRow, {}, h3(Text3, {}, " ")),
691
+ renderResult,
692
+ h3(ScreenRow, {}, h3(Text3, {}, " ")),
693
+ h3(ScreenDivider),
694
+ h3(ScreenFooter, { lines: footerLines })
695
+ );
696
+ };
697
+ const cleanup = (result) => {
698
+ if (instance) instance.unmount();
699
+ setTimeout(() => resolve(result), 50);
700
+ };
701
+ instance = render(h3(Screen));
702
+ });
703
+ }
704
+ async function showListScreen(config) {
705
+ const { title, items, onSelect, onEscape, parentData, initialSelectedIndex = 0, renderItem, getTitle, sortable, maxHeight, sortHighlightStyle, selectionMarker } = config;
706
+ return showScreen({
707
+ title,
708
+ parentData,
709
+ onRender: (ctx) => {
710
+ const selectedIndexRef = { current: initialSelectedIndex };
711
+ ctx.setAction("select", () => {
712
+ const selected = items[selectedIndexRef.current];
713
+ if (onSelect) {
714
+ const result = onSelect(selected.value, selectedIndexRef.current);
715
+ ctx.close(result);
716
+ }
717
+ });
718
+ if (onEscape) {
719
+ ctx.setAction("back", () => {
720
+ const result = onEscape(selectedIndexRef.current);
721
+ ctx.close(result);
722
+ });
723
+ }
724
+ ctx.setKeyBinding({ key: "return", caption: "select", action: "select", order: 2 });
725
+ return h3(ListComponent, { items, ctx, selectedIndexRef, renderItem, getTitle, sortable, maxHeight, sortHighlightStyle, selectionMarker });
726
+ }
727
+ });
728
+ }
729
+ async function showMultiColumnListScreen(config) {
730
+ const { title, items, onSelect, onEscape, parentData, initialSelectedIndex = 0 } = config;
731
+ return showScreen({
732
+ title,
733
+ parentData,
734
+ onRender: (ctx) => {
735
+ const selectedIndexRef = { current: initialSelectedIndex };
736
+ ctx.setAction("select", () => {
737
+ const selected = items[selectedIndexRef.current];
738
+ if (onSelect) {
739
+ const result = onSelect(selected, selectedIndexRef.current);
740
+ ctx.close(result);
741
+ }
742
+ });
743
+ if (onEscape) {
744
+ ctx.setAction("back", () => {
745
+ const result = onEscape(selectedIndexRef.current);
746
+ ctx.close(result);
747
+ });
748
+ }
749
+ ctx.setKeyBinding({ key: "return", caption: "select", action: "select", order: 2 });
750
+ return h3(MultiColumnListComponent, { items, ctx, selectedIndexRef });
751
+ }
752
+ });
753
+ }
754
+ async function showMultiColumnListWithPreviewScreen(config) {
755
+ const { title, items, getPreviewContent, onSelect, onEscape, parentData, initialSelectedIndex = 0 } = config;
756
+ return showScreen({
757
+ title,
758
+ parentData,
759
+ onRender: (ctx) => {
760
+ const selectedIndexRef = { current: initialSelectedIndex };
761
+ ctx.setAction("select", () => {
762
+ const selected = items[selectedIndexRef.current];
763
+ if (onSelect) {
764
+ const result = onSelect(selected, selectedIndexRef.current);
765
+ ctx.close(result);
766
+ }
767
+ });
768
+ if (onEscape) {
769
+ ctx.setAction("back", () => {
770
+ const result = onEscape(selectedIndexRef.current);
771
+ ctx.close(result);
772
+ });
773
+ }
774
+ ctx.setKeyBinding({ key: "return", caption: "select", action: "select", order: 2 });
775
+ return h3(MultiColumnListWithPreviewComponent, { items, getPreviewContent, ctx, selectedIndexRef });
776
+ }
777
+ });
778
+ }
779
+ var showMenuScreen = showListScreen;
780
+ var showWordGridScreen = showMultiColumnListScreen;
781
+
782
+ // src/screen/ui-elements.ts
783
+ import { createElement as h4 } from "react";
784
+ import { Box as Box4, Text as Text4 } from "ink";
785
+ function ListItem({
786
+ children,
787
+ isSelected = false,
788
+ color = "white",
789
+ backgroundColor,
790
+ bold = false,
791
+ dimColor = false
792
+ }) {
793
+ return h4(
794
+ Box4,
795
+ {},
796
+ h4(Text4, {
797
+ color: isSelected ? backgroundColor || "green" : color,
798
+ backgroundColor: isSelected ? color : backgroundColor,
799
+ bold: isSelected || bold,
800
+ dimColor: !isSelected && dimColor
801
+ }, children)
802
+ );
803
+ }
804
+ function TextBlock({
805
+ text,
806
+ color = "white",
807
+ dimmed = false,
808
+ bold = false,
809
+ maxWidth
810
+ }) {
811
+ return h4(
812
+ Box4,
813
+ {},
814
+ h4(Text4, {
815
+ color,
816
+ dimColor: dimmed,
817
+ bold
818
+ }, text)
819
+ );
820
+ }
821
+ function Divider({ character = "\u2500", width = 80 }) {
822
+ return h4(
823
+ Box4,
824
+ { marginY: 1 },
825
+ h4(Text4, { dimColor: true }, character.repeat(width))
826
+ );
827
+ }
828
+ function GridCell({
829
+ children,
830
+ width,
831
+ color = "white",
832
+ backgroundColor,
833
+ bold = false,
834
+ dimColor = false,
835
+ align = "left"
836
+ }) {
837
+ return h4(
838
+ Box4,
839
+ { width },
840
+ h4(Text4, {
841
+ color,
842
+ backgroundColor,
843
+ bold,
844
+ dimColor,
845
+ textAlign: align
846
+ }, children)
847
+ );
848
+ }
849
+ function InputField({ prompt, value, onChange, onSubmit }) {
850
+ return h4(
851
+ Box4,
852
+ { flexDirection: "column" },
853
+ h4(Text4, {}, prompt),
854
+ h4(
855
+ Box4,
856
+ { marginTop: 1 },
857
+ h4(Text4, { color: "cyan" }, " > ", value, "_")
858
+ )
859
+ );
860
+ }
861
+
862
+ // src/screen/utils.ts
863
+ function buildBreadcrumb(parts) {
864
+ if (parts.length === 0) return "";
865
+ if (parts.length === 1) return parts[0];
866
+ return parts.slice(1).map((part) => `\u2190 ${part}`).join(" ");
867
+ }
868
+ function buildDetailBreadcrumb(path, suffix = "") {
869
+ if (path.length <= 1) {
870
+ return suffix ? `\u2190 ${suffix}` : path[0] || "";
871
+ }
872
+ const breadcrumb = buildBreadcrumb(path);
873
+ return suffix ? `${breadcrumb} ${suffix}` : breadcrumb;
874
+ }
875
+
876
+ // src/screen/footer-builder.ts
877
+ function buildFooter(config = {}) {
878
+ const {
879
+ navigation = null,
880
+ actions = null,
881
+ info = null,
882
+ escape = "Esc to go back",
883
+ custom = null
884
+ } = config;
885
+ const lines = [];
886
+ const mainParts = [];
887
+ if (navigation) {
888
+ mainParts.push(navigation);
889
+ }
890
+ if (actions) {
891
+ mainParts.push(actions);
892
+ }
893
+ if (escape) {
894
+ mainParts.push(escape);
895
+ }
896
+ if (mainParts.length > 0) {
897
+ lines.push(mainParts.join(", "));
898
+ }
899
+ if (info) {
900
+ const infoLines = Array.isArray(info) ? info : [info];
901
+ lines.push(...infoLines);
902
+ }
903
+ if (custom) {
904
+ const customLines = Array.isArray(custom) ? custom : [custom];
905
+ lines.push(...customLines);
906
+ }
907
+ return lines;
908
+ }
909
+ var FooterPresets = {
910
+ /**
911
+ * Menu screen footer
912
+ */
913
+ menu: (customInfo = null) => buildFooter({
914
+ navigation: "\u2191/\u2193 to navigate",
915
+ actions: "Enter to select",
916
+ escape: "Esc to go back",
917
+ info: customInfo
918
+ }),
919
+ /**
920
+ * Word grid footer
921
+ */
922
+ wordGrid: (totalWords) => buildFooter({
923
+ navigation: "\u2191\u2193\u2190\u2192 to navigate",
924
+ actions: "Enter to select",
925
+ escape: "Esc to go back",
926
+ info: `Total: ${totalWords} words`
927
+ }),
928
+ /**
929
+ * Text input footer
930
+ */
931
+ textInput: () => buildFooter({
932
+ actions: "Type and press Enter to submit",
933
+ escape: "Esc to cancel"
934
+ }),
935
+ /**
936
+ * Info/static screen footer
937
+ */
938
+ info: () => buildFooter({
939
+ escape: "Esc to continue"
940
+ }),
941
+ /**
942
+ * Main menu footer (escape exits)
943
+ */
944
+ mainMenu: () => buildFooter({
945
+ navigation: "\u2191/\u2193 to navigate",
946
+ actions: "Enter to select",
947
+ escape: "Esc to exit"
948
+ }),
949
+ /**
950
+ * Action menu footer (for word cards, etc.)
951
+ */
952
+ actionMenu: (hasAudio = false) => {
953
+ const parts = buildFooter({
954
+ navigation: "\u2191/\u2193 to navigate",
955
+ actions: "Enter to select",
956
+ escape: "Esc to go back"
957
+ });
958
+ if (hasAudio) {
959
+ parts.push("Audio available");
960
+ }
961
+ return parts;
962
+ }
963
+ };
964
+ function organizeFooterMessages(messages) {
965
+ if (!messages || messages.length === 0) {
966
+ return ["Esc to go back"];
967
+ }
968
+ const navigation = messages.filter((m) => m.includes("\u2191") || m.includes("\u2193") || m.includes("\u2190") || m.includes("\u2192"));
969
+ const actions = messages.filter((m) => m.includes("Enter") || m.includes("select") || m.includes("submit"));
970
+ const escape = messages.filter((m) => m.includes("Esc"));
971
+ const others = messages.filter(
972
+ (m) => !navigation.includes(m) && !actions.includes(m) && !escape.includes(m)
973
+ );
974
+ const lines = [];
975
+ const mainLine = [...navigation, ...actions, ...escape].join(", ");
976
+ if (mainLine) lines.push(mainLine);
977
+ lines.push(...others);
978
+ return lines;
979
+ }
980
+ export {
981
+ Divider,
982
+ FooterPresets,
983
+ GridCell,
984
+ InputField,
985
+ ListComponent,
986
+ ListItem,
987
+ MultiColumnListComponent,
988
+ MultiColumnListWithPreviewComponent,
989
+ ScreenBody,
990
+ ScreenContainer,
991
+ ScreenDivider,
992
+ ScreenFooter,
993
+ ScreenRow,
994
+ ScreenTitle,
995
+ TextBlock,
996
+ buildBreadcrumb,
997
+ buildDetailBreadcrumb,
998
+ buildFooter,
999
+ organizeFooterMessages,
1000
+ showListScreen,
1001
+ showMenuScreen,
1002
+ showMultiColumnListScreen,
1003
+ showMultiColumnListWithPreviewScreen,
1004
+ showScreen,
1005
+ showWordGridScreen
1006
+ };
1007
+ //# sourceMappingURL=screen.js.map