@operad-io/tui 0.0.0-stage → 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.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/package.json +27 -4
  4. package/src/actions.ts +997 -0
  5. package/src/app.ts +1665 -0
  6. package/src/args.ts +198 -0
  7. package/src/autostart.ts +302 -0
  8. package/src/client.ts +478 -0
  9. package/src/discover.ts +90 -0
  10. package/src/events.ts +345 -0
  11. package/src/index.ts +11 -0
  12. package/src/layout.ts +260 -0
  13. package/src/live.ts +113 -0
  14. package/src/markdown.ts +85 -0
  15. package/src/recent.ts +40 -0
  16. package/src/sanitize.ts +18 -0
  17. package/src/state.ts +3200 -0
  18. package/src/theme.ts +525 -0
  19. package/src/themes.ts +60 -0
  20. package/src/view/index.ts +1204 -0
  21. package/src/wrap.ts +156 -0
  22. package/theme.schema.json +197 -0
  23. package/themes/LICENSE-catppuccin +21 -0
  24. package/themes/LICENSE-dracula +21 -0
  25. package/themes/LICENSE-github +21 -0
  26. package/themes/LICENSE-kanagawa +21 -0
  27. package/themes/LICENSE-nord +21 -0
  28. package/themes/LICENSE-one +20 -0
  29. package/themes/LICENSE-rose-pine +21 -0
  30. package/themes/LICENSE-solarized +20 -0
  31. package/themes/LICENSE-tokyo-night +22 -0
  32. package/themes/README.md +81 -0
  33. package/themes/catppuccin-frappe.json +19 -0
  34. package/themes/catppuccin-latte.json +19 -0
  35. package/themes/catppuccin-macchiato.json +19 -0
  36. package/themes/catppuccin-mocha.json +19 -0
  37. package/themes/dracula.json +19 -0
  38. package/themes/github-dark.json +19 -0
  39. package/themes/github-light.json +19 -0
  40. package/themes/kanagawa-dragon.json +19 -0
  41. package/themes/kanagawa-lotus.json +19 -0
  42. package/themes/kanagawa-wave.json +19 -0
  43. package/themes/nord.json +19 -0
  44. package/themes/one-dark.json +19 -0
  45. package/themes/one-light.json +19 -0
  46. package/themes/rose-pine-dawn.json +19 -0
  47. package/themes/rose-pine-main.json +19 -0
  48. package/themes/solarized-dark.json +19 -0
  49. package/themes/solarized-light.json +19 -0
  50. package/themes/tokyo-night-day.json +19 -0
  51. package/themes/tokyo-night-night.json +19 -0
  52. package/tui.schema.json +24 -0
