@operad-io/tui 0.1.1 → 0.2.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/src/theme.ts CHANGED
@@ -5,10 +5,11 @@
5
5
  * `default-bg` (the terminal's default foreground / background).
6
6
  */
7
7
 
8
- import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from "node:fs";
8
+ import { messageOf } from "@operad-io/engine";
9
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
9
10
  import { join } from "node:path";
10
11
  import { RGBA } from "@opentui/core";
11
- import { watchDirectory } from "@operad-io/engine/platform";
12
+ import { watchDirectory, writeJsonAtomicSync } from "@operad-io/engine/platform";
12
13
  import { repeatEvery } from "@operad-io/engine";
13
14
  import { SHIPPED_THEMES, THEME_FAMILIES, shippedThemeFile } from "./themes.ts";
14
15
 
@@ -253,7 +254,7 @@ function parseThemeFile(file: string): {
253
254
  try {
254
255
  value = JSON.parse(readFileSync(file, "utf8"));
255
256
  } catch (error) {
256
- const reason = error instanceof Error ? error.message : String(error);
257
+ const reason = messageOf(error);
257
258
  throw new Error(`${file} is not valid JSON: ${reason}`);
258
259
  }
259
260
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
@@ -360,21 +361,13 @@ export function chooseSelection(options: {
360
361
  try {
361
362
  return resolveSelection(options.home, name);
362
363
  } catch (error) {
363
- const reason = error instanceof Error ? error.message : String(error);
364
+ const reason = messageOf(error);
364
365
  if (!reason.startsWith("unknown theme")) throw error;
365
366
  const where = options.flag === undefined ? ` in ${file}` : " given with --theme";
366
367
  throw new Error(`${reason}${where}`);
367
368
  }
368
369
  }
369
370
 
370
- /** The theme name for this session; see `chooseSelection`. */
371
- export function chooseTheme(options: {
372
- readonly home: string;
373
- readonly flag?: string | undefined;
374
- }): string {
375
- return chooseSelection(options).name;
376
- }
377
-
378
371
  /** The theme in force, kept up to date by `watchThemes`. */
379
372
  export interface ThemeHolder {
380
373
  current: ThemeSelection;
@@ -405,10 +398,7 @@ function saveTuiChoice(home: string, key: "theme" | "layout", value: string): vo
405
398
  const existing: Record<string, unknown> = existsSync(file)
406
399
  ? (JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>)
407
400
  : {};
408
- mkdirSync(home, { recursive: true });
409
- const temporary = `${file}.${process.pid}.tmp`;
410
- writeFileSync(temporary, `${JSON.stringify({ ...existing, [key]: value }, null, 2)}\n`);
411
- renameSync(temporary, file);
401
+ writeJsonAtomicSync(file, { ...existing, [key]: value }, { space: 2 });
412
402
  }
413
403
 
414
404
  /**
@@ -464,7 +454,7 @@ export function watchThemes(options: {
464
454
  const flag = typeof options.flag === "function" ? options.flag() : options.flag;
465
455
  next = chooseSelection({ home: options.home, flag });
466
456
  } catch (error) {
467
- const problem = error instanceof Error ? error.message : String(error);
457
+ const problem = messageOf(error);
468
458
  const changed = problem !== lastProblem;
469
459
  lastProblem = problem;
470
460
  if (always || changed) options.onChange(problem);
@@ -495,7 +485,7 @@ function readTuiConfig(file: string): TuiConfig {
495
485
  try {
496
486
  value = JSON.parse(readFileSync(file, "utf8"));
497
487
  } catch (error) {
498
- const reason = error instanceof Error ? error.message : String(error);
488
+ const reason = messageOf(error);
499
489
  throw new Error(`${file} is not valid JSON: ${reason}`);
500
490
  }
501
491
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
package/src/view/index.ts CHANGED
@@ -12,9 +12,10 @@ import {
12
12
  type CliRenderer,
13
13
  type TextChunk,
14
14
  } from "@opentui/core";
15
- import type { RowMark } from "@operad-io/engine";
15
+ import { bareId, type RowMark } from "@operad-io/engine";
16
16
  import { allowedText } from "../args.ts";
17
- import { confirmText, entryDetail, matchPositions, paletteEntries, settingText, type TuiPaletteEntry } from "../actions.ts";
17
+ import { confirmText, entryDetail, keyOf, matchPositions, paletteEntries, settingText, stopAction, type TuiPaletteEntry } from "../actions.ts";
18
+ import { commandEntries } from "../commands.ts";
18
19
  import { chunksOfLine } from "../markdown.ts";
19
20
  import {
20
21
  TUI_PALETTE,
@@ -32,13 +33,13 @@ import {
32
33
  KEY_LIST,
33
34
  ROW_INDENT,
34
35
  activeSection,
35
- bareId,
36
36
  cancelledRow,
37
37
  childProgress,
38
38
  displayChildren,
39
39
  rowDetail,
40
40
  rowName,
41
41
  activeTab,
42
+ formatElapsed,
42
43
  LIST_HEAD,
43
44
  dividerX,
44
45
  listWidth,
@@ -333,7 +334,6 @@ function listContent(
333
334
  }),
334
335
  );
335
336
  });
336
- if (tab.list.loading) chunks.push(chunk("loading more…\n", palette.weak));
337
337
  if (tab.list.error !== undefined) {
338
338
  chunks.push(chunk(fit(tab.list.error, width), palette.error));
339
339
  }
@@ -566,6 +566,8 @@ function sectionContent(
566
566
  state: TuiState,
567
567
  section: TuiSection | undefined,
568
568
  palette: TuiPalette,
569
+ now: number,
570
+ timeZone?: string | undefined,
569
571
  ): TextChunk[] {
570
572
  if (section === undefined) {
571
573
  return [chunk(state.object?.loading === true ? "loading…" : "no sections", palette.weak)];
@@ -574,12 +576,20 @@ function sectionContent(
574
576
  return [chunk(section.loading ? "loading…" : "not loaded", palette.weak)];
575
577
  }
576
578
  const viewport = sectionViewport(state);
577
- const content = sectionLayout(state, section);
578
- const tail = sectionTailLayout(state, section);
579
- const total = content.length + tail.length;
579
+ const content = sectionLayout(state, section, { now, ...(timeZone === undefined ? {} : { timeZone }) });
580
+ const tail = sectionTailLayout(state, section, { now, ...(timeZone === undefined ? {} : { timeZone }) });
581
+ const statusRows = section.status === undefined ? 0 : 1;
582
+ const total = content.length + tail.length + statusRows;
580
583
  const start = Math.min(Math.max(0, section.scroll), Math.max(0, total - 1));
581
584
  const chunks: TextChunk[] = [];
582
585
  for (let at = start; at < Math.min(start + viewport, total); at += 1) {
586
+ if (at >= content.length + tail.length) {
587
+ const status = section.status;
588
+ if (status !== undefined) {
589
+ chunks.push(chunk(`${status.text} · ${formatElapsed(now - status.since)}\n`, palette.weak));
590
+ }
591
+ continue;
592
+ }
583
593
  const line = at < content.length ? content[at] : tail[at - content.length];
584
594
  if (line === undefined) continue;
585
595
  chunks.push(...chunksOfLine(line, palette, at >= content.length), chunk("\n"));
@@ -587,7 +597,7 @@ function sectionContent(
587
597
  return chunks;
588
598
  }
589
599
 
590
- function objectContent(state: TuiState, palette: TuiPalette): StyledText {
600
+ function objectContent(state: TuiState, palette: TuiPalette, now: number, timeZone?: string | undefined): StyledText {
591
601
  const object = state.object;
592
602
  if (object === undefined) {
593
603
  // An openable cursor row is on the way; a row that names no object, or an empty list, asks.
@@ -631,9 +641,9 @@ function objectContent(state: TuiState, palette: TuiPalette): StyledText {
631
641
  chunks.push(...sectionTabs(object, palette, width));
632
642
  chunks.push(
633
643
  ...(section === undefined
634
- ? sectionContent(state, section, palette)
644
+ ? sectionContent(state, section, palette, now, timeZone)
635
645
  : [
636
- ...sectionContent(state, section, palette),
646
+ ...sectionContent(state, section, palette, now, timeZone),
637
647
  ...sectionHint(section, section.following, palette, width),
638
648
  ]),
639
649
  );
@@ -641,10 +651,17 @@ function objectContent(state: TuiState, palette: TuiPalette): StyledText {
641
651
  }
642
652
 
643
653
  function keyContent(state: TuiState, palette: TuiPalette): StyledText {
644
- const width = Math.max(...KEY_LIST.map(([key]) => displayWidth(key)));
654
+ const stop = stopAction(state);
655
+ const stopKey = stop === undefined ? undefined : keyOf(state.bindings, stop);
656
+ const groups = KEY_GROUPS.map((group) =>
657
+ group.map(([key, what]): readonly [string, string] =>
658
+ key === "a" && stopKey !== undefined && stopKey !== "a" ? [`a / ${stopKey}`, what] : [key, what],
659
+ ),
660
+ );
661
+ const width = Math.max(...groups.flat().map(([key]) => displayWidth(key)), ...KEY_LIST.map(([key]) => displayWidth(key)));
645
662
  const room = Math.max(1, overlayTextWidth(state) - 2 - width - 2);
646
663
  const lines: TextChunk[][] = [[chunk("keys\n", palette.accent, TextAttributes.BOLD)]];
647
- KEY_GROUPS.forEach((group, at) => {
664
+ groups.forEach((group, at) => {
648
665
  if (at > 0) lines.push([chunk("\n")]);
649
666
  for (const [key, what] of group) {
650
667
  const pad = " ".repeat(Math.max(0, width - displayWidth(key)));
@@ -802,6 +819,18 @@ function nameRuns(
802
819
  return runs;
803
820
  }
804
821
 
822
+ /** A note's text with the cursor bar where the next character goes. */
823
+ function withBar(text: string, cursor: number | undefined, bar: string): string {
824
+ const units = graphemes(text);
825
+ const at = Math.min(Math.max(0, Math.trunc(cursor ?? units.length)), units.length);
826
+ units.splice(at, 0, bar);
827
+ return units.join("");
828
+ }
829
+
830
+ function choiceRows(state: TuiState, reserved: number): number {
831
+ return Math.max(1, state.height - 4 - reserved);
832
+ }
833
+
805
834
  /** The palette or the note input, drawn in the box; undefined when neither is open. */
806
835
  function inputContent(state: TuiState, palette: TuiPalette): StyledText | undefined {
807
836
  const input = state.input;
@@ -831,9 +860,27 @@ function inputContent(state: TuiState, palette: TuiPalette): StyledText | undefi
831
860
  return styled(chunks);
832
861
  }
833
862
  if (input.kind === "note") {
863
+ if (input.commandMenu !== undefined) {
864
+ const entries = commandEntries(state);
865
+ const chunks: TextChunk[] = [
866
+ chunk(`${input.action} · note${input.required ? " (required)" : ""}\n`, palette.accent, TextAttributes.BOLD),
867
+ ];
868
+ entries.forEach((entry, at) => {
869
+ chunks.push(chunk(at === input.commandMenu?.cursor ? "❯ " : " ", palette.accent));
870
+ chunks.push(chunk(entry.slash, at === input.commandMenu?.cursor ? palette.accent : palette.text));
871
+ if (entry.hint !== "") chunks.push(chunk(` ${entry.hint}`, palette.weak));
872
+ if (entry.description !== "") chunks.push(chunk(` ${entry.description}`, palette.weak));
873
+ chunks.push(chunk("\n"));
874
+ });
875
+ chunks.push(chunk(`${withBar(input.text, input.cursor, bar)}\n`, palette.text));
876
+ if (input.error !== undefined) chunks.push(chunk(`${input.error}\n`, palette.error));
877
+ chunks.push(chunk("enter picks · esc cancels", palette.weak));
878
+ return styled(chunks);
879
+ }
834
880
  const chunks: TextChunk[] = [
835
881
  chunk(`${input.action} · note${input.required ? " (required)" : ""}\n`, palette.accent, TextAttributes.BOLD),
836
- chunk(`${input.text}${bar}\n`, palette.text),
882
+ chunk(`${withBar(input.text, input.cursor, bar)}\n`, palette.text),
883
+ ...(input.error === undefined ? [] : [chunk(`${input.error}\n`, palette.error)]),
837
884
  chunk("enter sends · shift-enter or ctrl-j adds a line · esc cancels", palette.weak),
838
885
  ];
839
886
  return styled(chunks);
@@ -842,14 +889,58 @@ function inputContent(state: TuiState, palette: TuiPalette): StyledText | undefi
842
889
  const chunks: TextChunk[] = [
843
890
  chunk(`${input.answer.prompt}\n`, palette.accent, TextAttributes.BOLD),
844
891
  ];
845
- input.answer.choices.forEach((choice, at) => {
892
+ const rows = choiceRows(state, 2);
893
+ const start = Math.max(
894
+ 0,
895
+ Math.min(input.cursor - Math.floor(rows / 2), input.answer.choices.length - rows),
896
+ );
897
+ input.answer.choices.slice(start, start + rows).forEach((choice, offset) => {
898
+ const at = start + offset;
899
+ const info = input.answer.choiceInfo?.[choice];
900
+ const label = info?.label ?? choice;
901
+ const colour =
902
+ info?.role === "destructive" ? palette.error : at === input.cursor ? palette.accent : palette.text;
846
903
  chunks.push(chunk(at === input.cursor ? "❯ " : " ", palette.accent));
847
- chunks.push(chunk(choice, at === input.cursor ? palette.accent : palette.text));
904
+ chunks.push(chunk(label, colour));
905
+ if (info?.hint !== undefined) chunks.push(chunk(` ${info.hint}`, palette.weak));
848
906
  chunks.push(chunk("\n"));
849
907
  });
850
908
  chunks.push(chunk("j/k or arrows move · enter answers · esc cancels", palette.weak));
851
909
  return styled(chunks);
852
910
  }
911
+ if (input.kind === "form") {
912
+ const chunks: TextChunk[] = [
913
+ chunk(`${sanitize(input.answer.prompt)}\n`, palette.accent, TextAttributes.BOLD),
914
+ ];
915
+ const question = input.answer.questions?.[input.question];
916
+ if (question !== undefined) {
917
+ if (question.header !== undefined) chunks.push(chunk(`${sanitize(question.header)}\n`, palette.weak));
918
+ chunks.push(chunk(`${sanitize(question.text)}\n`, palette.text));
919
+ if (question.url !== undefined) chunks.push(chunk(`${sanitize(question.url)}\n`, palette.accent));
920
+ if (question.code !== undefined) {
921
+ chunks.push(chunk(`${sanitize(question.code)}\n`, palette.text, TextAttributes.BOLD));
922
+ }
923
+ const choices = question.choices ?? [];
924
+ if (choices.length > 0) {
925
+ const rows = choiceRows(state, 5);
926
+ const start = Math.max(0, Math.min(input.cursor - Math.floor(rows / 2), choices.length - rows));
927
+ choices.slice(start, start + rows).forEach((choice, offset) => {
928
+ const at = start + offset;
929
+ chunks.push(chunk(at === input.cursor ? "❯ " : " ", palette.accent));
930
+ chunks.push(chunk(sanitize(choice.label), at === input.cursor ? palette.accent : palette.text));
931
+ if (choice.description !== undefined) chunks.push(chunk(` ${sanitize(choice.description)}`, palette.weak));
932
+ chunks.push(chunk("\n"));
933
+ });
934
+ chunks.push(chunk("j/k or arrows move · enter answers · esc cancels", palette.weak));
935
+ } else {
936
+ // A secret answer is masked; the value is never drawn again.
937
+ const shown = question.secret === true ? "•".repeat(graphemes(input.text).length) : input.text;
938
+ chunks.push(chunk(`${shown}${bar}\n`, palette.text));
939
+ chunks.push(chunk("enter sends · esc cancels", palette.weak));
940
+ }
941
+ }
942
+ return styled(chunks);
943
+ }
853
944
  if (input.kind === "themes") {
854
945
  const chunks: TextChunk[] = [chunk("theme\n", palette.accent)];
855
946
  const names = state.themeNames;
@@ -983,12 +1074,22 @@ function inputLines(state: TuiState): number {
983
1074
  const body = field?.kind === "pick" ? field.options.length + 1 : 2;
984
1075
  return 3 + (setting.description === undefined ? 0 : 1) + body;
985
1076
  }
986
- if (input?.kind === "note") return input.text.split("\n").length + 2;
1077
+ if (input?.kind === "note") {
1078
+ return input.text.split("\n").length + 2 + (input.error === undefined ? 0 : 1) + (input.commandMenu === undefined ? 0 : commandEntries(state).length + 1);
1079
+ }
987
1080
  if (input?.kind === "palette") {
988
1081
  const entries = paletteEntries(state);
989
1082
  return entries.length === 0 ? 3 : 2 + paletteDisplayLines(entries).length;
990
1083
  }
991
- if (input?.kind === "answer") return input.answer.choices.length + 2;
1084
+ if (input?.kind === "answer") {
1085
+ return Math.min(input.answer.choices.length, choiceRows(state, 2)) + 2;
1086
+ }
1087
+ if (input?.kind === "form") {
1088
+ const question = input.answer.questions?.[input.question];
1089
+ const choices = question?.choices?.length ?? 0;
1090
+ const shown = Math.min(choices, choiceRows(state, 5));
1091
+ return 1 + (question?.header === undefined ? 0 : 1) + 1 + (question?.url === undefined ? 0 : 1) + (question?.code === undefined ? 0 : 1) + (choices > 0 ? shown + 1 : 2);
1092
+ }
992
1093
  if (input?.kind === "themes") return Math.max(1, state.themeNames.length) + 1;
993
1094
  if (input?.kind === "pages") return Math.max(1, pageEntries(state).length) + 1;
994
1095
  return 0;
@@ -1021,6 +1122,8 @@ function footerContent(state: TuiState, palette: TuiPalette): StyledText {
1021
1122
  export function drawState(
1022
1123
  state: TuiState,
1023
1124
  themeName: string | ThemeSelection = "auto",
1125
+ now: number = Date.now(),
1126
+ timeZone?: string | undefined,
1024
1127
  ): TuiDrawing {
1025
1128
  const palette = paletteFor(state.theme, themeName);
1026
1129
  const tab = activeTab(state);
@@ -1041,7 +1144,7 @@ export function drawState(
1041
1144
  state.connection === "unreachable",
1042
1145
  palette,
1043
1146
  ),
1044
- right: objectContent(state, palette),
1147
+ right: objectContent(state, palette, now, timeZone),
1045
1148
  overlay: state.keys
1046
1149
  ? keyContent(state, palette)
1047
1150
  : (inputContent(state, palette) ?? confirmContent(state, palette)),
@@ -1058,6 +1161,8 @@ export interface TuiView {
1058
1161
  export function createTuiView(
1059
1162
  ctx: CliRenderer,
1060
1163
  theme: string | ThemeSelection | (() => ThemeSelection) = "auto",
1164
+ timeZone?: string | undefined,
1165
+ now: () => number = Date.now,
1061
1166
  ): TuiView {
1062
1167
  const root = new BoxRenderable(ctx, {
1063
1168
  id: "operad-tui",
@@ -1164,7 +1269,7 @@ export function createTuiView(
1164
1269
  const themeName = typeof theme === "function" ? theme() : theme;
1165
1270
  const palette = paletteFor(state.theme, themeName);
1166
1271
  const wide = twoPane(state);
1167
- const drawing = drawState(state, themeName);
1272
+ const drawing = drawState(state, themeName, now(), timeZone);
1168
1273
 
1169
1274
  header.content = drawing.header;
1170
1275
  headerRule.content = drawing.rule;
package/src/wrap.ts CHANGED
@@ -29,13 +29,6 @@ export function displayWidth(char: string): number {
29
29
  return Bun.stringWidth(char);
30
30
  }
31
31
 
32
- /** The columns a whole string takes. */
33
- export function textWidth(text: string): number {
34
- let width = 0;
35
- for (const char of graphemes(text)) width += displayWidth(char);
36
- return width;
37
- }
38
-
39
32
  function isSpace(char: string): boolean {
40
33
  return /^\s/u.test(char);
41
34
  }
@@ -64,7 +57,7 @@ function widthOf<T>(glyphs: readonly WrapGlyph<T>[]): number {
64
57
  }
65
58
 
66
59
  /** Cuts a word wider than a row into rows of at most `limit` columns. */
67
- function cut<T>(
60
+ function cutGlyphs<T>(
68
61
  token: readonly WrapGlyph<T>[],
69
62
  limit: number,
70
63
  ): { readonly full: WrapGlyph<T>[][]; readonly rest: WrapGlyph<T>[]; readonly used: number } {
@@ -137,7 +130,7 @@ export function wrapGlyphs<T>(
137
130
  used = 0;
138
131
  }
139
132
 
140
- const pieces = cut(token, limit);
133
+ const pieces = cutGlyphs(token, limit);
141
134
  lines.push(...pieces.full);
142
135
  line = pieces.rest;
143
136
  used = pieces.used;