@operad-io/tui 0.0.0-stage → 0.0.1
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/LICENSE +21 -0
- package/README.md +68 -2
- package/package.json +27 -4
- package/src/actions.ts +997 -0
- package/src/app.ts +1665 -0
- package/src/args.ts +198 -0
- package/src/autostart.ts +302 -0
- package/src/client.ts +478 -0
- package/src/discover.ts +90 -0
- package/src/events.ts +345 -0
- package/src/index.ts +11 -0
- package/src/layout.ts +260 -0
- package/src/live.ts +113 -0
- package/src/markdown.ts +85 -0
- package/src/recent.ts +40 -0
- package/src/sanitize.ts +18 -0
- package/src/state.ts +3200 -0
- package/src/theme.ts +525 -0
- package/src/themes.ts +60 -0
- package/src/view/index.ts +1204 -0
- package/src/wrap.ts +156 -0
- package/theme.schema.json +197 -0
- package/themes/LICENSE-catppuccin +21 -0
- package/themes/LICENSE-dracula +21 -0
- package/themes/LICENSE-github +21 -0
- package/themes/LICENSE-kanagawa +21 -0
- package/themes/LICENSE-nord +21 -0
- package/themes/LICENSE-one +20 -0
- package/themes/LICENSE-rose-pine +21 -0
- package/themes/LICENSE-solarized +20 -0
- package/themes/LICENSE-tokyo-night +22 -0
- package/themes/README.md +81 -0
- package/themes/catppuccin-frappe.json +19 -0
- package/themes/catppuccin-latte.json +19 -0
- package/themes/catppuccin-macchiato.json +19 -0
- package/themes/catppuccin-mocha.json +19 -0
- package/themes/dracula.json +19 -0
- package/themes/github-dark.json +19 -0
- package/themes/github-light.json +19 -0
- package/themes/kanagawa-dragon.json +19 -0
- package/themes/kanagawa-lotus.json +19 -0
- package/themes/kanagawa-wave.json +19 -0
- package/themes/nord.json +19 -0
- package/themes/one-dark.json +19 -0
- package/themes/one-light.json +19 -0
- package/themes/rose-pine-dawn.json +19 -0
- package/themes/rose-pine-main.json +19 -0
- package/themes/solarized-dark.json +19 -0
- package/themes/solarized-light.json +19 -0
- package/themes/tokyo-night-day.json +19 -0
- package/themes/tokyo-night-night.json +19 -0
- package/tui.schema.json +24 -0
package/src/app.ts
ADDED
|
@@ -0,0 +1,1665 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `operad tui`: discover the server, open the full-screen view, keep the state
|
|
3
|
+
* fed from `/v1` and the event stream, and send keys through the reducer. It
|
|
4
|
+
* never opens the store and never loads a plugin.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
CliRenderEvents,
|
|
9
|
+
createCliRenderer,
|
|
10
|
+
type CliRenderer,
|
|
11
|
+
} from "@opentui/core";
|
|
12
|
+
import type {
|
|
13
|
+
PendingItem,
|
|
14
|
+
RunningItem,
|
|
15
|
+
ViewListPage,
|
|
16
|
+
ViewObject,
|
|
17
|
+
ViewRow,
|
|
18
|
+
ViewSectionContent,
|
|
19
|
+
} from "@operad-io/engine";
|
|
20
|
+
import { ensureServer, spawnServe, type EnsureServerOptions } from "./autostart.ts";
|
|
21
|
+
import {
|
|
22
|
+
TuiClient,
|
|
23
|
+
TuiError,
|
|
24
|
+
type FetchLike,
|
|
25
|
+
type TuiActInput,
|
|
26
|
+
type TuiKeyBinding,
|
|
27
|
+
} from "./client.ts";
|
|
28
|
+
import { defaultOperadHome, messageOf } from "@operad-io/engine";
|
|
29
|
+
import { loadRecent, saveRecent } from "./recent.ts";
|
|
30
|
+
import { discoverServer } from "./discover.ts";
|
|
31
|
+
import { TuiEvents, retryDelay, type TuiEvent } from "./events.ts";
|
|
32
|
+
import {
|
|
33
|
+
LiveBatcher,
|
|
34
|
+
connectionOf,
|
|
35
|
+
refetchTargets,
|
|
36
|
+
systemClock,
|
|
37
|
+
type Refetch,
|
|
38
|
+
type TuiClock,
|
|
39
|
+
} from "./live.ts";
|
|
40
|
+
import {
|
|
41
|
+
initialState,
|
|
42
|
+
pluginTabOf,
|
|
43
|
+
rowFromView,
|
|
44
|
+
sameObject,
|
|
45
|
+
type TuiTab,
|
|
46
|
+
type TuiTreeEntry,
|
|
47
|
+
type TuiObject,
|
|
48
|
+
joinMarkdown,
|
|
49
|
+
markPage,
|
|
50
|
+
reduce,
|
|
51
|
+
type TuiSection,
|
|
52
|
+
type TuiActionRequest,
|
|
53
|
+
type TuiAnswerRequest,
|
|
54
|
+
type TuiSettingRequest,
|
|
55
|
+
type TuiObjectRequest,
|
|
56
|
+
type TuiFilterRequest,
|
|
57
|
+
type TuiSectionRequest,
|
|
58
|
+
type TuiState,
|
|
59
|
+
type TuiStateEvent,
|
|
60
|
+
type TuiTheme,
|
|
61
|
+
} from "./state.ts";
|
|
62
|
+
import {
|
|
63
|
+
chooseChildLayout,
|
|
64
|
+
chooseSelection,
|
|
65
|
+
installedThemes,
|
|
66
|
+
resolveSelection,
|
|
67
|
+
saveChildLayout,
|
|
68
|
+
saveThemeChoice,
|
|
69
|
+
watchThemes,
|
|
70
|
+
type ThemeHolder,
|
|
71
|
+
type TuiChildLayout,
|
|
72
|
+
} from "./theme.ts";
|
|
73
|
+
import { createTuiView, type TuiView } from "./view/index.ts";
|
|
74
|
+
import type { TuiLevel, TuiSetInput, TuiSetting, TuiTypeInfo } from "./client.ts";
|
|
75
|
+
import { settingScopes } from "./actions.ts";
|
|
76
|
+
|
|
77
|
+
/** How `operad tui` finds its server and reports a problem. */
|
|
78
|
+
export interface TuiRunOptions {
|
|
79
|
+
readonly home?: string | undefined;
|
|
80
|
+
readonly url?: string | undefined;
|
|
81
|
+
readonly token?: string | undefined;
|
|
82
|
+
/** Closes the app from outside, as a signal would. */
|
|
83
|
+
readonly signal?: AbortSignal | undefined;
|
|
84
|
+
/**
|
|
85
|
+
* A non-fatal client or stream error. The messages are kept while the screen
|
|
86
|
+
* is open and passed here one by one after the terminal is restored.
|
|
87
|
+
*/
|
|
88
|
+
readonly onError?: ((message: string) => void) | undefined;
|
|
89
|
+
/**
|
|
90
|
+
* What the app logs while the screen is open (a refused action and its
|
|
91
|
+
* status). Kept until the terminal is restored, then passed one by one.
|
|
92
|
+
*/
|
|
93
|
+
readonly onLog?: ((message: string) => void) | undefined;
|
|
94
|
+
/** Never start `operad serve`, even when none answers. */
|
|
95
|
+
readonly noStart?: boolean | undefined;
|
|
96
|
+
/** The `operad` entry file a started serve runs; without it none is started. */
|
|
97
|
+
readonly serveEntry?: string | undefined;
|
|
98
|
+
/** Prints a line before the full screen opens. */
|
|
99
|
+
readonly write?: ((line: string) => void) | undefined;
|
|
100
|
+
/** `--theme`: the theme name for this session; it beats `tui.json`. */
|
|
101
|
+
readonly theme?: string | undefined;
|
|
102
|
+
/** Replaces the terminal pieces in a test. */
|
|
103
|
+
readonly hooks?: TuiRunHooks | undefined;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The terminal pieces `runTui` builds, so a test can hand it others. */
|
|
107
|
+
export interface TuiRunHooks {
|
|
108
|
+
readonly renderer?: (() => Promise<CliRenderer>) | undefined;
|
|
109
|
+
readonly view?: ((renderer: CliRenderer) => TuiView) | undefined;
|
|
110
|
+
/** Replaces the check that a serve answers, and its start. */
|
|
111
|
+
readonly ensure?:
|
|
112
|
+
| ((options: EnsureServerOptions) => Promise<string>)
|
|
113
|
+
| undefined;
|
|
114
|
+
readonly fetch?: FetchLike | undefined;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** One key press, as far as the reducer cares. */
|
|
118
|
+
export interface TuiKeyInput {
|
|
119
|
+
readonly name: string;
|
|
120
|
+
readonly sequence?: string | undefined;
|
|
121
|
+
readonly shift?: boolean | undefined;
|
|
122
|
+
readonly ctrl?: boolean | undefined;
|
|
123
|
+
readonly meta?: boolean | undefined;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** The calls the shell makes; `TuiClient` has them, and a test fakes them. */
|
|
127
|
+
export interface TuiShellClient {
|
|
128
|
+
types(signal?: AbortSignal): Promise<{ readonly types: readonly TuiTypeInfo[] }>;
|
|
129
|
+
pending(signal?: AbortSignal): Promise<readonly PendingItem[]>;
|
|
130
|
+
running(signal?: AbortSignal): Promise<readonly RunningItem[]>;
|
|
131
|
+
objects(
|
|
132
|
+
type: string,
|
|
133
|
+
cursor?: string,
|
|
134
|
+
signal?: AbortSignal,
|
|
135
|
+
filter?: string,
|
|
136
|
+
level?: TuiLevel,
|
|
137
|
+
): Promise<ViewListPage>;
|
|
138
|
+
/** Optional: a server without `/v1/keys` leaves the bindings empty. */
|
|
139
|
+
keys?(signal?: AbortSignal): Promise<readonly TuiKeyBinding[]>;
|
|
140
|
+
/** Optional: a server without `/v1/settings` lists none. */
|
|
141
|
+
settings?(scope?: string, signal?: AbortSignal): Promise<readonly TuiSetting[]>;
|
|
142
|
+
/** Optional: changes one setting. */
|
|
143
|
+
setSetting?(input: TuiSetInput): Promise<unknown>;
|
|
144
|
+
/** Optional: answers one open question of a pending item. */
|
|
145
|
+
answer?(input: TuiAnswerRequest & { readonly signal?: AbortSignal | undefined }): Promise<unknown>;
|
|
146
|
+
/** Optional so an older test client still fits; the actions need it. */
|
|
147
|
+
act?(input: TuiActInput): Promise<unknown>;
|
|
148
|
+
/** Optional so an older test client still fits; the object pane needs it. */
|
|
149
|
+
object?(id: string, signal?: AbortSignal): Promise<ViewObject>;
|
|
150
|
+
/** Optional so an older test client still fits; the object pane needs it. */
|
|
151
|
+
section?(
|
|
152
|
+
id: string,
|
|
153
|
+
section: string,
|
|
154
|
+
options?: {
|
|
155
|
+
readonly cursor?: string | undefined;
|
|
156
|
+
readonly after?: string | undefined;
|
|
157
|
+
readonly full?: boolean | undefined;
|
|
158
|
+
readonly signal?: AbortSignal | undefined;
|
|
159
|
+
},
|
|
160
|
+
): Promise<ViewSectionContent>;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** The change stream the shell reads; `TuiEvents` has this shape. */
|
|
164
|
+
export interface TuiEventSource extends AsyncIterable<TuiEvent> {
|
|
165
|
+
stop(): void;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Everything the shell needs from outside; no terminal handle is in here. */
|
|
169
|
+
export interface TuiShellDeps {
|
|
170
|
+
readonly client: TuiShellClient;
|
|
171
|
+
/** Opens the change stream; `signal` aborts it when the shell stops. */
|
|
172
|
+
readonly events: (signal: AbortSignal) => TuiEventSource;
|
|
173
|
+
readonly view: TuiView;
|
|
174
|
+
readonly width: number;
|
|
175
|
+
readonly height: number;
|
|
176
|
+
readonly theme: TuiTheme;
|
|
177
|
+
/** The child list layout to start with; the tree when unset. */
|
|
178
|
+
readonly childLayout?: TuiChildLayout | undefined;
|
|
179
|
+
/** Keeps a chosen child layout; a failure is shown as a footer line. */
|
|
180
|
+
readonly onChildLayout?: ((layout: TuiChildLayout) => void) | undefined;
|
|
181
|
+
/** Where a refusal's status goes: a log, never the screen. */
|
|
182
|
+
readonly onLog?: ((message: string) => void) | undefined;
|
|
183
|
+
/** A failed request; the page shows it too, and the app goes on. */
|
|
184
|
+
readonly onMessage?: ((message: string) => void) | undefined;
|
|
185
|
+
/**
|
|
186
|
+
* An error the app cannot go on from: the shell stops (`done` resolves 1)
|
|
187
|
+
* after this is called, and the caller reports it once the screen is gone.
|
|
188
|
+
*/
|
|
189
|
+
readonly onFatal?: ((message: string) => void) | undefined;
|
|
190
|
+
/** Called once when the shell finishes, before `done` resolves. */
|
|
191
|
+
readonly onFinish?: (() => void) | undefined;
|
|
192
|
+
/** Spaces the live refetches and the retries; the real clock by default. */
|
|
193
|
+
readonly clock?: TuiClock | undefined;
|
|
194
|
+
/** The server's URL, named when it does not answer. */
|
|
195
|
+
readonly url?: string | undefined;
|
|
196
|
+
/**
|
|
197
|
+
* The wait after the list cursor stops before the object pane follows it, so
|
|
198
|
+
* scrolling fast does not fetch every row; 150 by default.
|
|
199
|
+
*/
|
|
200
|
+
readonly followDelayMs?: number | undefined;
|
|
201
|
+
/** The palette entries used in earlier runs, the latest first. */
|
|
202
|
+
readonly recent?: readonly string[] | undefined;
|
|
203
|
+
/** The theme list of the `theme` command; without it the list is empty. */
|
|
204
|
+
readonly themes?: TuiThemes | undefined;
|
|
205
|
+
/** Called with the list of recent entries each time it changes. */
|
|
206
|
+
readonly onRecent?: ((recent: readonly string[]) => void) | undefined;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** What the `theme` command needs from outside the reducer. */
|
|
210
|
+
export interface TuiThemes {
|
|
211
|
+
/** The installed theme names. */
|
|
212
|
+
list(): readonly string[];
|
|
213
|
+
/** The name of the theme in force. */
|
|
214
|
+
current(): string;
|
|
215
|
+
/** Shows a theme without keeping it; none shows the one in force. Throws when the theme cannot be read. */
|
|
216
|
+
preview(name: string | undefined): void;
|
|
217
|
+
/** Keeps a theme: it is in force from now on and the next start uses it. Throws when it cannot. */
|
|
218
|
+
save(name: string): void;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** A running shell: feed it keys and sizes, and wait for `done`. */
|
|
222
|
+
export interface TuiShell {
|
|
223
|
+
readonly state: TuiState;
|
|
224
|
+
key(input: TuiKeyInput): void;
|
|
225
|
+
resize(width: number, height: number): void;
|
|
226
|
+
setTheme(theme: TuiTheme): void;
|
|
227
|
+
/** Repaints after the theme files changed; `problem` is shown in the footer, none clears it. */
|
|
228
|
+
repaintTheme(problem?: string): void;
|
|
229
|
+
stop(): void;
|
|
230
|
+
/** Resolves with the exit code once the shell has finished. */
|
|
231
|
+
readonly done: Promise<number>;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Starts the footer line that says a changed theme file was not applied. */
|
|
235
|
+
const THEME_PROBLEM = "theme not changed:";
|
|
236
|
+
|
|
237
|
+
/** The signals that close the app cleanly. */
|
|
238
|
+
const STOP_SIGNALS: readonly NodeJS.Signals[] = ["SIGINT", "SIGTERM"];
|
|
239
|
+
|
|
240
|
+
/** A settle result without throwing away the error's text. */
|
|
241
|
+
type Settled<T> =
|
|
242
|
+
| { readonly ok: true; readonly value: T }
|
|
243
|
+
| { readonly ok: false; readonly error: unknown };
|
|
244
|
+
|
|
245
|
+
async function settle<T>(promise: Promise<T>): Promise<Settled<T>> {
|
|
246
|
+
try {
|
|
247
|
+
return { ok: true, value: await promise };
|
|
248
|
+
} catch (error) {
|
|
249
|
+
return { ok: false, error };
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function themeOf(renderer: CliRenderer, fallback: TuiTheme): TuiTheme {
|
|
254
|
+
return renderer.themeMode ?? fallback;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* The app without a terminal: it keeps the state fed from the client and the
|
|
259
|
+
* change stream, and sends keys through the reducer. `runTui` wires it to a
|
|
260
|
+
* renderer; a test wires it to fakes.
|
|
261
|
+
*/
|
|
262
|
+
/** A result that was already true says so: its line shows as the notice. */
|
|
263
|
+
function settledNotice(ran: unknown): { readonly notice?: string; readonly opens?: string } {
|
|
264
|
+
if (typeof ran !== "object" || ran === null) return {};
|
|
265
|
+
const { settled, value, opens } = ran as { settled?: unknown; value?: unknown; opens?: unknown };
|
|
266
|
+
return {
|
|
267
|
+
...(settled === true && typeof value === "string" && value.length > 0 ? { notice: value } : {}),
|
|
268
|
+
...(typeof opens === "string" && opens.length > 0 ? { opens } : {}),
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
export function startShell(deps: TuiShellDeps): TuiShell {
|
|
273
|
+
const { client, view } = deps;
|
|
274
|
+
const abort = new AbortController();
|
|
275
|
+
const report = (error: unknown): void => deps.onMessage?.(messageOf(error));
|
|
276
|
+
|
|
277
|
+
let state: TuiState = initialState({
|
|
278
|
+
width: deps.width,
|
|
279
|
+
height: deps.height,
|
|
280
|
+
theme: deps.theme,
|
|
281
|
+
childLayout: deps.childLayout,
|
|
282
|
+
url: deps.url,
|
|
283
|
+
recent: deps.recent,
|
|
284
|
+
themeNames: deps.themes?.list(),
|
|
285
|
+
themeCurrent: deps.themes?.current(),
|
|
286
|
+
});
|
|
287
|
+
let shownPreview: string | undefined;
|
|
288
|
+
let finished = false;
|
|
289
|
+
let refreshAbort: AbortController | undefined;
|
|
290
|
+
// The requests of the open object: its read and its section pages. They end
|
|
291
|
+
// when the object closes or another one opens, and at no other time, so
|
|
292
|
+
// switching sections never cancels a page another section is waiting for.
|
|
293
|
+
const objectRequests = new Set<AbortController>();
|
|
294
|
+
// The live-section reads that asked after a mark. A whole read supersedes
|
|
295
|
+
// them, so an older delta can never land after it and hide its content.
|
|
296
|
+
const afterReads = new Set<AbortController>();
|
|
297
|
+
let seenObject: number | undefined;
|
|
298
|
+
let seenMove = 0;
|
|
299
|
+
const clock = deps.clock ?? systemClock;
|
|
300
|
+
let retryCancel: (() => void) | undefined;
|
|
301
|
+
let retryAttempt = 0;
|
|
302
|
+
const batcher = new LiveBatcher(clock, (targets) => guard(refetch(targets)));
|
|
303
|
+
let followTimer: (() => void) | undefined;
|
|
304
|
+
let events: TuiEventSource | undefined;
|
|
305
|
+
let announce: (code: number) => void = () => undefined;
|
|
306
|
+
const done = new Promise<number>((resolve) => {
|
|
307
|
+
announce = resolve;
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
/** An unexpected rejection ends the app, through the same exit as `q`. */
|
|
311
|
+
function guard(work: Promise<void>): void {
|
|
312
|
+
work.catch(fatal);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function fatal(error: unknown): void {
|
|
316
|
+
if (finished) return;
|
|
317
|
+
try {
|
|
318
|
+
deps.onFatal?.(messageOf(error));
|
|
319
|
+
} finally {
|
|
320
|
+
finish(1);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function finish(code = 0): void {
|
|
325
|
+
if (finished) return;
|
|
326
|
+
finished = true;
|
|
327
|
+
batcher.stop();
|
|
328
|
+
retryCancel?.();
|
|
329
|
+
retryCancel = undefined;
|
|
330
|
+
if (followTimer !== undefined) {
|
|
331
|
+
followTimer();
|
|
332
|
+
followTimer = undefined;
|
|
333
|
+
}
|
|
334
|
+
refreshAbort?.abort();
|
|
335
|
+
for (const request of objectRequests) request.abort();
|
|
336
|
+
objectRequests.clear();
|
|
337
|
+
events?.stop();
|
|
338
|
+
abort.abort();
|
|
339
|
+
try {
|
|
340
|
+
deps.onFinish?.();
|
|
341
|
+
} finally {
|
|
342
|
+
announce(code);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** A request that failed to reach the server, or was refused its token. */
|
|
347
|
+
function noteConnection(error: unknown): boolean {
|
|
348
|
+
const lost = connectionOf(error);
|
|
349
|
+
if (lost === undefined) return false;
|
|
350
|
+
// A 401 is terminal: a later transport failure does not replace it.
|
|
351
|
+
if (state.connection === "unauthorized" && lost !== "unauthorized") return true;
|
|
352
|
+
dispatch({ type: "connection", connection: lost });
|
|
353
|
+
if (lost === "unauthorized" && retryCancel !== undefined) {
|
|
354
|
+
retryCancel();
|
|
355
|
+
retryCancel = undefined;
|
|
356
|
+
}
|
|
357
|
+
if (lost === "unauthorized") batcher.stop();
|
|
358
|
+
// Whoever lost the server, the lists are asked for again with backoff.
|
|
359
|
+
if (lost === "unreachable") scheduleRetry();
|
|
360
|
+
return true;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
async function loadObject(request: TuiObjectRequest): Promise<void> {
|
|
364
|
+
const open = client.object;
|
|
365
|
+
if (open === undefined) return;
|
|
366
|
+
const mine = new AbortController();
|
|
367
|
+
objectRequests.add(mine);
|
|
368
|
+
try {
|
|
369
|
+
const object = await open.call(client, request.id, mine.signal);
|
|
370
|
+
dispatch({ type: "object", object, version: request.version });
|
|
371
|
+
await loadChildren(object, request.version, mine.signal);
|
|
372
|
+
} catch (error) {
|
|
373
|
+
if (mine.signal.aborted) return;
|
|
374
|
+
noteConnection(error);
|
|
375
|
+
dispatch({
|
|
376
|
+
type: "object-error",
|
|
377
|
+
id: request.id,
|
|
378
|
+
message: messageOf(error),
|
|
379
|
+
version: request.version,
|
|
380
|
+
});
|
|
381
|
+
report(error);
|
|
382
|
+
} finally {
|
|
383
|
+
objectRequests.delete(mine);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* The id a request sends: the open object's answer carries a bare id, and a
|
|
389
|
+
* bare id can be ambiguous across types, so the type goes in front of it.
|
|
390
|
+
*/
|
|
391
|
+
function wire(id: string): string {
|
|
392
|
+
const open = state.object;
|
|
393
|
+
if (open === undefined || open.id !== id || id.startsWith(`${open.type}:`)) return id;
|
|
394
|
+
return `${open.type}:${id}`;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
async function loadSection(request: TuiSectionRequest): Promise<void> {
|
|
398
|
+
const load = client.section;
|
|
399
|
+
if (load === undefined) return;
|
|
400
|
+
const mine = new AbortController();
|
|
401
|
+
objectRequests.add(mine);
|
|
402
|
+
try {
|
|
403
|
+
const content = await load.call(client, wire(request.objectId), request.sectionId, {
|
|
404
|
+
...(request.cursor === undefined ? {} : { cursor: request.cursor }),
|
|
405
|
+
...(request.full ? { full: true } : {}),
|
|
406
|
+
signal: mine.signal,
|
|
407
|
+
});
|
|
408
|
+
dispatch({
|
|
409
|
+
type: "section",
|
|
410
|
+
objectId: request.objectId,
|
|
411
|
+
sectionId: request.sectionId,
|
|
412
|
+
content,
|
|
413
|
+
...(request.cursor === undefined ? {} : { cursor: request.cursor }),
|
|
414
|
+
...(request.jump === undefined ? {} : { jump: request.jump }),
|
|
415
|
+
full: request.full,
|
|
416
|
+
version: request.version,
|
|
417
|
+
objectVersion: request.objectVersion,
|
|
418
|
+
});
|
|
419
|
+
} catch (error) {
|
|
420
|
+
if (mine.signal.aborted) return;
|
|
421
|
+
noteConnection(error);
|
|
422
|
+
dispatch({
|
|
423
|
+
type: "section-error",
|
|
424
|
+
objectId: request.objectId,
|
|
425
|
+
sectionId: request.sectionId,
|
|
426
|
+
message: messageOf(error),
|
|
427
|
+
version: request.version,
|
|
428
|
+
objectVersion: request.objectVersion,
|
|
429
|
+
});
|
|
430
|
+
report(error);
|
|
431
|
+
} finally {
|
|
432
|
+
objectRequests.delete(mine);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/** The page a refresh starts from: the one the text starts at, if the contents still list it. */
|
|
437
|
+
function startOf(section: TuiSection): { readonly index: number; readonly cursor: string | undefined } {
|
|
438
|
+
const page = section.toc?.[section.pageStart];
|
|
439
|
+
return page === undefined
|
|
440
|
+
? { index: 0, cursor: undefined }
|
|
441
|
+
: { index: section.pageStart, cursor: page.cursor };
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Reads a section from its first page to as many pages as it holds now, so a
|
|
446
|
+
* refresh keeps what the person paged to instead of cutting it back to one.
|
|
447
|
+
*/
|
|
448
|
+
async function fetchSectionDepth(
|
|
449
|
+
id: string,
|
|
450
|
+
sectionId: string,
|
|
451
|
+
pages: number,
|
|
452
|
+
full: boolean,
|
|
453
|
+
start: { readonly index: number; readonly cursor: string | undefined },
|
|
454
|
+
signal: AbortSignal,
|
|
455
|
+
): Promise<
|
|
456
|
+
| {
|
|
457
|
+
readonly content: ViewSectionContent;
|
|
458
|
+
readonly pages: number;
|
|
459
|
+
readonly marks: readonly number[];
|
|
460
|
+
}
|
|
461
|
+
| undefined
|
|
462
|
+
> {
|
|
463
|
+
const load = client.section;
|
|
464
|
+
if (load === undefined) return undefined;
|
|
465
|
+
let markdown = "";
|
|
466
|
+
let next: string | undefined;
|
|
467
|
+
let cursor: string | undefined = start.cursor;
|
|
468
|
+
let read = 0;
|
|
469
|
+
let mark: string | undefined;
|
|
470
|
+
let tail: string | undefined;
|
|
471
|
+
const marks: number[] = [];
|
|
472
|
+
do {
|
|
473
|
+
const content = await load.call(client, wire(id), sectionId, {
|
|
474
|
+
...(cursor === undefined ? {} : { cursor }),
|
|
475
|
+
...(full ? { full: true } : {}),
|
|
476
|
+
signal,
|
|
477
|
+
});
|
|
478
|
+
if (read > 0) marks.push(markPage(markdown, content.markdown));
|
|
479
|
+
markdown = read === 0 ? content.markdown : joinMarkdown(markdown, content.markdown);
|
|
480
|
+
next = content.next;
|
|
481
|
+
cursor = next;
|
|
482
|
+
// The last page read holds where the finished content ends and what is
|
|
483
|
+
// still changing; a later refresh continues from there.
|
|
484
|
+
mark = content.mark;
|
|
485
|
+
tail = content.tail;
|
|
486
|
+
read += 1;
|
|
487
|
+
} while (next !== undefined && read < Math.max(1, pages));
|
|
488
|
+
return {
|
|
489
|
+
content: {
|
|
490
|
+
markdown,
|
|
491
|
+
...(next === undefined ? {} : { next }),
|
|
492
|
+
...(mark === undefined ? {} : { mark }),
|
|
493
|
+
...(tail === undefined ? {} : { tail }),
|
|
494
|
+
},
|
|
495
|
+
pages: read,
|
|
496
|
+
marks,
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** Every row of one level of one type, all pages, and the hidden rows by role. */
|
|
501
|
+
async function fetchLevel(
|
|
502
|
+
type: string,
|
|
503
|
+
level: TuiLevel,
|
|
504
|
+
signal: AbortSignal,
|
|
505
|
+
filter?: string,
|
|
506
|
+
): Promise<{
|
|
507
|
+
readonly rows: readonly ViewRow[];
|
|
508
|
+
readonly hidden: number;
|
|
509
|
+
readonly hiddenDone: number;
|
|
510
|
+
readonly hiddenCancelled: number;
|
|
511
|
+
}> {
|
|
512
|
+
const rows: ViewRow[] = [];
|
|
513
|
+
let cursor: string | undefined;
|
|
514
|
+
let hidden = 0;
|
|
515
|
+
let hiddenDone = 0;
|
|
516
|
+
let hiddenCancelled = 0;
|
|
517
|
+
let first = true;
|
|
518
|
+
do {
|
|
519
|
+
const page = await client.objects(type, cursor, signal, filter, level);
|
|
520
|
+
rows.push(...page.rows);
|
|
521
|
+
if (first) {
|
|
522
|
+
hidden = page.hidden ?? 0;
|
|
523
|
+
hiddenDone = page.hiddenCounts?.done ?? hidden;
|
|
524
|
+
hiddenCancelled = page.hiddenCounts?.cancelled ?? 0;
|
|
525
|
+
}
|
|
526
|
+
first = false;
|
|
527
|
+
cursor = page.next;
|
|
528
|
+
} while (cursor !== undefined);
|
|
529
|
+
return { rows, hidden, hiddenDone, hiddenCancelled };
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/** The rows of one level across the types of a plugin, each tagged with its type. */
|
|
533
|
+
async function fetchTypes(
|
|
534
|
+
tab: TuiTab,
|
|
535
|
+
level: TuiLevel,
|
|
536
|
+
signal: AbortSignal,
|
|
537
|
+
filter: string | undefined,
|
|
538
|
+
): Promise<{
|
|
539
|
+
readonly entries: readonly TuiTreeEntry[];
|
|
540
|
+
readonly hidden: number;
|
|
541
|
+
readonly hiddenDone: number;
|
|
542
|
+
readonly hiddenCancelled: number;
|
|
543
|
+
}> {
|
|
544
|
+
const per = await Promise.all(
|
|
545
|
+
(tab.types ?? []).map(async (info) => {
|
|
546
|
+
const named = tab.filters?.some((f) => f.name === filter) === true;
|
|
547
|
+
const asked = named && info.filters?.some((f) => f.name === filter) === true ? filter : undefined;
|
|
548
|
+
const found = await fetchLevel(info.type, level, signal, asked);
|
|
549
|
+
return {
|
|
550
|
+
hidden: found.hidden,
|
|
551
|
+
hiddenDone: found.hiddenDone,
|
|
552
|
+
hiddenCancelled: found.hiddenCancelled,
|
|
553
|
+
entries: found.rows.map((row): TuiTreeEntry => ({ row, type: info.type })),
|
|
554
|
+
};
|
|
555
|
+
}),
|
|
556
|
+
);
|
|
557
|
+
return {
|
|
558
|
+
entries: per.flatMap((one) => one.entries),
|
|
559
|
+
hidden: per.reduce((total, one) => total + one.hidden, 0),
|
|
560
|
+
hiddenDone: per.reduce((total, one) => total + one.hiddenDone, 0),
|
|
561
|
+
hiddenCancelled: per.reduce((total, one) => total + one.hiddenCancelled, 0),
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* A plugin tab's list: its top-level objects, the objects whose parent is an
|
|
567
|
+
* object of another plugin (grouped under that parent), and, when at least
|
|
568
|
+
* one top-level object has a next level, that level grouped under it (one
|
|
569
|
+
* with nothing under it stays as its own group row).
|
|
570
|
+
*/
|
|
571
|
+
async function fetchPluginRows(
|
|
572
|
+
tab: TuiTab,
|
|
573
|
+
signal: AbortSignal,
|
|
574
|
+
filter: string | undefined,
|
|
575
|
+
): Promise<{
|
|
576
|
+
readonly level: "roots" | "children";
|
|
577
|
+
readonly entries: readonly TuiTreeEntry[];
|
|
578
|
+
readonly hidden: number;
|
|
579
|
+
}> {
|
|
580
|
+
const all = await fetchTypes(tab, {}, signal, filter);
|
|
581
|
+
const own = new Set<string>();
|
|
582
|
+
for (const entry of all.entries) {
|
|
583
|
+
for (const form of parentForms(entry)) own.add(form);
|
|
584
|
+
}
|
|
585
|
+
const roots = all.entries.filter(
|
|
586
|
+
(entry) => entry.row.parent === undefined || entry.row.parent.length === 0,
|
|
587
|
+
);
|
|
588
|
+
const ownTypes = new Set((tab.types ?? []).map((info) => info.type));
|
|
589
|
+
const byForm = new Map<string, TuiTreeEntry>();
|
|
590
|
+
for (const entry of all.entries) {
|
|
591
|
+
for (const form of parentForms(entry)) {
|
|
592
|
+
if (!byForm.has(form)) byForm.set(form, entry);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
// The first ancestor outside the tab names the group. A tab-owned object
|
|
596
|
+
// under a foreign one belongs to the same group, as do its own children.
|
|
597
|
+
const foreignGroupOf = (
|
|
598
|
+
entry: TuiTreeEntry,
|
|
599
|
+
seen: ReadonlySet<TuiTreeEntry>,
|
|
600
|
+
): string | undefined => {
|
|
601
|
+
const parent = entry.row.parent;
|
|
602
|
+
if (parent === undefined || parent.length === 0) return undefined;
|
|
603
|
+
const colon = parent.indexOf(":");
|
|
604
|
+
const parentType = colon > 0 ? parent.slice(0, colon) : undefined;
|
|
605
|
+
if (parentType !== undefined && !ownTypes.has(parentType)) return parent;
|
|
606
|
+
if (parentType === undefined && !own.has(parent)) return parent;
|
|
607
|
+
const owner = byForm.get(parent);
|
|
608
|
+
if (owner === undefined || seen.has(owner)) return undefined;
|
|
609
|
+
return foreignGroupOf(owner, new Set([...seen, owner]));
|
|
610
|
+
};
|
|
611
|
+
const foreign = new Map<string, TuiTreeEntry[]>();
|
|
612
|
+
for (const entry of all.entries) {
|
|
613
|
+
const parent = foreignGroupOf(entry, new Set([entry]));
|
|
614
|
+
if (parent === undefined) continue;
|
|
615
|
+
const group = foreign.get(parent);
|
|
616
|
+
if (group === undefined) foreign.set(parent, [entry]);
|
|
617
|
+
else group.push(entry);
|
|
618
|
+
}
|
|
619
|
+
const under = roots.map((root) => {
|
|
620
|
+
const forms = new Set(parentForms(root));
|
|
621
|
+
return all.entries.filter((entry) => {
|
|
622
|
+
const parent = entry.row.parent;
|
|
623
|
+
return parent !== undefined && forms.has(parent);
|
|
624
|
+
});
|
|
625
|
+
});
|
|
626
|
+
// The hidden rows the sidebar counts are the roots' next level only: a
|
|
627
|
+
// hidden task under a plan is not part of the repository's group row.
|
|
628
|
+
const childLevels = await Promise.all(
|
|
629
|
+
roots.map((root) =>
|
|
630
|
+
fetchTypes(tab, { parent: `${root.type}:${rowFromView(root.row).id}` }, signal, filter),
|
|
631
|
+
),
|
|
632
|
+
);
|
|
633
|
+
const underHidden = childLevels.reduce((total, one) => total + one.hidden, 0);
|
|
634
|
+
// A type with filters can hide every child of a root; the list then still
|
|
635
|
+
// groups under the roots.
|
|
636
|
+
const some = under.some((rows) => rows.length > 0) || underHidden > 0;
|
|
637
|
+
if (!some && foreign.size === 0) {
|
|
638
|
+
const hidden =
|
|
639
|
+
(tab.types?.length ?? 0) > 1 && all.hidden > 0
|
|
640
|
+
? (await fetchTypes(tab, { root: true }, signal, filter)).hidden
|
|
641
|
+
: all.hidden;
|
|
642
|
+
return { level: "roots", entries: roots, hidden };
|
|
643
|
+
}
|
|
644
|
+
const entries: TuiTreeEntry[] = [];
|
|
645
|
+
roots.forEach((root, index) => {
|
|
646
|
+
const rows = under[index] ?? [];
|
|
647
|
+
if (rows.length === 0) {
|
|
648
|
+
entries.push({ row: root.row, type: root.type, bare: true });
|
|
649
|
+
return;
|
|
650
|
+
}
|
|
651
|
+
const parent = rowFromView(root.row).id;
|
|
652
|
+
rows.forEach((entry, at) => {
|
|
653
|
+
entries.push({
|
|
654
|
+
...entry,
|
|
655
|
+
parent,
|
|
656
|
+
...(at === 0 ? { heading: { row: root.row, type: root.type } } : {}),
|
|
657
|
+
});
|
|
658
|
+
});
|
|
659
|
+
});
|
|
660
|
+
for (const [parent, rows] of foreign) {
|
|
661
|
+
[...rows].sort(newestFirst).forEach((entry, at) => {
|
|
662
|
+
entries.push({
|
|
663
|
+
...entry,
|
|
664
|
+
parent,
|
|
665
|
+
...(at === 0 ? { heading: foreignHeading(parent) } : {}),
|
|
666
|
+
});
|
|
667
|
+
});
|
|
668
|
+
}
|
|
669
|
+
return { level: "children", entries, hidden: underHidden };
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/** The spellings a row's parent may use for this object, with or without its type. */
|
|
673
|
+
function parentForms(entry: TuiTreeEntry): readonly string[] {
|
|
674
|
+
const id = rowFromView(entry.row).id;
|
|
675
|
+
const raw = entry.row.id;
|
|
676
|
+
return [...new Set([id, `${entry.type}:${id}`, raw, `${entry.type}:${raw}`])];
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
/** A heading for objects whose parent belongs to another plugin. */
|
|
680
|
+
function foreignHeading(parent: string): {
|
|
681
|
+
readonly row: ViewRow;
|
|
682
|
+
readonly type: string;
|
|
683
|
+
readonly label: string;
|
|
684
|
+
} {
|
|
685
|
+
const colon = parent.indexOf(":");
|
|
686
|
+
return {
|
|
687
|
+
row: { id: parent, title: parent, state: "", waiting: false, running: false },
|
|
688
|
+
type: colon > 0 ? parent.slice(0, colon) : "",
|
|
689
|
+
label: parent,
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/** The newest object first: ids count up as objects are made. */
|
|
694
|
+
function newestFirst(left: TuiTreeEntry, right: TuiTreeEntry): number {
|
|
695
|
+
const a = rowFromView(left.row).id;
|
|
696
|
+
const b = rowFromView(right.row).id;
|
|
697
|
+
return a < b ? 1 : a > b ? -1 : 0;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* The next level of an open object, from the plugin's other types. It is
|
|
702
|
+
* asked for under the tab's filter, the same one the left list shows, so the
|
|
703
|
+
* page lists and counts only the children that filter shows.
|
|
704
|
+
*/
|
|
705
|
+
async function loadChildren(
|
|
706
|
+
object: ViewObject,
|
|
707
|
+
version: number,
|
|
708
|
+
signal: AbortSignal,
|
|
709
|
+
filter?: string | undefined,
|
|
710
|
+
filterSeq?: number | undefined,
|
|
711
|
+
): Promise<void> {
|
|
712
|
+
const tab = pluginTabOf(state, object.type);
|
|
713
|
+
if (tab === undefined) return;
|
|
714
|
+
const chosen = filter ?? tab.filter;
|
|
715
|
+
const seq = filterSeq ?? tab.filterSeq ?? 0;
|
|
716
|
+
try {
|
|
717
|
+
const found = await fetchTypes(
|
|
718
|
+
tab,
|
|
719
|
+
{ parent: `${object.type}:${object.id}` },
|
|
720
|
+
signal,
|
|
721
|
+
chosen,
|
|
722
|
+
);
|
|
723
|
+
if (signal.aborted || finished) return;
|
|
724
|
+
dispatch({
|
|
725
|
+
type: "children",
|
|
726
|
+
objectId: object.id,
|
|
727
|
+
version,
|
|
728
|
+
entries: found.entries,
|
|
729
|
+
hidden: found.hidden,
|
|
730
|
+
hiddenDone: found.hiddenDone,
|
|
731
|
+
hiddenCancelled: found.hiddenCancelled,
|
|
732
|
+
...(chosen === undefined ? {} : { filter: chosen }),
|
|
733
|
+
filterSeq: seq,
|
|
734
|
+
});
|
|
735
|
+
} catch (error) {
|
|
736
|
+
if (signal.aborted || finished) return;
|
|
737
|
+
noteConnection(error);
|
|
738
|
+
report(error);
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/** The first page of a tab under the filter `f` chose. */
|
|
743
|
+
async function loadFilter(request: TuiFilterRequest): Promise<void> {
|
|
744
|
+
const tab = state.tabs.find((candidate) => candidate.id === request.tabId);
|
|
745
|
+
if (tab?.types === undefined) return;
|
|
746
|
+
try {
|
|
747
|
+
const found = await fetchPluginRows(tab, abort.signal, request.filter);
|
|
748
|
+
if (abort.signal.aborted) return;
|
|
749
|
+
dispatch({
|
|
750
|
+
type: "tree",
|
|
751
|
+
tabId: request.tabId,
|
|
752
|
+
level: found.level,
|
|
753
|
+
entries: found.entries,
|
|
754
|
+
hidden: found.hidden,
|
|
755
|
+
filter: request.filter,
|
|
756
|
+
filterSeq: request.seq,
|
|
757
|
+
});
|
|
758
|
+
// The open object's next level uses the same filter as the left list.
|
|
759
|
+
const current = state.tabs.find((candidate) => candidate.id === request.tabId);
|
|
760
|
+
const object = state.object;
|
|
761
|
+
if (
|
|
762
|
+
current?.filter === request.filter &&
|
|
763
|
+
(current.filterSeq ?? 0) === request.seq &&
|
|
764
|
+
object !== undefined &&
|
|
765
|
+
pluginTabOf(state, object.type)?.id === request.tabId
|
|
766
|
+
) {
|
|
767
|
+
await loadChildren(object, object.version, abort.signal, request.filter, request.seq);
|
|
768
|
+
}
|
|
769
|
+
} catch (error) {
|
|
770
|
+
if (abort.signal.aborted) return;
|
|
771
|
+
noteConnection(error);
|
|
772
|
+
dispatch({ type: "page-error", tabId: request.tabId, message: messageOf(error) });
|
|
773
|
+
report(error);
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
async function refresh(): Promise<void> {
|
|
778
|
+
if (finished) return;
|
|
779
|
+
refreshAbort?.abort();
|
|
780
|
+
const mine = new AbortController();
|
|
781
|
+
refreshAbort = mine;
|
|
782
|
+
const signal = mine.signal;
|
|
783
|
+
dispatch({ type: "refresh-start" });
|
|
784
|
+
const generation = state.generation;
|
|
785
|
+
const objectAtStart = state.object;
|
|
786
|
+
const filtersAtStart = new Map(
|
|
787
|
+
state.tabs.map((tab) => [tab.id, { filter: tab.filter, seq: tab.filterSeq ?? 0 }] as const),
|
|
788
|
+
);
|
|
789
|
+
let failed = false;
|
|
790
|
+
let lost = false;
|
|
791
|
+
|
|
792
|
+
// A request that the next refresh cancelled says nothing.
|
|
793
|
+
const fail = (error: unknown): void => {
|
|
794
|
+
if (signal.aborted || finished) return;
|
|
795
|
+
failed = true;
|
|
796
|
+
if (noteConnection(error)) lost = true;
|
|
797
|
+
dispatch({ type: "status", message: messageOf(error), generation });
|
|
798
|
+
report(error);
|
|
799
|
+
};
|
|
800
|
+
|
|
801
|
+
const asked = Promise.all([
|
|
802
|
+
settle(client.types(signal)),
|
|
803
|
+
settle(client.pending(signal)),
|
|
804
|
+
settle(client.running(signal)),
|
|
805
|
+
// An older server has no keys; the bindings then stay as they were.
|
|
806
|
+
settle(client.keys?.(signal) ?? Promise.resolve(undefined)),
|
|
807
|
+
]);
|
|
808
|
+
const [typesResult, pending, running, keys] = await asked;
|
|
809
|
+
if (keys.ok && keys.value !== undefined) {
|
|
810
|
+
dispatch({ type: "keys", bindings: keys.value, generation });
|
|
811
|
+
}
|
|
812
|
+
if (typesResult.ok) {
|
|
813
|
+
dispatch({ type: "types", types: typesResult.value.types, generation });
|
|
814
|
+
} else {
|
|
815
|
+
fail(typesResult.error);
|
|
816
|
+
}
|
|
817
|
+
if (pending.ok) dispatch({ type: "pending", items: pending.value, generation });
|
|
818
|
+
else fail(pending.error);
|
|
819
|
+
if (running.ok) dispatch({ type: "running", items: running.value, generation });
|
|
820
|
+
else fail(running.error);
|
|
821
|
+
|
|
822
|
+
if (typesResult.ok) {
|
|
823
|
+
await Promise.all(
|
|
824
|
+
state.tabs
|
|
825
|
+
.filter((tab) => tab.kind === "plugin")
|
|
826
|
+
.map(async (tab) => {
|
|
827
|
+
const asked = filtersAtStart.get(tab.id) ?? {
|
|
828
|
+
filter: tab.filter,
|
|
829
|
+
seq: tab.filterSeq ?? 0,
|
|
830
|
+
};
|
|
831
|
+
const filter = asked.filter;
|
|
832
|
+
const result = await settle(fetchPluginRows(tab, signal, filter));
|
|
833
|
+
if (signal.aborted || finished) return;
|
|
834
|
+
if (result.ok) {
|
|
835
|
+
dispatch({
|
|
836
|
+
type: "tree",
|
|
837
|
+
tabId: tab.id,
|
|
838
|
+
level: result.value.level,
|
|
839
|
+
entries: result.value.entries,
|
|
840
|
+
hidden: result.value.hidden,
|
|
841
|
+
generation,
|
|
842
|
+
filter,
|
|
843
|
+
filterSeq: asked.seq,
|
|
844
|
+
});
|
|
845
|
+
} else {
|
|
846
|
+
dispatch({
|
|
847
|
+
type: "page-error",
|
|
848
|
+
tabId: tab.id,
|
|
849
|
+
message: messageOf(result.error),
|
|
850
|
+
});
|
|
851
|
+
fail(result.error);
|
|
852
|
+
}
|
|
853
|
+
}),
|
|
854
|
+
);
|
|
855
|
+
await refreshSettingsObjects(signal, fail, generation);
|
|
856
|
+
}
|
|
857
|
+
await refreshObjectPane(signal, objectAtStart, fail);
|
|
858
|
+
if (signal.aborted || finished) return;
|
|
859
|
+
if (!lost && state.connection !== "unauthorized") {
|
|
860
|
+
dispatch({ type: "connection", connection: "ok" });
|
|
861
|
+
retryAttempt = 0;
|
|
862
|
+
}
|
|
863
|
+
if (!failed) dispatch({ type: "status", generation });
|
|
864
|
+
if (state.connection === "unreachable") scheduleRetry();
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
/** While the server does not answer, ask again with growing waits. */
|
|
868
|
+
function scheduleRetry(): void {
|
|
869
|
+
if (retryCancel !== undefined || finished) return;
|
|
870
|
+
if (state.connection === "unauthorized") return;
|
|
871
|
+
const delay = retryDelay(retryAttempt);
|
|
872
|
+
retryAttempt += 1;
|
|
873
|
+
retryCancel = clock.after(() => {
|
|
874
|
+
retryCancel = undefined;
|
|
875
|
+
requestRefresh();
|
|
876
|
+
}, delay);
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
/** Fetches the targets an event asked for; a lost server asks for everything. */
|
|
880
|
+
async function refetch(targets: Refetch): Promise<void> {
|
|
881
|
+
if (finished || state.connection === "unauthorized") return;
|
|
882
|
+
if (targets.all || state.connection !== "ok") {
|
|
883
|
+
await refresh();
|
|
884
|
+
return;
|
|
885
|
+
}
|
|
886
|
+
const signal = abort.signal;
|
|
887
|
+
const fail = (error: unknown): void => {
|
|
888
|
+
if (signal.aborted || finished) return;
|
|
889
|
+
if (noteConnection(error)) {
|
|
890
|
+
if (state.connection === "unreachable") scheduleRetry();
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
dispatch({ type: "status", message: messageOf(error) });
|
|
894
|
+
report(error);
|
|
895
|
+
};
|
|
896
|
+
const work: Promise<void>[] = [];
|
|
897
|
+
if (targets.lists) {
|
|
898
|
+
work.push(refreshPendingRunning(signal, fail));
|
|
899
|
+
work.push(refreshSettingsObjects(signal, fail));
|
|
900
|
+
}
|
|
901
|
+
for (const id of targets.rows) {
|
|
902
|
+
if (targets.object && state.object !== undefined && sameObject(state.object.id, id)) {
|
|
903
|
+
continue;
|
|
904
|
+
}
|
|
905
|
+
work.push(refreshRow(id, signal, fail));
|
|
906
|
+
}
|
|
907
|
+
if (targets.object) {
|
|
908
|
+
work.push(refreshObjectPane(signal, state.object, fail, false));
|
|
909
|
+
}
|
|
910
|
+
await Promise.all(work);
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/**
|
|
914
|
+
* The top-level objects of every type a plugin put under settings. They are
|
|
915
|
+
* fetched like a tab but never listed in the top bar; the palette shows them.
|
|
916
|
+
*/
|
|
917
|
+
async function refreshSettingsObjects(
|
|
918
|
+
signal: AbortSignal,
|
|
919
|
+
fail?: ((error: unknown) => void) | undefined,
|
|
920
|
+
generation?: number | undefined,
|
|
921
|
+
): Promise<void> {
|
|
922
|
+
const tab = state.settingsTab;
|
|
923
|
+
if (tab === undefined) return;
|
|
924
|
+
try {
|
|
925
|
+
const per = await Promise.all(
|
|
926
|
+
(tab.types ?? []).map(async (info) => {
|
|
927
|
+
const found = await fetchLevel(info.type, { root: true }, signal);
|
|
928
|
+
return found.rows.map((row): TuiTreeEntry => ({ row, type: info.type }));
|
|
929
|
+
}),
|
|
930
|
+
);
|
|
931
|
+
if (signal.aborted || finished) return;
|
|
932
|
+
dispatch({
|
|
933
|
+
type: "settings-objects",
|
|
934
|
+
entries: per.flat(),
|
|
935
|
+
...(generation === undefined ? {} : { generation }),
|
|
936
|
+
});
|
|
937
|
+
} catch (error) {
|
|
938
|
+
if (signal.aborted || finished) return;
|
|
939
|
+
if (noteConnection(error)) return;
|
|
940
|
+
fail?.(error);
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
async function refreshPendingRunning(
|
|
945
|
+
signal: AbortSignal,
|
|
946
|
+
fail: (error: unknown) => void,
|
|
947
|
+
): Promise<void> {
|
|
948
|
+
const [pending, running] = await Promise.all([
|
|
949
|
+
settle(client.pending(signal)),
|
|
950
|
+
settle(client.running(signal)),
|
|
951
|
+
]);
|
|
952
|
+
if (signal.aborted || finished) return;
|
|
953
|
+
if (pending.ok) dispatch({ type: "pending", items: pending.value });
|
|
954
|
+
else fail(pending.error);
|
|
955
|
+
if (running.ok) dispatch({ type: "running", items: running.value });
|
|
956
|
+
else fail(running.error);
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
/**
|
|
960
|
+
* The typed id of an object a pending, running or settings row names, for an
|
|
961
|
+
* event that publishes the bare id. Pending and running ids are already
|
|
962
|
+
* `<type>:<id>`; a settings row carries its type beside a bare id.
|
|
963
|
+
*/
|
|
964
|
+
function typedFromLists(id: string): string | undefined {
|
|
965
|
+
const tabs = [
|
|
966
|
+
...state.tabs.filter((tab) => tab.kind === "pending" || tab.kind === "running"),
|
|
967
|
+
...(state.settingsTab === undefined ? [] : [state.settingsTab]),
|
|
968
|
+
];
|
|
969
|
+
for (const tab of tabs) {
|
|
970
|
+
for (const row of tab.list.rows) {
|
|
971
|
+
if (!sameObject(row.id, id)) continue;
|
|
972
|
+
if (row.id.includes(":")) return row.id;
|
|
973
|
+
if (row.type !== undefined) return `${row.type}:${row.id}`;
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
return undefined;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
/**
|
|
980
|
+
* Fetches one row again. An object that no open list holds yet (a new one)
|
|
981
|
+
* refetches the list of its type instead.
|
|
982
|
+
*/
|
|
983
|
+
async function refreshRow(
|
|
984
|
+
id: string,
|
|
985
|
+
signal: AbortSignal,
|
|
986
|
+
fail: (error: unknown) => void,
|
|
987
|
+
): Promise<void> {
|
|
988
|
+
const read = client.object;
|
|
989
|
+
if (read === undefined) return;
|
|
990
|
+
// The server publishes a bare id. The list row it names knows the type, so
|
|
991
|
+
// the request is scoped the same way an open row's request is.
|
|
992
|
+
const page = state.object;
|
|
993
|
+
const knownRow =
|
|
994
|
+
state.tabs
|
|
995
|
+
.filter((tab) => tab.kind === "plugin")
|
|
996
|
+
.flatMap((tab) => tab.list.rows)
|
|
997
|
+
.find((row) => sameObject(row.id, id)) ??
|
|
998
|
+
page?.children?.rows.find((row) => sameObject(row.id, id));
|
|
999
|
+
const requestId =
|
|
1000
|
+
knownRow?.type !== undefined && !knownRow.id.startsWith(`${knownRow.type}:`)
|
|
1001
|
+
? `${knownRow.type}:${knownRow.id}`
|
|
1002
|
+
: knownRow?.id ?? typedFromLists(id) ?? wire(id);
|
|
1003
|
+
const result = await settle(read.call(client, requestId, signal));
|
|
1004
|
+
if (signal.aborted || finished) return;
|
|
1005
|
+
if (!result.ok) {
|
|
1006
|
+
// An object that is gone from the server is not a failure of the screen.
|
|
1007
|
+
if (result.error instanceof TuiError && result.error.status === 404) {
|
|
1008
|
+
dispatch({ type: "row-gone", id });
|
|
1009
|
+
} else {
|
|
1010
|
+
fail(result.error);
|
|
1011
|
+
}
|
|
1012
|
+
return;
|
|
1013
|
+
}
|
|
1014
|
+
const known = knownRow !== undefined;
|
|
1015
|
+
// A child on the open page: its row there is refreshed, and a new child is read in.
|
|
1016
|
+
const onPage = page?.children?.rows.some((row) => sameObject(row.id, id)) === true;
|
|
1017
|
+
const parent = result.value.row.parent;
|
|
1018
|
+
const underPage =
|
|
1019
|
+
page !== undefined &&
|
|
1020
|
+
parent !== undefined &&
|
|
1021
|
+
(parent === page.id || parent === `${page.type}:${page.id}`);
|
|
1022
|
+
if (known || onPage) {
|
|
1023
|
+
dispatch({ type: "row", row: result.value.row });
|
|
1024
|
+
// The row is held already: its change needs no refetch of the lists.
|
|
1025
|
+
return;
|
|
1026
|
+
}
|
|
1027
|
+
if (underPage && page !== undefined && !onPage) {
|
|
1028
|
+
await loadChildren(
|
|
1029
|
+
{ ...result.value, id: page.id, type: page.type },
|
|
1030
|
+
page.version,
|
|
1031
|
+
signal,
|
|
1032
|
+
);
|
|
1033
|
+
return;
|
|
1034
|
+
}
|
|
1035
|
+
const tab = pluginTabOf(state, result.value.type);
|
|
1036
|
+
if (tab === undefined) return;
|
|
1037
|
+
if (tab.kind === "settings") {
|
|
1038
|
+
await refreshSettingsObjects(signal, fail);
|
|
1039
|
+
return;
|
|
1040
|
+
}
|
|
1041
|
+
const filter = tab.filter;
|
|
1042
|
+
const filterSeq = tab.filterSeq ?? 0;
|
|
1043
|
+
const found = await settle(fetchPluginRows(tab, signal, filter));
|
|
1044
|
+
if (signal.aborted || finished) return;
|
|
1045
|
+
if (found.ok) {
|
|
1046
|
+
dispatch({
|
|
1047
|
+
type: "tree",
|
|
1048
|
+
tabId: tab.id,
|
|
1049
|
+
level: found.value.level,
|
|
1050
|
+
entries: found.value.entries,
|
|
1051
|
+
hidden: found.value.hidden,
|
|
1052
|
+
filter,
|
|
1053
|
+
filterSeq,
|
|
1054
|
+
});
|
|
1055
|
+
} else fail(found.error);
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
/** Fetches the open object again, and the live sections it shows. */
|
|
1059
|
+
async function refreshObjectPane(
|
|
1060
|
+
signal: AbortSignal,
|
|
1061
|
+
objectAtStart: TuiObject | undefined,
|
|
1062
|
+
fail: (error: unknown) => void,
|
|
1063
|
+
whole = true,
|
|
1064
|
+
): Promise<void> {
|
|
1065
|
+
const open = state.object;
|
|
1066
|
+
if (
|
|
1067
|
+
open !== undefined &&
|
|
1068
|
+
objectAtStart !== undefined &&
|
|
1069
|
+
open.id === objectAtStart.id &&
|
|
1070
|
+
open.version === objectAtStart.version &&
|
|
1071
|
+
!open.loading &&
|
|
1072
|
+
client.object !== undefined &&
|
|
1073
|
+
!signal.aborted &&
|
|
1074
|
+
!finished
|
|
1075
|
+
) {
|
|
1076
|
+
// A whole read (after `r` or a reconnect) is authoritative: the deltas in
|
|
1077
|
+
// flight were asked from the content it is about to replace.
|
|
1078
|
+
if (whole) {
|
|
1079
|
+
for (const request of afterReads) request.abort();
|
|
1080
|
+
afterReads.clear();
|
|
1081
|
+
}
|
|
1082
|
+
const id = open.id;
|
|
1083
|
+
const version = open.version;
|
|
1084
|
+
// The object's own requests end with it (Esc, another open), not only
|
|
1085
|
+
// with this refresh.
|
|
1086
|
+
const scoped = new AbortController();
|
|
1087
|
+
const stop = (): void => scoped.abort();
|
|
1088
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
1089
|
+
objectRequests.add(scoped);
|
|
1090
|
+
if (!whole) afterReads.add(scoped);
|
|
1091
|
+
try {
|
|
1092
|
+
const result = await settle(client.object(wire(id), scoped.signal));
|
|
1093
|
+
if (!scoped.signal.aborted && !finished) {
|
|
1094
|
+
if (result.ok) {
|
|
1095
|
+
dispatch({ type: "object", object: result.value, version });
|
|
1096
|
+
dispatch({ type: "row", row: result.value.row });
|
|
1097
|
+
await loadChildren(result.value, version, scoped.signal);
|
|
1098
|
+
const current = state.object;
|
|
1099
|
+
const live =
|
|
1100
|
+
current?.sections.filter(
|
|
1101
|
+
(section) => section.live && section.loaded && !section.loading,
|
|
1102
|
+
) ?? [];
|
|
1103
|
+
const load = client.section;
|
|
1104
|
+
if (load !== undefined) {
|
|
1105
|
+
const lost = (
|
|
1106
|
+
error: unknown,
|
|
1107
|
+
objectId: string,
|
|
1108
|
+
sectionId: string,
|
|
1109
|
+
sectionVersion: number,
|
|
1110
|
+
objectVersion: number,
|
|
1111
|
+
): void => {
|
|
1112
|
+
if (!noteConnection(error)) {
|
|
1113
|
+
dispatch({
|
|
1114
|
+
type: "section-error",
|
|
1115
|
+
objectId,
|
|
1116
|
+
sectionId,
|
|
1117
|
+
message: messageOf(error),
|
|
1118
|
+
version: sectionVersion,
|
|
1119
|
+
objectVersion,
|
|
1120
|
+
});
|
|
1121
|
+
}
|
|
1122
|
+
};
|
|
1123
|
+
await Promise.all(
|
|
1124
|
+
live.map(async (section) => {
|
|
1125
|
+
const objectId = current?.id ?? id;
|
|
1126
|
+
const objectVersion = current?.version ?? version;
|
|
1127
|
+
// A live section whose last read gave a mark reads only what
|
|
1128
|
+
// follows it; a whole refresh (after `r` or a reconnect) reads
|
|
1129
|
+
// it again from the start.
|
|
1130
|
+
if (!whole && section.mark !== undefined) {
|
|
1131
|
+
const read = await settle(
|
|
1132
|
+
load.call(client, wire(objectId), section.id, {
|
|
1133
|
+
after: section.mark,
|
|
1134
|
+
...(section.full ? { full: true } : {}),
|
|
1135
|
+
signal: scoped.signal,
|
|
1136
|
+
}),
|
|
1137
|
+
);
|
|
1138
|
+
if (scoped.signal.aborted || finished) return;
|
|
1139
|
+
if (!read.ok) {
|
|
1140
|
+
lost(read.error, objectId, section.id, section.version, objectVersion);
|
|
1141
|
+
return;
|
|
1142
|
+
}
|
|
1143
|
+
dispatch({
|
|
1144
|
+
type: "section",
|
|
1145
|
+
objectId,
|
|
1146
|
+
sectionId: section.id,
|
|
1147
|
+
content: read.value,
|
|
1148
|
+
full: section.full,
|
|
1149
|
+
version: section.version,
|
|
1150
|
+
objectVersion,
|
|
1151
|
+
after: true,
|
|
1152
|
+
});
|
|
1153
|
+
return;
|
|
1154
|
+
}
|
|
1155
|
+
const fetched = await settle(
|
|
1156
|
+
fetchSectionDepth(
|
|
1157
|
+
objectId,
|
|
1158
|
+
section.id,
|
|
1159
|
+
section.pages,
|
|
1160
|
+
section.full,
|
|
1161
|
+
startOf(section),
|
|
1162
|
+
scoped.signal,
|
|
1163
|
+
),
|
|
1164
|
+
);
|
|
1165
|
+
if (scoped.signal.aborted || finished) return;
|
|
1166
|
+
if (!fetched.ok) {
|
|
1167
|
+
lost(fetched.error, objectId, section.id, section.version, objectVersion);
|
|
1168
|
+
return;
|
|
1169
|
+
}
|
|
1170
|
+
if (fetched.value === undefined) return;
|
|
1171
|
+
dispatch({
|
|
1172
|
+
type: "section",
|
|
1173
|
+
objectId,
|
|
1174
|
+
sectionId: section.id,
|
|
1175
|
+
content: fetched.value.content,
|
|
1176
|
+
pages: fetched.value.pages,
|
|
1177
|
+
marks: fetched.value.marks,
|
|
1178
|
+
start: startOf(section).index,
|
|
1179
|
+
full: section.full,
|
|
1180
|
+
version: section.version,
|
|
1181
|
+
objectVersion,
|
|
1182
|
+
});
|
|
1183
|
+
}),
|
|
1184
|
+
);
|
|
1185
|
+
}
|
|
1186
|
+
} else {
|
|
1187
|
+
if (result.error instanceof TuiError && result.error.status === 404) {
|
|
1188
|
+
dispatch({ type: "row-gone", id });
|
|
1189
|
+
}
|
|
1190
|
+
dispatch({
|
|
1191
|
+
type: "object-error",
|
|
1192
|
+
id,
|
|
1193
|
+
message: messageOf(result.error),
|
|
1194
|
+
version,
|
|
1195
|
+
});
|
|
1196
|
+
fail(result.error);
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
} finally {
|
|
1200
|
+
signal.removeEventListener("abort", stop);
|
|
1201
|
+
objectRequests.delete(scoped);
|
|
1202
|
+
afterReads.delete(scoped);
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
/** Sends one action; a success refreshes the object and its list row. */
|
|
1208
|
+
async function sendAction(request: TuiActionRequest): Promise<void> {
|
|
1209
|
+
const act = client.act;
|
|
1210
|
+
if (act === undefined) {
|
|
1211
|
+
dispatch({ type: "action-error", message: "this client cannot run actions" });
|
|
1212
|
+
return;
|
|
1213
|
+
}
|
|
1214
|
+
try {
|
|
1215
|
+
const ran = await act.call(client, {
|
|
1216
|
+
action: request.action,
|
|
1217
|
+
id: wire(request.id),
|
|
1218
|
+
...(request.note === undefined ? {} : { note: request.note }),
|
|
1219
|
+
...(request.args === undefined ? {} : { args: request.args }),
|
|
1220
|
+
...(request.confirmed === true ? { confirmed: true } : {}),
|
|
1221
|
+
signal: abort.signal,
|
|
1222
|
+
});
|
|
1223
|
+
if (abort.signal.aborted) return;
|
|
1224
|
+
dispatch({ type: "action-done", ...settledNotice(ran) });
|
|
1225
|
+
requestRefresh();
|
|
1226
|
+
} catch (error) {
|
|
1227
|
+
if (abort.signal.aborted) return;
|
|
1228
|
+
if (error instanceof TuiError && error.status !== undefined) {
|
|
1229
|
+
deps.onLog?.(`action ${request.action} ${request.id}: ${error.status} ${messageOf(error)}`);
|
|
1230
|
+
}
|
|
1231
|
+
dispatch({
|
|
1232
|
+
type: "action-error",
|
|
1233
|
+
message: messageOf(error),
|
|
1234
|
+
status: error instanceof TuiError ? error.status : undefined,
|
|
1235
|
+
});
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
/** Sends one answer; a success refreshes the pending list. */
|
|
1240
|
+
async function sendAnswer(request: TuiAnswerRequest): Promise<void> {
|
|
1241
|
+
const answer = client.answer;
|
|
1242
|
+
if (answer === undefined) {
|
|
1243
|
+
dispatch({ type: "action-error", message: "this client cannot answer questions" });
|
|
1244
|
+
return;
|
|
1245
|
+
}
|
|
1246
|
+
try {
|
|
1247
|
+
await answer.call(client, { ...request, signal: abort.signal });
|
|
1248
|
+
if (abort.signal.aborted) return;
|
|
1249
|
+
dispatch({ type: "action-done" });
|
|
1250
|
+
requestRefresh();
|
|
1251
|
+
} catch (error) {
|
|
1252
|
+
if (abort.signal.aborted) return;
|
|
1253
|
+
if (error instanceof TuiError && error.status !== undefined) {
|
|
1254
|
+
deps.onLog?.(`answer ${request.runId} ${request.waitId}: ${error.status} ${messageOf(error)}`);
|
|
1255
|
+
}
|
|
1256
|
+
dispatch({
|
|
1257
|
+
type: "action-error",
|
|
1258
|
+
message: messageOf(error),
|
|
1259
|
+
status: error instanceof TuiError ? error.status : undefined,
|
|
1260
|
+
});
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
/** Reads the settings of the scopes the palette lists; a scope that cannot be read adds none. */
|
|
1265
|
+
async function loadSettings(): Promise<void> {
|
|
1266
|
+
const list = client.settings;
|
|
1267
|
+
if (list === undefined) {
|
|
1268
|
+
await refreshSettingsObjects(abort.signal);
|
|
1269
|
+
return;
|
|
1270
|
+
}
|
|
1271
|
+
const scopes = settingScopes(state);
|
|
1272
|
+
const found = await Promise.all(
|
|
1273
|
+
scopes.map((scope) => settle(list.call(client, scope, abort.signal))),
|
|
1274
|
+
);
|
|
1275
|
+
if (abort.signal.aborted || finished) return;
|
|
1276
|
+
dispatch({
|
|
1277
|
+
type: "settings",
|
|
1278
|
+
settings: found.flatMap((result) => (result.ok ? result.value : [])),
|
|
1279
|
+
});
|
|
1280
|
+
await refreshSettingsObjects(abort.signal);
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
/** Sends one setting change; the server's refusal comes back as the footer notice. */
|
|
1284
|
+
async function sendSetting(request: TuiSettingRequest): Promise<void> {
|
|
1285
|
+
const set = client.setSetting;
|
|
1286
|
+
if (set === undefined) {
|
|
1287
|
+
dispatch({ type: "action-error", message: "this client cannot change settings" });
|
|
1288
|
+
return;
|
|
1289
|
+
}
|
|
1290
|
+
try {
|
|
1291
|
+
await set.call(client, {
|
|
1292
|
+
name: request.name,
|
|
1293
|
+
value: request.value,
|
|
1294
|
+
scope: request.scope,
|
|
1295
|
+
...(request.confirmed === true ? { confirmed: true } : {}),
|
|
1296
|
+
signal: abort.signal,
|
|
1297
|
+
});
|
|
1298
|
+
if (abort.signal.aborted) return;
|
|
1299
|
+
dispatch({ type: "action-done" });
|
|
1300
|
+
await loadSettings();
|
|
1301
|
+
} catch (error) {
|
|
1302
|
+
if (abort.signal.aborted) return;
|
|
1303
|
+
dispatch({
|
|
1304
|
+
type: "action-error",
|
|
1305
|
+
message: messageOf(error),
|
|
1306
|
+
status: error instanceof TuiError ? error.status : undefined,
|
|
1307
|
+
});
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
function requestRefresh(): void {
|
|
1312
|
+
if (finished) return;
|
|
1313
|
+
guard(refresh());
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
function dispatch(event: TuiStateEvent): void {
|
|
1317
|
+
if (finished) return;
|
|
1318
|
+
const before = state.recent;
|
|
1319
|
+
state = reduce(state, event);
|
|
1320
|
+
if (state.recent !== before) deps.onRecent?.(state.recent);
|
|
1321
|
+
// A request is asked for once: it leaves the state as it is launched.
|
|
1322
|
+
const request = state.pageRequest;
|
|
1323
|
+
if (request !== undefined) state = reduce(state, { type: "page-launched" });
|
|
1324
|
+
const objectRequest = state.objectRequest;
|
|
1325
|
+
if (objectRequest !== undefined) {
|
|
1326
|
+
state = reduce(state, { type: "object-launched" });
|
|
1327
|
+
}
|
|
1328
|
+
const sectionRequest = state.sectionRequest;
|
|
1329
|
+
if (sectionRequest !== undefined) {
|
|
1330
|
+
state = reduce(state, { type: "section-launched" });
|
|
1331
|
+
}
|
|
1332
|
+
const filterRequest = state.filterRequest;
|
|
1333
|
+
if (filterRequest !== undefined) state = reduce(state, { type: "filter-launched" });
|
|
1334
|
+
const actionRequest = state.actionRequest;
|
|
1335
|
+
if (actionRequest !== undefined) state = reduce(state, { type: "action-launched" });
|
|
1336
|
+
const answerRequest = state.answerRequest;
|
|
1337
|
+
if (answerRequest !== undefined) state = reduce(state, { type: "answer-launched" });
|
|
1338
|
+
const settingRequest = state.settingRequest;
|
|
1339
|
+
const settingsRequested = state.settingsRequest;
|
|
1340
|
+
if (settingRequest !== undefined || settingsRequested) {
|
|
1341
|
+
state = reduce(state, { type: "setting-launched" });
|
|
1342
|
+
}
|
|
1343
|
+
const themes = deps.themes;
|
|
1344
|
+
if (themes !== undefined) {
|
|
1345
|
+
const problem = (error: unknown): void => {
|
|
1346
|
+
state = reduce(state, { type: "status", message: `${THEME_PROBLEM} ${messageOf(error)}` });
|
|
1347
|
+
};
|
|
1348
|
+
if (state.themePreview !== shownPreview) {
|
|
1349
|
+
shownPreview = state.themePreview;
|
|
1350
|
+
try {
|
|
1351
|
+
themes.preview(shownPreview);
|
|
1352
|
+
} catch (error) {
|
|
1353
|
+
problem(error);
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
const asked = state.themeRequest;
|
|
1357
|
+
if (asked !== undefined) {
|
|
1358
|
+
state = reduce(state, { type: "theme-launched" });
|
|
1359
|
+
try {
|
|
1360
|
+
themes.save(asked);
|
|
1361
|
+
} catch (error) {
|
|
1362
|
+
problem(error);
|
|
1363
|
+
}
|
|
1364
|
+
state = reduce(state, { type: "theme-names", names: themes.list(), current: themes.current() });
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
const layoutAsked = state.layoutRequest;
|
|
1368
|
+
if (layoutAsked !== undefined) {
|
|
1369
|
+
state = reduce(state, { type: "layout-launched" });
|
|
1370
|
+
try {
|
|
1371
|
+
deps.onChildLayout?.(layoutAsked);
|
|
1372
|
+
} catch (error) {
|
|
1373
|
+
state = reduce(state, { type: "status", message: `layout not saved: ${messageOf(error)}` });
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
const refreshing = state.refreshRequested;
|
|
1377
|
+
if (refreshing) state = reduce(state, { type: "refreshed" });
|
|
1378
|
+
// Requests belong to the object version that asked: another open, or a
|
|
1379
|
+
// close, ends them.
|
|
1380
|
+
if (state.object?.version !== seenObject) {
|
|
1381
|
+
seenObject = state.object?.version;
|
|
1382
|
+
for (const pending of objectRequests) pending.abort();
|
|
1383
|
+
objectRequests.clear();
|
|
1384
|
+
}
|
|
1385
|
+
if (state.moveSeq !== seenMove) {
|
|
1386
|
+
seenMove = state.moveSeq;
|
|
1387
|
+
followTimer?.();
|
|
1388
|
+
followTimer = state.followPending
|
|
1389
|
+
? clock.after(() => {
|
|
1390
|
+
followTimer = undefined;
|
|
1391
|
+
dispatch({ type: "follow" });
|
|
1392
|
+
}, deps.followDelayMs ?? 150)
|
|
1393
|
+
: undefined;
|
|
1394
|
+
}
|
|
1395
|
+
view.render(state);
|
|
1396
|
+
if (state.quit) {
|
|
1397
|
+
finish();
|
|
1398
|
+
return;
|
|
1399
|
+
}
|
|
1400
|
+
if (filterRequest !== undefined) guard(loadFilter(filterRequest));
|
|
1401
|
+
if (objectRequest !== undefined) guard(loadObject(objectRequest));
|
|
1402
|
+
if (sectionRequest !== undefined) guard(loadSection(sectionRequest));
|
|
1403
|
+
if (actionRequest !== undefined) guard(sendAction(actionRequest));
|
|
1404
|
+
if (answerRequest !== undefined) guard(sendAnswer(answerRequest));
|
|
1405
|
+
if (settingRequest !== undefined) guard(sendSetting(settingRequest));
|
|
1406
|
+
if (settingsRequested) guard(loadSettings());
|
|
1407
|
+
if (refreshing) requestRefresh();
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1410
|
+
view.render(state);
|
|
1411
|
+
requestRefresh();
|
|
1412
|
+
events = deps.events(abort.signal);
|
|
1413
|
+
const source = events;
|
|
1414
|
+
void (async () => {
|
|
1415
|
+
try {
|
|
1416
|
+
for await (const event of source) {
|
|
1417
|
+
if (finished) break;
|
|
1418
|
+
if (event.kind === "change" || event.kind === "reset") {
|
|
1419
|
+
batcher.push(refetchTargets(event, state.object?.id));
|
|
1420
|
+
} else if (noteConnection(event.error)) {
|
|
1421
|
+
report(event.error);
|
|
1422
|
+
} else {
|
|
1423
|
+
dispatch({ type: "status", message: event.error.message });
|
|
1424
|
+
report(event.error);
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
} catch (error) {
|
|
1428
|
+
// A stream that throws cannot be read again.
|
|
1429
|
+
fatal(error);
|
|
1430
|
+
}
|
|
1431
|
+
})();
|
|
1432
|
+
|
|
1433
|
+
return {
|
|
1434
|
+
get state(): TuiState {
|
|
1435
|
+
return state;
|
|
1436
|
+
},
|
|
1437
|
+
key(input: TuiKeyInput): void {
|
|
1438
|
+
const sequence = input.sequence ?? "";
|
|
1439
|
+
const plain = input.ctrl !== true && input.meta !== true;
|
|
1440
|
+
// A key that types text reaches an input as that text (a space is "space"
|
|
1441
|
+
// by name); a symbol is named by itself, so `?` and `:` bind and match.
|
|
1442
|
+
const text = plain && sequence.length > 0 && !/[\u0000-\u001f\u007f]/.test(sequence)
|
|
1443
|
+
? sequence
|
|
1444
|
+
: undefined;
|
|
1445
|
+
const symbol = text !== undefined && /^[^\p{L}\p{N}\s]$/u.test(text);
|
|
1446
|
+
const name = symbol ? text : input.name;
|
|
1447
|
+
dispatch({
|
|
1448
|
+
type: "key",
|
|
1449
|
+
key: name,
|
|
1450
|
+
text,
|
|
1451
|
+
shift: input.shift,
|
|
1452
|
+
ctrl: input.ctrl,
|
|
1453
|
+
meta: input.meta,
|
|
1454
|
+
});
|
|
1455
|
+
},
|
|
1456
|
+
resize(width: number, height: number): void {
|
|
1457
|
+
dispatch({ type: "resize", width, height });
|
|
1458
|
+
},
|
|
1459
|
+
setTheme(theme: TuiTheme): void {
|
|
1460
|
+
dispatch({ type: "theme", theme });
|
|
1461
|
+
},
|
|
1462
|
+
repaintTheme(problem?: string): void {
|
|
1463
|
+
const themes = deps.themes;
|
|
1464
|
+
if (themes !== undefined) {
|
|
1465
|
+
state = reduce(state, { type: "theme-names", names: themes.list(), current: themes.current() });
|
|
1466
|
+
}
|
|
1467
|
+
if (problem !== undefined) {
|
|
1468
|
+
dispatch({ type: "status", message: `${THEME_PROBLEM} ${problem}` });
|
|
1469
|
+
} else if (state.status?.startsWith(THEME_PROBLEM) === true) {
|
|
1470
|
+
// Clear the line only when it is still ours.
|
|
1471
|
+
dispatch({ type: "status" });
|
|
1472
|
+
} else {
|
|
1473
|
+
dispatch({ type: "theme", theme: state.theme });
|
|
1474
|
+
}
|
|
1475
|
+
},
|
|
1476
|
+
stop: () => finish(),
|
|
1477
|
+
done,
|
|
1478
|
+
};
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
/**
|
|
1482
|
+
* Runs the terminal app until `q`, Ctrl-C or `signal`. It resolves with the
|
|
1483
|
+
* command exit code; a discovery error is thrown before the screen opens. The
|
|
1484
|
+
* terminal is restored whatever happens, and the messages the app collected are
|
|
1485
|
+
* reported after that.
|
|
1486
|
+
*/
|
|
1487
|
+
export async function runTui(options: TuiRunOptions = {}): Promise<number> {
|
|
1488
|
+
// A broken config or an unknown theme stops here, before a server is started.
|
|
1489
|
+
const themeHome = options.home ?? defaultOperadHome();
|
|
1490
|
+
const holder: ThemeHolder = {
|
|
1491
|
+
current: chooseSelection({ home: themeHome, flag: options.theme }),
|
|
1492
|
+
};
|
|
1493
|
+
const childLayout = chooseChildLayout({ home: themeHome });
|
|
1494
|
+
// A theme chosen in the `:` palette beats `--theme` for the rest of the session.
|
|
1495
|
+
let flag = options.theme;
|
|
1496
|
+
const themes: TuiThemes = {
|
|
1497
|
+
list: () => installedThemes(themeHome),
|
|
1498
|
+
current: () => holder.current.name,
|
|
1499
|
+
preview: (name) => {
|
|
1500
|
+
holder.preview = name === undefined ? undefined : resolveSelection(themeHome, name);
|
|
1501
|
+
},
|
|
1502
|
+
save: (name) => {
|
|
1503
|
+
const chosen = resolveSelection(themeHome, name);
|
|
1504
|
+
saveThemeChoice(themeHome, name);
|
|
1505
|
+
flag = undefined;
|
|
1506
|
+
holder.current = chosen;
|
|
1507
|
+
},
|
|
1508
|
+
};
|
|
1509
|
+
// With no --url, make sure a serve answers (starting one) before the screen.
|
|
1510
|
+
if (options.url === undefined && options.noStart !== true) {
|
|
1511
|
+
const home = options.home ?? defaultOperadHome();
|
|
1512
|
+
await (options.hooks?.ensure ?? ensureServer)({
|
|
1513
|
+
home,
|
|
1514
|
+
...(options.hooks?.fetch === undefined ? {} : { fetch: options.hooks.fetch }),
|
|
1515
|
+
...(options.serveEntry === undefined
|
|
1516
|
+
? {}
|
|
1517
|
+
: { spawn: spawnServe(home, options.serveEntry) }),
|
|
1518
|
+
...(options.write === undefined ? {} : { write: options.write }),
|
|
1519
|
+
});
|
|
1520
|
+
}
|
|
1521
|
+
const location = await discoverServer({
|
|
1522
|
+
home: options.home,
|
|
1523
|
+
url: options.url,
|
|
1524
|
+
token: options.token,
|
|
1525
|
+
});
|
|
1526
|
+
const client = new TuiClient(location);
|
|
1527
|
+
const messages: string[] = [];
|
|
1528
|
+
const logs: string[] = [];
|
|
1529
|
+
let renderer: CliRenderer | undefined;
|
|
1530
|
+
let view: TuiView | undefined;
|
|
1531
|
+
let shell: TuiShell | undefined;
|
|
1532
|
+
let code = 0;
|
|
1533
|
+
let stopThemeWatch: (() => void) | undefined;
|
|
1534
|
+
const onAbort = (): void => shell?.stop();
|
|
1535
|
+
const onSignal = (): void => shell?.stop();
|
|
1536
|
+
|
|
1537
|
+
// A callback that throws must not leave the screen up.
|
|
1538
|
+
const guarded = (work: () => void): void => {
|
|
1539
|
+
try {
|
|
1540
|
+
work();
|
|
1541
|
+
} catch (error) {
|
|
1542
|
+
messages.push(messageOf(error));
|
|
1543
|
+
code = 1;
|
|
1544
|
+
shell?.stop();
|
|
1545
|
+
}
|
|
1546
|
+
};
|
|
1547
|
+
|
|
1548
|
+
// The renderer keeps its own handlers that only print; an error nobody
|
|
1549
|
+
// caught ends the app the way every other fault does.
|
|
1550
|
+
// A fault before the shell exists is remembered and stops it as it starts.
|
|
1551
|
+
let faulted = false;
|
|
1552
|
+
const onUncaught = (error: unknown): void => {
|
|
1553
|
+
messages.push(messageOf(error));
|
|
1554
|
+
code = 1;
|
|
1555
|
+
faulted = true;
|
|
1556
|
+
shell?.stop();
|
|
1557
|
+
};
|
|
1558
|
+
process.on("uncaughtException", onUncaught);
|
|
1559
|
+
process.on("unhandledRejection", onUncaught);
|
|
1560
|
+
|
|
1561
|
+
try {
|
|
1562
|
+
const created = await (options.hooks?.renderer?.() ??
|
|
1563
|
+
createCliRenderer({
|
|
1564
|
+
exitOnCtrlC: true,
|
|
1565
|
+
screenMode: "alternate-screen",
|
|
1566
|
+
}));
|
|
1567
|
+
renderer = created;
|
|
1568
|
+
const createdView = (options.hooks?.view ?? ((ctx) => createTuiView(ctx, () => holder.preview ?? holder.current)))(created);
|
|
1569
|
+
view = createdView;
|
|
1570
|
+
const started = startShell({
|
|
1571
|
+
client,
|
|
1572
|
+
url: location.url,
|
|
1573
|
+
themes,
|
|
1574
|
+
recent: loadRecent(themeHome),
|
|
1575
|
+
onRecent: (recent) => saveRecent(themeHome, recent),
|
|
1576
|
+
events: (signal) =>
|
|
1577
|
+
new TuiEvents({ url: location.url, token: location.token, signal }),
|
|
1578
|
+
view: createdView,
|
|
1579
|
+
// Request failures show on the page and are echoed after the screen closes.
|
|
1580
|
+
onMessage: (message) => messages.push(message),
|
|
1581
|
+
onLog: (message) => logs.push(message),
|
|
1582
|
+
width: created.width,
|
|
1583
|
+
height: created.height,
|
|
1584
|
+
theme: themeOf(created, "dark"),
|
|
1585
|
+
childLayout,
|
|
1586
|
+
onChildLayout: (layout) => saveChildLayout(themeHome, layout),
|
|
1587
|
+
onFatal: (message) => {
|
|
1588
|
+
messages.push(message);
|
|
1589
|
+
code = 1;
|
|
1590
|
+
},
|
|
1591
|
+
onFinish: () => {
|
|
1592
|
+
// Close the screen first: nothing may be written under it.
|
|
1593
|
+
try {
|
|
1594
|
+
createdView.destroy();
|
|
1595
|
+
} finally {
|
|
1596
|
+
view = undefined;
|
|
1597
|
+
if (!created.isDestroyed) created.destroy();
|
|
1598
|
+
}
|
|
1599
|
+
},
|
|
1600
|
+
});
|
|
1601
|
+
shell = started;
|
|
1602
|
+
if (faulted) started.stop();
|
|
1603
|
+
stopThemeWatch = watchThemes({
|
|
1604
|
+
home: themeHome,
|
|
1605
|
+
flag: () => flag,
|
|
1606
|
+
holder,
|
|
1607
|
+
onChange: (problem) => guarded(() => started.repaintTheme(problem)),
|
|
1608
|
+
});
|
|
1609
|
+
|
|
1610
|
+
created.keyInput.on("keypress", (key) => {
|
|
1611
|
+
guarded(() => started.key(key));
|
|
1612
|
+
});
|
|
1613
|
+
created.on(CliRenderEvents.RESIZE, () => {
|
|
1614
|
+
guarded(() => started.resize(created.width, created.height));
|
|
1615
|
+
});
|
|
1616
|
+
created.on(CliRenderEvents.THEME_MODE, () => {
|
|
1617
|
+
const theme = created.themeMode;
|
|
1618
|
+
if (theme !== null) guarded(() => started.setTheme(theme));
|
|
1619
|
+
});
|
|
1620
|
+
created.once(CliRenderEvents.DESTROY, () => started.stop());
|
|
1621
|
+
// SIGINT and SIGTERM end the app the way `q` does: the screen is restored
|
|
1622
|
+
// and the event stream closed before the process goes on.
|
|
1623
|
+
for (const name of STOP_SIGNALS) process.on(name, onSignal);
|
|
1624
|
+
if (options.signal !== undefined) {
|
|
1625
|
+
if (options.signal.aborted) started.stop();
|
|
1626
|
+
else options.signal.addEventListener("abort", onAbort, { once: true });
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1629
|
+
await started.done;
|
|
1630
|
+
} catch (error) {
|
|
1631
|
+
messages.push(messageOf(error));
|
|
1632
|
+
code = 1;
|
|
1633
|
+
} finally {
|
|
1634
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
1635
|
+
for (const name of STOP_SIGNALS) process.off(name, onSignal);
|
|
1636
|
+
stopThemeWatch?.();
|
|
1637
|
+
try {
|
|
1638
|
+
shell?.stop();
|
|
1639
|
+
view?.destroy();
|
|
1640
|
+
} catch (error) {
|
|
1641
|
+
messages.push(messageOf(error));
|
|
1642
|
+
code = 1;
|
|
1643
|
+
}
|
|
1644
|
+
if (renderer !== undefined) {
|
|
1645
|
+
if (!renderer.isDestroyed) renderer.destroy();
|
|
1646
|
+
// destroy() only starts the restore (mouse tracking off, keyboard
|
|
1647
|
+
// protocol popped, main screen, cursor); `closed` settles when the
|
|
1648
|
+
// terminal has the bytes. Nothing is written before that.
|
|
1649
|
+
try {
|
|
1650
|
+
await renderer.closed;
|
|
1651
|
+
} catch (error) {
|
|
1652
|
+
messages.push(messageOf(error));
|
|
1653
|
+
code = 1;
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
// Keep the handlers until the screen is closed: a fault during the restore
|
|
1657
|
+
// must not take the process down half way.
|
|
1658
|
+
process.off("uncaughtException", onUncaught);
|
|
1659
|
+
process.off("unhandledRejection", onUncaught);
|
|
1660
|
+
}
|
|
1661
|
+
const onError = options.onError ?? (() => undefined);
|
|
1662
|
+
for (const message of messages) onError(message);
|
|
1663
|
+
for (const line of logs) options.onLog?.(line);
|
|
1664
|
+
return code;
|
|
1665
|
+
}
|