package/src/actions.ts ADDED
@@ -0,0 +1,997 @@
1
+ /**
2
+ * The action half of the reducer: the main action, the `:` palette, bound keys,
3
+ * the note input and the confirmation. Everything here is a pure function of the
4
+ * state; the shell sends the request this code leaves in `actionRequest`.
5
+ */
6
+
7
+ import type { ViewAction, ViewRow } from "@operad-io/engine";
8
+ import { argFields, narrowField, parseArg, type ArgField } from "./args.ts";
9
+ import type { TuiSetting, TuiTypeInfo } from "./client.ts";
10
+ import { sanitize } from "./sanitize.ts";
11
+ import type { TuiAnswer, TuiBinding, TuiInput, TuiState } from "./state.ts";
12
+ import { graphemes } from "./wrap.ts";
13
+
14
+ /** The key that runs the main action when the plugin binds none to it. */
15
+ export const MAIN_KEY = "a";
16
+
17
+ /**
18
+ * Every key the TUI uses itself for navigation and control (lower case). A
19
+ * plugin default or a `keys.json` entry on one of these is dropped when the
20
+ * bindings are resolved; `handleKey` never looks a binding up for them.
21
+ */
22
+ export const RESERVED_KEYS: readonly string[] = [
23
+ "enter", "return", "escape", "esc", "tab",
24
+ "up", "down", "left", "right", "arrowup", "arrowdown", "arrowleft", "arrowright",
25
+ "pageup", "page-up", "prior", "pagedown", "page-down", "next",
26
+ "home", "end", "space", " ",
27
+ "[", "]", ":", "?", "/",
28
+ "b", "f", "g", "j", "k", "n", "p", "q", "r", "t",
29
+ "1", "2", "3", "4", "5", "6", "7", "8", "9",
30
+ ];
31
+
32
+ /** Is `key` one the TUI keeps for itself? Letters match in either case. */
33
+ export function isReserved(key: string): boolean {
34
+ const lowered = key.toLowerCase();
35
+ // handleKey ignores every Ctrl or Meta chord, so none can be bound.
36
+ return RESERVED_KEYS.includes(lowered) || CHORD.test(lowered);
37
+ }
38
+
39
+ const CHORD = /^(ctrl|control|meta|cmd|command|alt|option|opt|super)[-+].|^\^./;
40
+
41
+ /** The bindings that may run actions, and the footer line naming those dropped. */
42
+ export function resolveBindings(bindings: readonly TuiBinding[]): {
43
+ readonly bindings: readonly TuiBinding[];
44
+ readonly notice: string | undefined;
45
+ } {
46
+ const kept = bindings.filter((binding) => !isReserved(binding.key));
47
+ const dropped = bindings.filter((binding) => isReserved(binding.key));
48
+ return {
49
+ bindings: kept,
50
+ notice:
51
+ dropped.length === 0
52
+ ? undefined
53
+ : sanitize(
54
+ `reserved keys ignored: ${dropped
55
+ .map((b) => `${b.key} (${b.action}, ${b.source})`)
56
+ .join(", ")}`,
57
+ ),
58
+ };
59
+ }
60
+
61
+ /** The palette's fixed groups, in the order they are shown before a type's own group. */
62
+ export const PALETTE_GROUPS = ["actions", "tui", "settings"] as const;
63
+ /** A group label: one of the fixed ones, or a type's title for an object under settings. */
64
+ export type TuiPaletteGroup = string;
65
+
66
+ /** One line of the palette. */
67
+ export interface TuiPaletteEntry {
68
+ /** The grouping key; two types never share one, even with the same title. */
69
+ readonly group: TuiPaletteGroup;
70
+ /** The group label a person reads, when it differs from the key. */
71
+ readonly groupTitle?: string | undefined;
72
+ /** `<plugin>:<action>` for an action; the command's words for the TUI. */
73
+ readonly name: string;
74
+ /** One line that says what the entry does; search reads it too. */
75
+ readonly title: string;
76
+ /** Set on a TUI command: what the reducer runs. */
77
+ readonly command?: TuiCommand | undefined;
78
+ readonly key: string | undefined;
79
+ readonly needsNote: boolean;
80
+ readonly confirm: boolean;
81
+ /** Set on a settings entry: the setting it opens. */
82
+ readonly setting?: TuiSetting | undefined;
83
+ /** Set when the query carries a value for the action's first argument. */
84
+ readonly typed?: { readonly value: unknown } | undefined;
85
+ /** Set when that value does not fit: the values the argument allows. */
86
+ readonly refusal?: string | undefined;
87
+ }
88
+
89
+ /** The key that should reach `bindings`: a shifted letter is upper case. */
90
+ export function keyLabel(key: string, shift: boolean): string {
91
+ return shift && /^[a-z]$/i.test(key) ? key.toUpperCase() : key;
92
+ }
93
+
94
+ /** The binding for a key; a user binding beats a plugin default. */
95
+ export function bindingFor(
96
+ bindings: readonly TuiBinding[],
97
+ key: string,
98
+ source?: "plugin" | "user",
99
+ ): TuiBinding | undefined {
100
+ const found = bindings.filter(
101
+ (binding) => binding.key === key && (source === undefined || binding.source === source),
102
+ );
103
+ return found.find((binding) => binding.source === "user") ?? found[0];
104
+ }
105
+
106
+ /** The key bound to an action, a user binding first. */
107
+ export function keyOf(
108
+ bindings: readonly TuiBinding[],
109
+ action: ViewAction,
110
+ ): string | undefined {
111
+ const mine = bindings.filter((binding) => binding.action === action.name);
112
+ // A key is only the action's key when it still resolves to it.
113
+ const live = mine.filter((binding) => bindingFor(bindings, binding.key)?.action === action.name);
114
+ return (
115
+ live.find((binding) => binding.source === "user")?.key ??
116
+ live[0]?.key
117
+ );
118
+ }
119
+
120
+ function bareId(id: string): string {
121
+ const at = id.indexOf(":");
122
+ return at < 0 ? id : id.slice(at + 1);
123
+ }
124
+
125
+ /**
126
+ * The actions a page lists: those that do not create an object of another type.
127
+ * A creating action belongs to that type's tab (`c` on the chat tab), not to the
128
+ * parent's page.
129
+ */
130
+ export function pageActions(actions: readonly ViewAction[]): readonly ViewAction[] {
131
+ return actions.filter((action) => action.creates === undefined);
132
+ }
133
+
134
+ /** The first available action, the one the footer offers. */
135
+ export function mainAction(state: TuiState): ViewAction | undefined {
136
+ // An action that ends the object is never the main one, even when it is alone.
137
+ return pageActions(state.object?.actions ?? []).find((action) => action.ends !== true);
138
+ }
139
+
140
+ /** The key the footer shows for the main action. */
141
+ export function mainKey(state: TuiState): string | undefined {
142
+ const main = mainAction(state);
143
+ const own = main === undefined ? undefined : keyOf(state.bindings, main);
144
+ if (own !== undefined) return own;
145
+ // `a` runs the main action only while no binding claims it.
146
+ return bindingFor(state.bindings, MAIN_KEY) === undefined ? MAIN_KEY : undefined;
147
+ }
148
+
149
+ /** The characters after which a letter starts a word. */
150
+ const WORD_BREAKS = ":-. /";
151
+
152
+ const HIT = 1;
153
+ const RUN = 4;
154
+ const WORD_START = 10;
155
+
156
+ /** The best way `word` is a subsequence of `text`: its score (higher is better) and where it matched. */
157
+ function matchWord(
158
+ word: readonly string[],
159
+ text: readonly string[],
160
+ ): { readonly score: number; readonly at: readonly number[] } | undefined {
161
+ const n = text.length;
162
+ const m = word.length;
163
+ if (m === 0) return { score: 0, at: [] };
164
+ if (m > n) return undefined;
165
+ const start = (i: number): boolean => i === 0 || WORD_BREAKS.includes(text[i - 1] ?? "");
166
+ // best[j][i]: the best score with word[j] matched at text[i]; from[j][i] is the previous index.
167
+ const best: number[][] = [];
168
+ const from: number[][] = [];
169
+ for (let j = 0; j < m; j++) {
170
+ const row: number[] = new Array<number>(n).fill(-1);
171
+ const back: number[] = new Array<number>(n).fill(-1);
172
+ for (let i = j; i < n; i++) {
173
+ if (text[i] !== word[j]) continue;
174
+ const own = HIT + (start(i) ? WORD_START : 0);
175
+ if (j === 0) {
176
+ row[i] = own;
177
+ continue;
178
+ }
179
+ const previous = best[j - 1] ?? [];
180
+ let top = -1;
181
+ let topAt = -1;
182
+ for (let k = j - 1; k < i; k++) {
183
+ const base = previous[k] ?? -1;
184
+ if (base < 0) continue;
185
+ const value = base + (k === i - 1 ? RUN : 0);
186
+ if (value > top) {
187
+ top = value;
188
+ topAt = k;
189
+ }
190
+ }
191
+ if (topAt >= 0) {
192
+ row[i] = top + own;
193
+ back[i] = topAt;
194
+ }
195
+ }
196
+ best.push(row);
197
+ from.push(back);
198
+ }
199
+ const last = best[m - 1] ?? [];
200
+ let end = -1;
201
+ for (let i = 0; i < n; i++) {
202
+ // An earlier end wins a tie, so the match sits near the start.
203
+ if ((last[i] ?? -1) > (last[end] ?? -1)) end = i;
204
+ }
205
+ if (end < 0) return undefined;
206
+ const at: number[] = [];
207
+ for (let j = m - 1, i = end; j >= 0; j--) {
208
+ at.unshift(i);
209
+ i = from[j]?.[i] ?? -1;
210
+ }
211
+ return { score: last[end] ?? 0, at };
212
+ }
213
+
214
+ function unitsOf(text: string): string[] {
215
+ return graphemes(text.toLowerCase());
216
+ }
217
+
218
+ function wordsOf(query: string): string[][] {
219
+ return query
220
+ .split(/\s+/)
221
+ .filter((word) => word !== "")
222
+ .map(unitsOf);
223
+ }
224
+
225
+ /** Above any word score, so a match never goes negative (-1 means no match). */
226
+ const FUZZY_BASE = 100000;
227
+
228
+ /**
229
+ * Does `query` match `name`? A space in the query separates words that may
230
+ * match in any order; each word is a subsequence, best where it starts a word.
231
+ * Lower is better; -1 is no match.
232
+ */
233
+ export function fuzzyScore(query: string, name: string): number {
234
+ const words = wordsOf(query);
235
+ if (words.length === 0) return 0;
236
+ const text = unitsOf(name);
237
+ let total = 0;
238
+ for (const word of words) {
239
+ const found = matchWord(word, text);
240
+ if (found === undefined) return -1;
241
+ total += found.score;
242
+ }
243
+ return Math.max(0, FUZZY_BASE - total * 10) + text.length;
244
+ }
245
+
246
+ /** What a palette entry is called in the list of recent entries. */
247
+ export function entryId(entry: Pick<TuiPaletteEntry, "group" | "name">): string {
248
+ return `${entry.group}/${entry.name}`;
249
+ }
250
+
251
+ /** How many entries the palette remembers as the last used. */
252
+ export const RECENT_ENTRIES = 5;
253
+
254
+ /** The matches of one entry: its rank (higher first) and the characters of its name that matched. */
255
+ function matchEntry(
256
+ words: readonly (readonly string[])[],
257
+ entry: TuiPaletteEntry,
258
+ ): { readonly score: number; readonly name: readonly number[] } | undefined {
259
+ const fields = [
260
+ { units: unitsOf(entry.name), bonus: 2000, name: true },
261
+ { units: unitsOf(entry.groupTitle ?? entry.group), bonus: 1000, name: false },
262
+ { units: unitsOf(entry.title), bonus: 0, name: false },
263
+ ];
264
+ let score = 0;
265
+ const marked = new Set<number>();
266
+ for (const word of words) {
267
+ let top: { score: number; at: readonly number[]; name: boolean } | undefined;
268
+ for (const field of fields) {
269
+ const found = matchWord(word, field.units);
270
+ if (found === undefined) continue;
271
+ const value = found.score + field.bonus;
272
+ if (top === undefined || value > top.score) top = { score: value, at: found.at, name: field.name };
273
+ }
274
+ if (top === undefined) return undefined;
275
+ score += top.score;
276
+ if (top.name) for (const index of top.at) marked.add(index);
277
+ }
278
+ return { score, name: [...marked].sort((a, b) => a - b) };
279
+ }
280
+
281
+ /** The positions (grapheme indexes) in an entry's name that `query` matched. */
282
+ export function matchPositions(query: string, entry: TuiPaletteEntry): readonly number[] {
283
+ return matchEntry(wordsOf(query), entry)?.name ?? [];
284
+ }
285
+
286
+ /** What a TUI command does; each is what a key does. */
287
+ export type TuiCommand =
288
+ | { readonly kind: "help" | "refresh" | "back" | "quit" | "themes" }
289
+ | { readonly kind: "go"; readonly tabId: string }
290
+ | { readonly kind: "open"; readonly type: string; readonly id: string }
291
+ | { readonly kind: "create"; readonly parent: string; readonly type: string };
292
+
293
+ /** The objects a new `type` can be made under: every loaded row, or group, of a type that creating it works on. */
294
+ export function creationParents(
295
+ state: TuiState,
296
+ type: string,
297
+ parents: readonly string[],
298
+ ): readonly string[] {
299
+ const ids = new Set<string>();
300
+ const rows = [
301
+ ...state.tabs.flatMap((tab) => tab.list.rows),
302
+ ...(state.settingsTab?.list.rows ?? []),
303
+ ];
304
+ for (const row of rows) {
305
+ for (const candidate of [row, row.group]) {
306
+ if (candidate?.type === undefined || !parents.includes(candidate.type)) continue;
307
+ ids.add(candidate.id.includes(":") ? candidate.id : `${candidate.type}:${candidate.id}`);
308
+ }
309
+ }
310
+ return [...ids];
311
+ }
312
+
313
+ /** The scopes the palette lists settings of: global, and the open object's repository. */
314
+ export function settingScopes(state: TuiState): readonly string[] {
315
+ const object = state.object;
316
+ if (object === undefined) return ["global"];
317
+ const bare = object.id.slice(object.id.indexOf(":") + 1);
318
+ // A repository's own page is named by the repository; other objects carry it before the last slash.
319
+ if (object.type === "repo") return ["global", bare];
320
+ const slash = bare.lastIndexOf("/");
321
+ return slash < 0 ? ["global"] : ["global", bare.slice(0, slash)];
322
+ }
323
+
324
+ /** A value as the person reads it: text as it is, anything else as JSON. */
325
+ export function settingText(value: unknown): string {
326
+ if (value === undefined) return "none";
327
+ return sanitize(typeof value === "string" ? value : (JSON.stringify(value) ?? "none"));
328
+ }
329
+
330
+ /** The name a type shows in a client: its title, or the type name when it has none. */
331
+ function typeTitle(info: TuiTypeInfo): string {
332
+ return info.title.length === 0 ? info.type : info.title;
333
+ }
334
+
335
+ function settingEntries(state: TuiState): readonly TuiPaletteEntry[] {
336
+ return state.settings.map((setting) => ({
337
+ group: "settings",
338
+ name: sanitize(setting.name),
339
+ title: sanitize(setting.description ?? ""),
340
+ key: undefined,
341
+ needsNote: false,
342
+ confirm: setting.confirm,
343
+ setting,
344
+ }));
345
+ }
346
+
347
+ /**
348
+ * The objects a plugin put under settings, one palette group per type, named
349
+ * after the type. Enter opens the object's page.
350
+ */
351
+ function settingsObjectEntries(state: TuiState): readonly TuiPaletteEntry[] {
352
+ const tab = state.settingsTab;
353
+ if (tab === undefined) return [];
354
+ const entries: TuiPaletteEntry[] = [];
355
+ for (const info of tab.types ?? []) {
356
+ const group = typeTitle(info);
357
+ for (const row of tab.list.rows) {
358
+ if (row.type !== info.type) continue;
359
+ entries.push({
360
+ group: `settings-object-${info.type}`,
361
+ groupTitle: group,
362
+ name: sanitize(row.title === "" ? row.id : row.title),
363
+ title: sanitize(row.id),
364
+ key: undefined,
365
+ needsNote: false,
366
+ confirm: false,
367
+ command: { kind: "open", type: info.type, id: row.id },
368
+ });
369
+ }
370
+ }
371
+ return entries;
372
+ }
373
+
374
+ /** The group labels in drawing order: the fixed ones, then each settings type. */
375
+ function paletteGroups(state: TuiState): readonly string[] {
376
+ const groups: string[] = [...PALETTE_GROUPS];
377
+ for (const info of state.settingsTab?.types ?? []) {
378
+ const key = `settings-object-${info.type}`;
379
+ if (!groups.includes(key)) groups.push(key);
380
+ }
381
+ return groups;
382
+ }
383
+
384
+ /** The field a setting's value prompt asks: a list for an enum or a boolean, else text. */
385
+ export function settingField(setting: TuiSetting): ArgField {
386
+ const name = sanitize(setting.name);
387
+ const description = setting.description === undefined ? undefined : sanitize(setting.description);
388
+ const shown = settingText(setting.value);
389
+ const pick = (options: ArgField["options"]): ArgField => ({
390
+ name,
391
+ kind: "pick",
392
+ integer: false,
393
+ options,
394
+ description,
395
+ current: options.findIndex((o) => o.value === setting.value) >= 0
396
+ ? options.findIndex((o) => o.value === setting.value)
397
+ : undefined,
398
+ initial: "",
399
+ });
400
+ if (setting.enum !== undefined && setting.enum.length > 0) {
401
+ return pick(setting.enum.map((value) => ({ value, label: sanitize(String(value)) })));
402
+ }
403
+ if (setting.type === "boolean" || typeof setting.value === "boolean" || typeof setting.default === "boolean") {
404
+ return pick([
405
+ { value: true, label: "yes" },
406
+ { value: false, label: "no" },
407
+ ]);
408
+ }
409
+ return {
410
+ name,
411
+ kind: "text",
412
+ integer: false,
413
+ options: [],
414
+ description,
415
+ initial: setting.value === undefined ? "" : shown,
416
+ };
417
+ }
418
+
419
+ /** What the server is sent for typed text: the text for a string setting, else JSON when it reads as JSON, else the text; the server checks it. */
420
+ export function settingValue(text: string, type?: string | undefined): unknown {
421
+ if (type === "string") return text;
422
+ try {
423
+ return JSON.parse(text);
424
+ } catch {
425
+ return text;
426
+ }
427
+ }
428
+
429
+ function commandEntries(state: TuiState): readonly TuiPaletteEntry[] {
430
+ const make = (
431
+ name: string,
432
+ title: string,
433
+ key: string | undefined,
434
+ command: TuiCommand,
435
+ ): TuiPaletteEntry => ({
436
+ group: "tui",
437
+ name,
438
+ title,
439
+ key,
440
+ needsNote: false,
441
+ confirm: false,
442
+ command,
443
+ });
444
+ const tabs = state.tabs.map((tab, at) => ({ tab, key: at < 9 ? String(at + 1) : undefined }));
445
+ const go = (kind: "pending" | "running"): TuiPaletteEntry | undefined => {
446
+ const found = tabs.find((item) => item.tab.kind === kind);
447
+ return found === undefined
448
+ ? undefined
449
+ : make(`go to ${kind}`, `show the ${kind} list`, found.key, { kind: "go", tabId: found.tab.id });
450
+ };
451
+ const types = tabs
452
+ .filter((item) => item.tab.kind === "plugin")
453
+ .map((item) =>
454
+ make(`go to ${item.tab.title}`, `show the list of ${item.tab.title}`, item.key, {
455
+ kind: "go",
456
+ tabId: item.tab.id,
457
+ }),
458
+ );
459
+ // A creating action is offered from its type's own tab only, never on a parent's page.
460
+ const here = state.tabs[state.active];
461
+ const creating = (here?.kind === "plugin" ? (here.types ?? []) : [])
462
+ .filter((info) => state.object === undefined || !(info.parents ?? []).includes(state.object.type))
463
+ .flatMap((info) =>
464
+ creationParents(state, info.type, info.parents ?? []).map((parent) =>
465
+ make(`new ${info.type}`, `start a new ${info.type} in ${parent}`, undefined, {
466
+ kind: "create",
467
+ parent,
468
+ type: info.type,
469
+ }),
470
+ ),
471
+ );
472
+ return [
473
+ make("help", "show or hide the key list", "?", { kind: "help" }),
474
+ ...creating,
475
+ make("refresh", "load the lists again", "r", { kind: "refresh" }),
476
+ ...[go("pending"), go("running")].filter((entry): entry is TuiPaletteEntry => entry !== undefined),
477
+ ...types,
478
+ make("theme", "choose the colour theme", undefined, { kind: "themes" }),
479
+ make("go back", "close the open object", "escape", { kind: "back" }),
480
+ make("quit", "leave the TUI", "q", { kind: "quit" }),
481
+ ];
482
+ }
483
+
484
+ /** The palette's lines for the typed query: groups in order, best match first inside one. */
485
+ export function paletteEntries(state: TuiState): readonly TuiPaletteEntry[] {
486
+ const object = state.object;
487
+ const query = state.input?.kind === "palette" ? state.input.query : "";
488
+ const raw = query.trim().split(/\s+/);
489
+ const actions: readonly TuiPaletteEntry[] =
490
+ object === undefined
491
+ ? []
492
+ : pageActions(object.actions).map((action) => ({
493
+ group: "actions",
494
+ name: action.name,
495
+ title: `${action.name} on ${bareId(object.id)}`,
496
+ key: keyOf(state.bindings, action),
497
+ needsNote: action.note !== undefined,
498
+ confirm: action.confirm,
499
+ ...typedValue(action, object.row, raw),
500
+ }));
501
+ const words = wordsOf(query);
502
+ const rank = (entries: readonly TuiPaletteEntry[]): readonly TuiPaletteEntry[] =>
503
+ entries
504
+ .map((entry, order) => {
505
+ // Words after the action's name are its first argument, not part of the search.
506
+ const hasValue = entry.typed !== undefined || entry.refusal !== undefined;
507
+ const search = hasValue ? words.slice(0, 1) : words;
508
+ return { entry, order, found: matchEntry(search, entry) };
509
+ })
510
+ .filter((item) => item.found !== undefined)
511
+ // Equal scores keep the order the entries were listed in.
512
+ .sort((a, b) => (b.found?.score ?? 0) - (a.found?.score ?? 0) || a.order - b.order)
513
+ .map((item) => item.entry);
514
+ const all = [
515
+ ...rank(actions),
516
+ ...rank(commandEntries(state)),
517
+ ...rank(settingEntries(state)),
518
+ ...rank(settingsObjectEntries(state)),
519
+ ];
520
+ const ordered =
521
+ words.length > 0
522
+ ? all
523
+ : (() => {
524
+ // With no query the last used entries lead, the latest first.
525
+ const used = state.recent
526
+ .map((id) => all.find((entry) => entryId(entry) === id))
527
+ .filter((entry): entry is TuiPaletteEntry => entry !== undefined)
528
+ .slice(0, RECENT_ENTRIES);
529
+ return [...used, ...all.filter((entry) => !used.includes(entry))];
530
+ })();
531
+ // The palette shows one group at a time, so a group label can separate them.
532
+ return paletteGroups(state).flatMap((group) => ordered.filter((entry) => entry.group === group));
533
+ }
534
+
535
+ /** The state after an entry ran: it is now the latest of the recent ones. */
536
+ export function remember(state: TuiState, entry: TuiPaletteEntry): TuiState {
537
+ const id = entryId(entry);
538
+ return { ...state, recent: [id, ...state.recent.filter((one) => one !== id)].slice(0, RECENT_ENTRIES) };
539
+ }
540
+
541
+ /** The value typed after an action's name, checked against its first argument. */
542
+ function typedValue(
543
+ action: ViewAction,
544
+ row: ViewRow,
545
+ words: readonly string[],
546
+ ): Pick<TuiPaletteEntry, "typed" | "refusal"> {
547
+ if (words.length < 2) return {};
548
+ const field = argFields(action, row)[0];
549
+ if (field === undefined) return {};
550
+ // Only an action that the first word names takes the rest as its value.
551
+ if (fuzzyScore(words[0] ?? "", action.name) < 0) return {};
552
+ const parsed = parseArg(field, words.slice(1).join(" "));
553
+ return parsed.ok ? { typed: { value: parsed.value } } : { refusal: parsed.reason };
554
+ }
555
+
556
+ /** The entry the palette cursor is on. */
557
+ export function chosenEntry(state: TuiState): TuiPaletteEntry | undefined {
558
+ const input = state.input;
559
+ if (input?.kind !== "palette") return undefined;
560
+ const entries = paletteEntries(state);
561
+ return entries[Math.min(input.cursor, entries.length - 1)];
562
+ }
563
+
564
+ /** The words after an entry: its key and what it asks. */
565
+ export function entryHint(entry: TuiPaletteEntry): string {
566
+ if (entry.refusal !== undefined) return entry.refusal;
567
+ if (entry.setting !== undefined) {
568
+ return [
569
+ settingText(entry.setting.value),
570
+ entry.setting.scope === "global" ? undefined : sanitize(entry.setting.scope),
571
+ entry.setting.editable ? undefined : "read-only",
572
+ ]
573
+ .filter((part): part is string => part !== undefined)
574
+ .join(" · ");
575
+ }
576
+ return [
577
+ entry.key,
578
+ entry.needsNote ? "needs a note" : undefined,
579
+ entry.confirm ? "asks to confirm" : undefined,
580
+ ]
581
+ .filter((part): part is string => part !== undefined)
582
+ .join(" · ");
583
+ }
584
+
585
+ /** What an entry says after its name, without the key a column of its own shows. */
586
+ export function entryDetail(entry: TuiPaletteEntry): string {
587
+ if (entry.refusal !== undefined) return entry.refusal;
588
+ if (entry.setting !== undefined) return entryHint(entry);
589
+ return [
590
+ entry.needsNote ? "needs a note" : undefined,
591
+ entry.confirm ? "asks to confirm" : undefined,
592
+ ]
593
+ .filter((part): part is string => part !== undefined)
594
+ .join(" · ");
595
+ }
596
+
597
+ export function withNotice(state: TuiState, notice: string): TuiState {
598
+ return { ...state, notice: sanitize(notice) };
599
+ }
600
+
601
+ /** Opens a setting: its value prompt when it can change, a read-only page when not. */
602
+ function openSetting(state: TuiState, setting: TuiSetting): TuiState {
603
+ const field = setting.editable ? settingField(setting) : undefined;
604
+ return {
605
+ ...state,
606
+ input: {
607
+ kind: "setting",
608
+ setting,
609
+ ...(field === undefined ? {} : { field }),
610
+ cursor: field?.current ?? 0,
611
+ text: field?.initial ?? "",
612
+ },
613
+ };
614
+ }
615
+
616
+ function sendSetting(state: TuiState, setting: TuiSetting, value: unknown, confirmed: boolean): TuiState {
617
+ if (state.acting) return withNotice({ ...state, input: undefined }, "the last change has not answered yet");
618
+ return {
619
+ ...state,
620
+ input: undefined,
621
+ acting: true,
622
+ settingRequest: {
623
+ name: setting.name,
624
+ scope: setting.scope,
625
+ value,
626
+ ...(confirmed ? { confirmed: true } : {}),
627
+ },
628
+ };
629
+ }
630
+
631
+ /** A value is chosen or typed: ask to confirm when the setting says so, else send. */
632
+ function settingAnswered(state: TuiState, setting: TuiSetting, value: unknown): TuiState {
633
+ return setting.confirm
634
+ ? { ...state, input: { kind: "setting-confirm", setting, value } }
635
+ : sendSetting(state, setting, value, false);
636
+ }
637
+
638
+ /** A key arrives while a setting is open. */
639
+ function settingKey(
640
+ state: TuiState,
641
+ input: Extract<TuiInput, { readonly kind: "setting" }>,
642
+ event: { readonly text?: string | undefined; readonly ctrl?: boolean | undefined; readonly meta?: boolean | undefined },
643
+ key: string,
644
+ enter: boolean,
645
+ ): TuiState {
646
+ const field = input.field;
647
+ // A read-only setting only shows; Enter closes it as Escape does.
648
+ if (field === undefined) return enter ? { ...state, input: undefined } : state;
649
+ if (field.kind === "pick") {
650
+ const down = key === "down" || key === "arrowdown" || (event.ctrl !== true && event.text === "j") || (event.ctrl === true && (key === "n" || key === "j"));
651
+ const up = key === "up" || key === "arrowup" || (event.ctrl !== true && event.text === "k") || (event.ctrl === true && (key === "p" || key === "k"));
652
+ if (down || up) {
653
+ const cursor = Math.min(Math.max(0, input.cursor + (down ? 1 : -1)), field.options.length - 1);
654
+ return { ...state, input: { ...input, cursor } };
655
+ }
656
+ const option = field.options[input.cursor];
657
+ return enter && option !== undefined ? settingAnswered(state, input.setting, option.value) : state;
658
+ }
659
+ if (enter) return settingAnswered(state, input.setting, settingValue(input.text, input.setting.type));
660
+ if (key === "backspace") return { ...state, input: { ...input, text: dropLast(input.text) } };
661
+ const text = event.ctrl === true || event.meta === true ? undefined : typed(event);
662
+ return text === undefined ? state : { ...state, input: { ...input, text: input.text + text } };
663
+ }
664
+
665
+ /** Runs an action on the open object, or says why it cannot. */
666
+ export function startAction(
667
+ state: TuiState,
668
+ name: string,
669
+ first?: { readonly value: unknown },
670
+ ): TuiState {
671
+ const object = state.object;
672
+ const closed: TuiState = { ...state, input: undefined };
673
+ if (object === undefined) return withNotice(closed, "no object is selected");
674
+ if (state.acting) return withNotice(closed, "the last action has not answered yet");
675
+ const action = object.actions.find((candidate) => candidate.name === name);
676
+ if (action === undefined) {
677
+ return withNotice(closed, `${name} is not available for ${bareId(object.id)}`);
678
+ }
679
+ const fields = argFields(action, object.row);
680
+ const note = action.note === undefined ? undefined : { required: action.noteRequired };
681
+ if (fields.length > 0) {
682
+ const asking = argsInput(action.name, object.id, fields, 0, {}, note, action.confirm);
683
+ return first === undefined ? { ...closed, input: asking } : answer(closed, asking, first.value);
684
+ }
685
+ return afterArgs(closed, action.name, object.id, {}, note, action.confirm);
686
+ }
687
+
688
+ /** Opens the choice list of a pending question. */
689
+ export function startAnswer(state: TuiState, answer: TuiAnswer): TuiState {
690
+ const closed: TuiState = { ...state, input: undefined };
691
+ if (state.acting) return withNotice(closed, "the last change has not answered yet");
692
+ return {
693
+ ...closed,
694
+ input: { kind: "answer", answer, cursor: 0 },
695
+ };
696
+ }
697
+
698
+ /** Sends the chosen answer and closes the choice list. */
699
+ function sendAnswer(state: TuiState, answer: TuiAnswer, choice: string): TuiState {
700
+ return {
701
+ ...state,
702
+ input: undefined,
703
+ acting: true,
704
+ answerRequest: {
705
+ runId: answer.runId,
706
+ waitId: answer.waitId,
707
+ choice,
708
+ },
709
+ };
710
+ }
711
+
712
+ /** The keys of a pending question's choice list. */
713
+ function answerKey(
714
+ state: TuiState,
715
+ input: Extract<TuiInput, { readonly kind: "answer" }>,
716
+ key: string,
717
+ enter: boolean,
718
+ ): TuiState {
719
+ const down = key === "down" || key === "arrowdown" || key === "j";
720
+ const up = key === "up" || key === "arrowup" || key === "k";
721
+ if (down || up) {
722
+ const cursor = Math.min(
723
+ Math.max(0, input.cursor + (down ? 1 : -1)),
724
+ input.answer.choices.length - 1,
725
+ );
726
+ return { ...state, input: { ...input, cursor } };
727
+ }
728
+ if (!enter) return state;
729
+ const choice = input.answer.choices[input.cursor];
730
+ return choice === undefined ? state : sendAnswer(state, input.answer, choice);
731
+ }
732
+
733
+ type ArgsInput = Extract<TuiInput, { readonly kind: "args" }>;
734
+
735
+ function argsInput(
736
+ action: string,
737
+ id: string,
738
+ fields: readonly ArgField[],
739
+ at: number,
740
+ values: Readonly<Record<string, unknown>>,
741
+ note: ArgsInput["note"],
742
+ confirm: boolean,
743
+ ): ArgsInput {
744
+ const asked = fields[at];
745
+ const field = asked === undefined ? undefined : narrowField(asked, values);
746
+ return {
747
+ kind: "args",
748
+ action,
749
+ id,
750
+ fields: field === undefined ? fields : fields.map((one, index) => (index === at ? field : one)),
751
+ at,
752
+ values,
753
+ cursor: field?.optional === true && field.current === undefined ? -1 : (field?.current ?? 0),
754
+ text: field?.initial ?? "",
755
+ note,
756
+ confirm,
757
+ };
758
+ }
759
+
760
+ /** Records the answer to the field being asked and moves to the next step. */
761
+ function answer(state: TuiState, input: ArgsInput, value: unknown): TuiState {
762
+ const field = input.fields[input.at];
763
+ if (field === undefined) return { ...state, input: undefined };
764
+ const values = value === undefined
765
+ ? { ...input.values }
766
+ : { ...input.values, [field.name]: value };
767
+ let at = input.at + 1;
768
+ // A field the answered branch gives nothing to pick is not asked.
769
+ while (at < input.fields.length && narrowField(input.fields[at] as ArgField, values).skipped === true) at += 1;
770
+ if (at < input.fields.length) {
771
+ return {
772
+ ...state,
773
+ input: argsInput(input.action, input.id, input.fields, at, values, input.note, input.confirm),
774
+ };
775
+ }
776
+ return afterArgs({ ...state, input: undefined }, input.action, input.id, values, input.note, input.confirm);
777
+ }
778
+
779
+ /** Every argument is in: the note, the confirmation or the request comes next. */
780
+ function afterArgs(
781
+ state: TuiState,
782
+ action: string,
783
+ id: string,
784
+ args: Readonly<Record<string, unknown>>,
785
+ note: ArgsInput["note"],
786
+ confirm: boolean,
787
+ ): TuiState {
788
+ const given = Object.keys(args).length === 0 ? {} : { args };
789
+ if (note !== undefined) {
790
+ return {
791
+ ...state,
792
+ input: { kind: "note", action, id, text: "", required: note.required, confirm, ...given },
793
+ };
794
+ }
795
+ if (confirm) return { ...state, input: { kind: "confirm", action, id, ...given } };
796
+ return send(state, { action, id, ...given });
797
+ }
798
+
799
+ function send(
800
+ state: TuiState,
801
+ request: {
802
+ action: string;
803
+ id: string;
804
+ note?: string;
805
+ args?: Readonly<Record<string, unknown>>;
806
+ confirmed?: boolean;
807
+ },
808
+ ): TuiState {
809
+ return { ...state, input: undefined, acting: true, actionRequest: request };
810
+ }
811
+
812
+ /** `a`, or a bound key: the key that reached the reducer, as a label. */
813
+ export function runKey(state: TuiState, label: string): TuiState | undefined {
814
+ const bound = bindingFor(state.bindings, label);
815
+ if (bound !== undefined) return startAction(state, bound.action);
816
+ if (label === MAIN_KEY) {
817
+ const main = mainAction(state);
818
+ return main === undefined
819
+ ? withNotice(state, "no action is available")
820
+ : startAction(state, main.name);
821
+ }
822
+ return undefined;
823
+ }
824
+
825
+ /** The text a key adds to an input, if it adds any. */
826
+ export function typed(event: { readonly text?: string | undefined }): string | undefined {
827
+ const text = event.text;
828
+ return text === undefined || text === "" || /[\u0000-\u001f\u007f]/.test(text)
829
+ ? undefined
830
+ : text;
831
+ }
832
+
833
+ export function dropLast(text: string): string {
834
+ const all = graphemes(text);
835
+ all.pop();
836
+ return all.join("");
837
+ }
838
+
839
+ /** A key arrives while the palette, a note or a confirmation is open. */
840
+ export function inputKey(
841
+ state: TuiState,
842
+ input: Exclude<TuiInput, { readonly kind: "pages" | "themes" }>,
843
+ event: {
844
+ readonly key: string;
845
+ readonly text?: string | undefined;
846
+ readonly shift?: boolean | undefined;
847
+ readonly ctrl?: boolean | undefined;
848
+ readonly meta?: boolean | undefined;
849
+ },
850
+ ): TuiState {
851
+ const key = event.key.toLowerCase();
852
+ const escape = key === "escape" || key === "esc";
853
+ const enter = key === "enter" || key === "return";
854
+ if (input.kind === "confirm" || input.kind === "setting-confirm") {
855
+ const yes = event.ctrl !== true && event.meta !== true && (key === "y" || event.text === "y" || event.text === "Y");
856
+ if (!yes) return { ...state, input: undefined };
857
+ if (input.kind === "setting-confirm") return sendSetting(state, input.setting, input.value, true);
858
+ return send(state, {
859
+ action: input.action,
860
+ id: input.id,
861
+ ...(input.note === undefined ? {} : { note: input.note }),
862
+ ...(input.args === undefined ? {} : { args: input.args }),
863
+ confirmed: true,
864
+ });
865
+ }
866
+ if (escape) return { ...state, input: undefined };
867
+ if (input.kind === "answer") return answerKey(state, input, key, enter);
868
+ if (input.kind === "setting") return settingKey(state, input, event, key, enter);
869
+ if (input.kind === "args") return argsKey(state, input, event, key, enter);
870
+ if (input.kind === "palette") {
871
+ const entries = paletteEntries(state);
872
+ const down = key === "down" || key === "arrowdown" || (event.ctrl === true && (key === "n" || key === "j"));
873
+ const up = key === "up" || key === "arrowup" || (event.ctrl === true && (key === "p" || key === "k"));
874
+ if (down || up) {
875
+ const cursor = Math.min(
876
+ Math.max(0, input.cursor + (down ? 1 : -1)),
877
+ Math.max(0, entries.length - 1),
878
+ );
879
+ return { ...state, input: { ...input, cursor } };
880
+ }
881
+ if (enter) {
882
+ const chosen = chosenEntry(state);
883
+ // A command is run by the reducer that owns the state it changes.
884
+ // A value that does not fit stays in the palette, with what is allowed.
885
+ if (chosen?.setting !== undefined) {
886
+ return openSetting(remember({ ...state, input: undefined }, chosen), chosen.setting);
887
+ }
888
+ return chosen === undefined || chosen.command !== undefined || chosen.refusal !== undefined
889
+ ? state
890
+ : startAction(remember({ ...state, input: undefined }, chosen), chosen.name, chosen.typed);
891
+ }
892
+ if (key === "backspace") {
893
+ return { ...state, input: { ...input, query: dropLast(input.query), cursor: 0 } };
894
+ }
895
+ const text = event.ctrl === true || event.meta === true ? undefined : typed(event);
896
+ return text === undefined
897
+ ? state
898
+ : { ...state, input: { ...input, query: input.query + text, cursor: 0 } };
899
+ }
900
+ // A note: Enter sends, Shift-Enter or Ctrl-J adds a line.
901
+ const newline = (enter && event.shift === true) || (event.ctrl === true && (key === "j" || key === "linefeed")) || key === "linefeed";
902
+ if (newline) return { ...state, input: { ...input, text: `${input.text}\n` } };
903
+ if (enter) {
904
+ const note = input.text;
905
+ if (note.trim() === "" && input.required) return withNotice(state, "a note is required");
906
+ if (input.confirm) {
907
+ return {
908
+ ...state,
909
+ input: {
910
+ kind: "confirm",
911
+ action: input.action,
912
+ id: input.id,
913
+ ...(note === "" ? {} : { note }),
914
+ ...(input.args === undefined ? {} : { args: input.args }),
915
+ },
916
+ };
917
+ }
918
+ return send(state, {
919
+ action: input.action,
920
+ id: input.id,
921
+ ...(note === "" ? {} : { note }),
922
+ ...(input.args === undefined ? {} : { args: input.args }),
923
+ });
924
+ }
925
+ if (key === "backspace") return { ...state, input: { ...input, text: dropLast(input.text) } };
926
+ const text = event.ctrl === true || event.meta === true ? undefined : typed(event);
927
+ return text === undefined ? state : { ...state, input: { ...input, text: input.text + text } };
928
+ }
929
+
930
+ /**
931
+ * The server refused (or the network failed): show the line itself. The status
932
+ * is for logs, never for the person; a plugin's own field prefix ("confirm: ")
933
+ * is dropped too.
934
+ */
935
+ export function actionFailed(state: TuiState, message: string): TuiState {
936
+ return {
937
+ ...withNotice(state, refusalLine(message)),
938
+ acting: false,
939
+ actionRequest: undefined,
940
+ answerRequest: undefined,
941
+ };
942
+ }
943
+
944
+ /** The line a person reads: the server's sentence without its status number. */
945
+ export function refusalLine(message: string): string {
946
+ return message.replace(/^\d{3}\s+/, "");
947
+ }
948
+
949
+ /** A key arrives while an argument is asked. */
950
+ function argsKey(
951
+ state: TuiState,
952
+ input: ArgsInput,
953
+ event: { readonly text?: string | undefined; readonly ctrl?: boolean | undefined; readonly meta?: boolean | undefined },
954
+ key: string,
955
+ enter: boolean,
956
+ ): TuiState {
957
+ const field = input.fields[input.at];
958
+ if (field === undefined) return { ...state, input: undefined };
959
+ if (field.kind === "pick") {
960
+ const down = key === "down" || key === "arrowdown" || (event.ctrl !== true && event.text === "j") || (event.ctrl === true && (key === "n" || key === "j"));
961
+ const up = key === "up" || key === "arrowup" || (event.ctrl !== true && event.text === "k") || (event.ctrl === true && (key === "p" || key === "k"));
962
+ if (down || up) {
963
+ const floor = field.optional === true ? -1 : 0;
964
+ const cursor = Math.min(Math.max(floor, input.cursor + (down ? 1 : -1)), field.options.length - 1);
965
+ return { ...state, input: { ...input, cursor } };
966
+ }
967
+ if (enter && field.optional === true && input.cursor < 0) {
968
+ return answer(state, input, undefined);
969
+ }
970
+ const option = field.options[input.cursor];
971
+ return enter && option !== undefined ? answer(state, input, option.value) : state;
972
+ }
973
+ if (enter) {
974
+ const parsed = parseArg(field, input.text);
975
+ return parsed.ok
976
+ ? answer(state, input, parsed.value)
977
+ : { ...state, input: { ...input, error: parsed.reason } };
978
+ }
979
+ if (key === "backspace") {
980
+ return { ...state, input: { ...input, text: dropLast(input.text), error: undefined } };
981
+ }
982
+ const text = event.ctrl === true || event.meta === true ? undefined : typed(event);
983
+ return text === undefined
984
+ ? state
985
+ : { ...state, input: { ...input, text: input.text + text, error: undefined } };
986
+ }
987
+
988
+ /** The footer line a confirmation asks, in red. */
989
+ export function confirmText(state: TuiState): string | undefined {
990
+ const input = state.input;
991
+ if (input?.kind === "setting-confirm") {
992
+ return `set ${sanitize(input.setting.name)} to ${settingText(input.value)}? [y/N]`;
993
+ }
994
+ return input?.kind === "confirm"
995
+ ? `${input.action} ${bareId(input.id)}? [y/N]`
996
+ : undefined;
997
+ }