@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.
- package/LICENSE +21 -0
- package/README.md +12 -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/events.ts
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `/v1/events` stream: server-sent events parsed by hand, an opaque
|
|
3
|
+
* `Last-Event-ID` kept across reconnects, one reset signal when the server
|
|
4
|
+
* cannot resume, and a reconnect with capped backoff until the caller stops it.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
defaultFetch,
|
|
9
|
+
httpError,
|
|
10
|
+
TuiUnreachableError,
|
|
11
|
+
type FetchLike,
|
|
12
|
+
type TuiError,
|
|
13
|
+
} from "./client.ts";
|
|
14
|
+
import { isRecord } from "@operad-io/engine";
|
|
15
|
+
|
|
16
|
+
/** The first delay before a reconnect. */
|
|
17
|
+
export const DEFAULT_RETRY_MIN_MS = 250;
|
|
18
|
+
|
|
19
|
+
/** The longest delay between reconnects. */
|
|
20
|
+
export const DEFAULT_RETRY_MAX_MS = 5_000;
|
|
21
|
+
|
|
22
|
+
/** One object changed. */
|
|
23
|
+
export interface TuiChangeEvent {
|
|
24
|
+
readonly kind: "change";
|
|
25
|
+
readonly id: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The server could not resume; refetch the lists and open sections. */
|
|
29
|
+
export interface TuiResetEvent {
|
|
30
|
+
readonly kind: "reset";
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The server refused the stream. `error` is the typed error of the response.
|
|
35
|
+
* After a 401, 404 or 409 the stream ends (a wrong token, or an old or wrong
|
|
36
|
+
* server: retrying cannot help). After a 5xx the stream goes on with backoff,
|
|
37
|
+
* and another error event follows each failed attempt.
|
|
38
|
+
*/
|
|
39
|
+
export interface TuiErrorEvent {
|
|
40
|
+
readonly kind: "error";
|
|
41
|
+
readonly error: TuiError;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* What the event stream yields: `change` (one object changed), `reset` (refetch
|
|
46
|
+
* the lists and open sections; also sent by the client itself when it
|
|
47
|
+
* reconnected with no id to resume from) and `error` (the server refused).
|
|
48
|
+
*/
|
|
49
|
+
export type TuiEvent = TuiChangeEvent | TuiResetEvent | TuiErrorEvent;
|
|
50
|
+
|
|
51
|
+
/** Statuses after which a retry cannot succeed. */
|
|
52
|
+
const FINAL_STATUSES: ReadonlySet<number> = new Set([401, 404, 409]);
|
|
53
|
+
|
|
54
|
+
/** Options for one event stream. */
|
|
55
|
+
export interface TuiEventsOptions {
|
|
56
|
+
readonly url: string;
|
|
57
|
+
readonly token: string;
|
|
58
|
+
readonly fetch?: FetchLike | undefined;
|
|
59
|
+
/** Resume from this opaque id instead of from now. */
|
|
60
|
+
readonly lastEventId?: string | undefined;
|
|
61
|
+
readonly retryMinMs?: number | undefined;
|
|
62
|
+
readonly retryMaxMs?: number | undefined;
|
|
63
|
+
/** Stops the stream from outside, like a screen closing. */
|
|
64
|
+
readonly signal?: AbortSignal | undefined;
|
|
65
|
+
/** Tests inject a wait instead of a real timer. */
|
|
66
|
+
readonly wait?: ((ms: number, signal: AbortSignal) => Promise<void>) | undefined;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The retry delay: double each failure, never past the cap. */
|
|
70
|
+
export function retryDelay(
|
|
71
|
+
attempt: number,
|
|
72
|
+
minMs = DEFAULT_RETRY_MIN_MS,
|
|
73
|
+
maxMs = DEFAULT_RETRY_MAX_MS,
|
|
74
|
+
): number {
|
|
75
|
+
const low = Math.max(0, minMs);
|
|
76
|
+
const high = Math.max(low, maxMs);
|
|
77
|
+
const step = Math.min(Math.max(0, Math.trunc(attempt)), 30);
|
|
78
|
+
return Math.min(high, low * 2 ** step);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Waits for a retry, or ends at once when the stream is stopped. */
|
|
82
|
+
export function waitForRetry(ms: number, signal: AbortSignal): Promise<void> {
|
|
83
|
+
return new Promise<void>((resolve) => {
|
|
84
|
+
if (signal.aborted) {
|
|
85
|
+
resolve();
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
const done = (): void => {
|
|
89
|
+
clearTimeout(timer);
|
|
90
|
+
signal.removeEventListener("abort", done);
|
|
91
|
+
resolve();
|
|
92
|
+
};
|
|
93
|
+
const timer = setTimeout(done, ms);
|
|
94
|
+
signal.addEventListener("abort", done, { once: true });
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
interface SseBlock {
|
|
99
|
+
readonly id: string | undefined;
|
|
100
|
+
readonly event: string;
|
|
101
|
+
readonly data: string;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Reads one SSE block; a comment-only block is undefined. */
|
|
105
|
+
function parseBlock(block: string): SseBlock | undefined {
|
|
106
|
+
let id: string | undefined;
|
|
107
|
+
let event = "message";
|
|
108
|
+
const data: string[] = [];
|
|
109
|
+
let sawField = false;
|
|
110
|
+
for (const line of block.split(/\r?\n/)) {
|
|
111
|
+
if (line.startsWith(":")) continue;
|
|
112
|
+
const colon = line.indexOf(":");
|
|
113
|
+
if (colon < 0) continue;
|
|
114
|
+
sawField = true;
|
|
115
|
+
const field = line.slice(0, colon);
|
|
116
|
+
const value = line.slice(colon + 1).replace(/^ /, "");
|
|
117
|
+
if (field === "id") id = value;
|
|
118
|
+
else if (field === "event") event = value;
|
|
119
|
+
else if (field === "data") data.push(value);
|
|
120
|
+
}
|
|
121
|
+
if (!sawField) return undefined;
|
|
122
|
+
return { id, event, data: data.join("\n") };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** One live event stream; it reconnects until `stop()`. */
|
|
126
|
+
export class TuiEvents implements AsyncIterableIterator<TuiEvent> {
|
|
127
|
+
private readonly baseUrl: string;
|
|
128
|
+
private readonly token: string;
|
|
129
|
+
private readonly fetchImpl: FetchLike;
|
|
130
|
+
private readonly retryMinMs: number;
|
|
131
|
+
private readonly retryMaxMs: number;
|
|
132
|
+
private readonly waitImpl: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
133
|
+
private readonly abort = new AbortController();
|
|
134
|
+
private readonly externalSignal: AbortSignal | undefined;
|
|
135
|
+
private readonly onExternalAbort: () => void;
|
|
136
|
+
private readonly queue: TuiEvent[] = [];
|
|
137
|
+
private readonly waiters: ((result: IteratorResult<TuiEvent>) => void)[] = [];
|
|
138
|
+
private lastId: string | undefined;
|
|
139
|
+
private connectedBefore = false;
|
|
140
|
+
private started = false;
|
|
141
|
+
private closed = false;
|
|
142
|
+
private down = false;
|
|
143
|
+
|
|
144
|
+
constructor(options: TuiEventsOptions) {
|
|
145
|
+
this.baseUrl = options.url.replace(/\/+$/, "");
|
|
146
|
+
this.token = options.token;
|
|
147
|
+
this.fetchImpl = options.fetch ?? defaultFetch;
|
|
148
|
+
this.retryMinMs = options.retryMinMs ?? DEFAULT_RETRY_MIN_MS;
|
|
149
|
+
this.retryMaxMs = options.retryMaxMs ?? DEFAULT_RETRY_MAX_MS;
|
|
150
|
+
this.waitImpl = options.wait ?? waitForRetry;
|
|
151
|
+
this.lastId = options.lastEventId;
|
|
152
|
+
this.externalSignal = options.signal;
|
|
153
|
+
this.onExternalAbort = (): void => {
|
|
154
|
+
this.stop();
|
|
155
|
+
};
|
|
156
|
+
if (options.signal !== undefined) {
|
|
157
|
+
if (options.signal.aborted) this.closed = true;
|
|
158
|
+
else options.signal.addEventListener("abort", this.onExternalAbort, { once: true });
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** The opaque id to resume from; cleared by a reset event. */
|
|
163
|
+
get lastEventId(): string | undefined {
|
|
164
|
+
return this.lastId;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
[Symbol.asyncIterator](): AsyncIterableIterator<TuiEvent> {
|
|
168
|
+
this.start();
|
|
169
|
+
return this;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
next(): Promise<IteratorResult<TuiEvent>> {
|
|
173
|
+
this.start();
|
|
174
|
+
const event = this.queue.shift();
|
|
175
|
+
if (event !== undefined) {
|
|
176
|
+
return Promise.resolve({ done: false, value: event });
|
|
177
|
+
}
|
|
178
|
+
if (this.closed) return Promise.resolve({ done: true, value: undefined });
|
|
179
|
+
return new Promise<IteratorResult<TuiEvent>>((resolve) => {
|
|
180
|
+
this.waiters.push(resolve);
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return(): Promise<IteratorResult<TuiEvent>> {
|
|
185
|
+
this.stop();
|
|
186
|
+
return Promise.resolve({ done: true, value: undefined });
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Stops the stream and ends any waiting `next()`. */
|
|
190
|
+
stop(): void {
|
|
191
|
+
if (this.closed) return;
|
|
192
|
+
this.closed = true;
|
|
193
|
+
this.abort.abort();
|
|
194
|
+
if (this.externalSignal !== undefined) {
|
|
195
|
+
this.externalSignal.removeEventListener("abort", this.onExternalAbort);
|
|
196
|
+
}
|
|
197
|
+
this.settle();
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
private start(): void {
|
|
201
|
+
if (this.started || this.closed) return;
|
|
202
|
+
this.started = true;
|
|
203
|
+
void this.run();
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
private settle(): void {
|
|
207
|
+
for (const resolve of this.waiters.splice(0)) {
|
|
208
|
+
resolve({ done: true, value: undefined });
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
private push(event: TuiEvent): void {
|
|
213
|
+
if (this.closed) return;
|
|
214
|
+
const waiter = this.waiters.shift();
|
|
215
|
+
if (waiter !== undefined) {
|
|
216
|
+
waiter({ done: false, value: event });
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
this.queue.push(event);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
private async run(): Promise<void> {
|
|
223
|
+
let attempt = 0;
|
|
224
|
+
while (!this.closed) {
|
|
225
|
+
let delivered = false;
|
|
226
|
+
try {
|
|
227
|
+
delivered = await this.connect();
|
|
228
|
+
} catch (error) {
|
|
229
|
+
// A refused connection or a dropped stream is retried below, and said
|
|
230
|
+
// once per outage so the app can show it and ask the lists again.
|
|
231
|
+
if (!this.closed && !this.down) {
|
|
232
|
+
this.down = true;
|
|
233
|
+
this.push({
|
|
234
|
+
kind: "error",
|
|
235
|
+
error: new TuiUnreachableError(
|
|
236
|
+
`the event stream to ${this.baseUrl} was lost`,
|
|
237
|
+
error,
|
|
238
|
+
),
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
if (this.closed) break;
|
|
243
|
+
// A server that accepts and then closes without an event is still a
|
|
244
|
+
// failure: only a connection that delivered something resets the backoff.
|
|
245
|
+
if (delivered) attempt = 0;
|
|
246
|
+
const delay = retryDelay(attempt, this.retryMinMs, this.retryMaxMs);
|
|
247
|
+
attempt += 1;
|
|
248
|
+
await this.waitImpl(delay, this.abort.signal);
|
|
249
|
+
}
|
|
250
|
+
this.settle();
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Reads one connection to its end; true when it delivered an event. */
|
|
254
|
+
private async connect(): Promise<boolean> {
|
|
255
|
+
const headers: Record<string, string> = {
|
|
256
|
+
authorization: `Bearer ${this.token}`,
|
|
257
|
+
"x-operad-client": "tui",
|
|
258
|
+
accept: "text/event-stream",
|
|
259
|
+
};
|
|
260
|
+
if (this.lastId !== undefined) headers["last-event-id"] = this.lastId;
|
|
261
|
+
|
|
262
|
+
const response = await this.fetchImpl(`${this.baseUrl}/v1/events`, {
|
|
263
|
+
headers,
|
|
264
|
+
signal: this.abort.signal,
|
|
265
|
+
});
|
|
266
|
+
if (!response.ok) {
|
|
267
|
+
const error = await httpError(response);
|
|
268
|
+
this.push({ kind: "error", error });
|
|
269
|
+
if (error.status !== undefined && FINAL_STATUSES.has(error.status)) {
|
|
270
|
+
this.stop();
|
|
271
|
+
}
|
|
272
|
+
return false;
|
|
273
|
+
}
|
|
274
|
+
if (response.body === null) {
|
|
275
|
+
throw new Error("the event stream has no body");
|
|
276
|
+
}
|
|
277
|
+
// A reconnect with no id asks "from now", and the server then cannot say
|
|
278
|
+
// that events were missed: the client says it.
|
|
279
|
+
if (this.connectedBefore && this.lastId === undefined) {
|
|
280
|
+
this.push({ kind: "reset" });
|
|
281
|
+
}
|
|
282
|
+
this.connectedBefore = true;
|
|
283
|
+
this.down = false;
|
|
284
|
+
|
|
285
|
+
const reader = response.body.getReader();
|
|
286
|
+
const decoder = new TextDecoder();
|
|
287
|
+
let buffer = "";
|
|
288
|
+
let delivered = false;
|
|
289
|
+
try {
|
|
290
|
+
while (!this.closed) {
|
|
291
|
+
const read = await reader.read();
|
|
292
|
+
if (read.done) break;
|
|
293
|
+
buffer += decoder.decode(read.value, { stream: true });
|
|
294
|
+
const drained = this.drain(buffer);
|
|
295
|
+
buffer = drained.remaining;
|
|
296
|
+
delivered = delivered || drained.delivered;
|
|
297
|
+
}
|
|
298
|
+
} finally {
|
|
299
|
+
await reader.cancel().catch(() => undefined);
|
|
300
|
+
}
|
|
301
|
+
// The stream is meant to stay open: an end that was not asked for is a loss.
|
|
302
|
+
if (!this.closed) throw new Error("the event stream ended");
|
|
303
|
+
return delivered;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** Consumes every complete block and returns the unfinished tail. */
|
|
307
|
+
private drain(buffer: string): { remaining: string; delivered: boolean } {
|
|
308
|
+
let remaining = buffer;
|
|
309
|
+
let delivered = false;
|
|
310
|
+
for (;;) {
|
|
311
|
+
const match = /\r?\n\r?\n/.exec(remaining);
|
|
312
|
+
if (match === null) break;
|
|
313
|
+
const block = remaining.slice(0, match.index);
|
|
314
|
+
remaining = remaining.slice(match.index + match[0].length);
|
|
315
|
+
if (this.handleBlock(block)) delivered = true;
|
|
316
|
+
}
|
|
317
|
+
return { remaining, delivered };
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** Handles one block; true when it yielded an event. */
|
|
321
|
+
private handleBlock(block: string): boolean {
|
|
322
|
+
const parsed = parseBlock(block);
|
|
323
|
+
if (parsed === undefined) return false;
|
|
324
|
+
if (parsed.id !== undefined && parsed.id.length > 0) {
|
|
325
|
+
this.lastId = parsed.id;
|
|
326
|
+
}
|
|
327
|
+
if (parsed.event === "reset") {
|
|
328
|
+
// The old id is not resumable. The next connection starts from now, so a
|
|
329
|
+
// second reset does not follow the first.
|
|
330
|
+
this.lastId = undefined;
|
|
331
|
+
this.push({ kind: "reset" });
|
|
332
|
+
return true;
|
|
333
|
+
}
|
|
334
|
+
if (parsed.event !== "message" || parsed.data.length === 0) return false;
|
|
335
|
+
let body: unknown;
|
|
336
|
+
try {
|
|
337
|
+
body = JSON.parse(parsed.data);
|
|
338
|
+
} catch {
|
|
339
|
+
return false;
|
|
340
|
+
}
|
|
341
|
+
if (!isRecord(body) || typeof body.id !== "string") return false;
|
|
342
|
+
this.push({ kind: "change", id: body.id });
|
|
343
|
+
return true;
|
|
344
|
+
}
|
|
345
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** The operad terminal client: `/v1`, discovery, events, state and the view. */
|
|
2
|
+
|
|
3
|
+
export * from "./autostart.ts";
|
|
4
|
+
export * from "./client.ts";
|
|
5
|
+
export * from "./discover.ts";
|
|
6
|
+
export * from "./events.ts";
|
|
7
|
+
export * from "./state.ts";
|
|
8
|
+
export * from "./view/index.ts";
|
|
9
|
+
export * from "./markdown.ts";
|
|
10
|
+
export * from "./app.ts";
|
|
11
|
+
export * from "./live.ts";
|
package/src/layout.ts
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The rows a section takes: the engine's Markdown lines, cleaned of control
|
|
3
|
+
* characters, wrapped by display width. The reducer counts these rows and the
|
|
4
|
+
* view draws a window of them, so they are laid out once per content version
|
|
5
|
+
* and width and kept, not on every key and every render.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { TextAttributes } from "@opentui/core";
|
|
9
|
+
import { renderMarkdownLines } from "@operad-io/engine";
|
|
10
|
+
import { sanitize } from "./sanitize.ts";
|
|
11
|
+
import { graphemes, wrapGlyphs, type WrapGlyph } from "./wrap.ts";
|
|
12
|
+
|
|
13
|
+
/** What a run of text is coloured by; the view maps it to its palette. */
|
|
14
|
+
export type LayoutRole = "add" | "remove" | "accent" | "weak" | undefined;
|
|
15
|
+
|
|
16
|
+
/** The style of a run: a role and the text attributes. */
|
|
17
|
+
export interface LayoutStyle {
|
|
18
|
+
readonly role: LayoutRole;
|
|
19
|
+
readonly attributes: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** A run of text in one style. */
|
|
23
|
+
export interface LayoutRun {
|
|
24
|
+
readonly text: string;
|
|
25
|
+
readonly style: LayoutStyle;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** One drawn row: its runs, its plain text and whether it is fenced code. */
|
|
29
|
+
export interface LayoutLine {
|
|
30
|
+
readonly text: string;
|
|
31
|
+
readonly code: boolean;
|
|
32
|
+
readonly runs: readonly LayoutRun[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function roleFor(code: number): LayoutRole | null {
|
|
36
|
+
switch (code) {
|
|
37
|
+
case 31:
|
|
38
|
+
return "remove";
|
|
39
|
+
case 32:
|
|
40
|
+
return "add";
|
|
41
|
+
case 36:
|
|
42
|
+
return "accent";
|
|
43
|
+
case 90:
|
|
44
|
+
return "weak";
|
|
45
|
+
default:
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Reads the ANSI the engine's renderer emits into styled display characters. */
|
|
51
|
+
function glyphsFor(text: string): WrapGlyph<LayoutStyle>[] {
|
|
52
|
+
const glyphs: WrapGlyph<LayoutStyle>[] = [];
|
|
53
|
+
let role: LayoutRole;
|
|
54
|
+
let attributes = 0;
|
|
55
|
+
const pattern = /\x1b\[([0-9;]*)m/g;
|
|
56
|
+
let at = 0;
|
|
57
|
+
const plain = (value: string): void => {
|
|
58
|
+
// The text was cleaned before it was rendered; what is left of ESC is the
|
|
59
|
+
// renderer's own styles, read below. A tab becomes spaces.
|
|
60
|
+
const effective: LayoutRole = role;
|
|
61
|
+
for (const char of graphemes(value.replace(/\t/g, " "))) {
|
|
62
|
+
glyphs.push({ char, value: { role: effective, attributes } });
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
for (const match of text.matchAll(pattern)) {
|
|
66
|
+
plain(sanitize(text.slice(at, match.index)));
|
|
67
|
+
at = (match.index ?? 0) + match[0].length;
|
|
68
|
+
for (const part of (match[1] ?? "").split(";")) {
|
|
69
|
+
const value = Number(part);
|
|
70
|
+
if (!Number.isFinite(value)) continue;
|
|
71
|
+
if (value === 0) {
|
|
72
|
+
role = undefined;
|
|
73
|
+
attributes = 0;
|
|
74
|
+
} else if (value === 1) attributes |= TextAttributes.BOLD;
|
|
75
|
+
else if (value === 2) attributes |= TextAttributes.DIM;
|
|
76
|
+
else if (value === 3) attributes |= TextAttributes.ITALIC;
|
|
77
|
+
else if (value === 4) attributes |= TextAttributes.UNDERLINE;
|
|
78
|
+
else if (value === 9) attributes |= TextAttributes.STRIKETHROUGH;
|
|
79
|
+
else {
|
|
80
|
+
const next = roleFor(value);
|
|
81
|
+
if (next !== null) role = next;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
plain(sanitize(text.slice(at)));
|
|
86
|
+
return glyphs;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const DIFF_HEADER = /^(diff --git|index |new file mode|deleted file mode|old mode|new mode|similarity index|dissimilarity index|rename from|rename to|copy from|copy to)/;
|
|
90
|
+
const STAT_LINE = /^(\s*\S.*?\|\s*\d+\s+)([+-]+)\s*$/;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* The glyphs of one fenced code row. The engine's own styling is not used: a
|
|
94
|
+
* row has no role unless it is a diff line, and then the role follows the
|
|
95
|
+
* line's first characters (or, in a --stat line, the + and - runs).
|
|
96
|
+
*/
|
|
97
|
+
function codeGlyphs(text: string, language: string): WrapGlyph<LayoutStyle>[] {
|
|
98
|
+
// The engine indents code by two columns; the block keeps one.
|
|
99
|
+
const plain = sanitize(text.replace(/\x1b\[[0-9;]*m/g, "")).replace(/\t/g, " ").replace(/^ /, "");
|
|
100
|
+
const body = plain.replace(/^ /, "");
|
|
101
|
+
const make = (role: LayoutRole, attributes = 0) =>
|
|
102
|
+
graphemes(plain).map((char): WrapGlyph<LayoutStyle> => ({ char, value: { role, attributes } }));
|
|
103
|
+
if (language !== "diff") return make(undefined);
|
|
104
|
+
if (body.startsWith("+")) return make("add");
|
|
105
|
+
if (body.startsWith("-")) return make("remove");
|
|
106
|
+
if (body.startsWith("@@")) return make("accent");
|
|
107
|
+
if (body.startsWith("diff --git")) return make("accent", TextAttributes.BOLD);
|
|
108
|
+
if (DIFF_HEADER.test(body)) return make("accent");
|
|
109
|
+
const stat = STAT_LINE.exec(body);
|
|
110
|
+
if (stat !== null) {
|
|
111
|
+
const head = 1 + graphemes(stat[1] ?? "").length;
|
|
112
|
+
return graphemes(plain).map((char, index): WrapGlyph<LayoutStyle> => ({
|
|
113
|
+
char,
|
|
114
|
+
value: {
|
|
115
|
+
role: index < head ? undefined : char === "+" ? "add" : char === "-" ? "remove" : undefined,
|
|
116
|
+
attributes: 0,
|
|
117
|
+
},
|
|
118
|
+
}));
|
|
119
|
+
}
|
|
120
|
+
return make(undefined);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Cuts a code row into rows of `width` columns at any column, keeping its
|
|
125
|
+
* indentation, and gives every row the block's one column of left padding.
|
|
126
|
+
*/
|
|
127
|
+
function cutCode(glyphs: readonly WrapGlyph<LayoutStyle>[], width: number): WrapGlyph<LayoutStyle>[][] {
|
|
128
|
+
const [pad, ...body] = glyphs;
|
|
129
|
+
if (pad === undefined) return [[]];
|
|
130
|
+
const limit = Math.max(1, Math.trunc(width) - 1);
|
|
131
|
+
const rows: WrapGlyph<LayoutStyle>[][] = [];
|
|
132
|
+
let row: WrapGlyph<LayoutStyle>[] = [pad];
|
|
133
|
+
let used = 0;
|
|
134
|
+
for (const glyph of body) {
|
|
135
|
+
const size = Bun.stringWidth(glyph.char);
|
|
136
|
+
if (used > 0 && used + size > limit) {
|
|
137
|
+
rows.push(row);
|
|
138
|
+
row = [pad];
|
|
139
|
+
used = 0;
|
|
140
|
+
}
|
|
141
|
+
row.push(glyph);
|
|
142
|
+
used += size;
|
|
143
|
+
}
|
|
144
|
+
rows.push(row);
|
|
145
|
+
return rows;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function sameStyle(left: LayoutStyle, right: LayoutStyle): boolean {
|
|
149
|
+
return left.role === right.role && left.attributes === right.attributes;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function runsOf(glyphs: readonly WrapGlyph<LayoutStyle>[]): LayoutRun[] {
|
|
153
|
+
const runs: LayoutRun[] = [];
|
|
154
|
+
let text = "";
|
|
155
|
+
let style: LayoutStyle | undefined;
|
|
156
|
+
const flush = (): void => {
|
|
157
|
+
if (text.length > 0 && style !== undefined) runs.push({ text, style });
|
|
158
|
+
text = "";
|
|
159
|
+
};
|
|
160
|
+
for (const glyph of glyphs) {
|
|
161
|
+
if (style !== undefined && !sameStyle(style, glyph.value)) flush();
|
|
162
|
+
style = glyph.value;
|
|
163
|
+
text += glyph.char;
|
|
164
|
+
}
|
|
165
|
+
flush();
|
|
166
|
+
if (runs.length === 0) {
|
|
167
|
+
runs.push({ text: "", style: style ?? { role: undefined, attributes: 0 } });
|
|
168
|
+
}
|
|
169
|
+
return runs;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Every row one section's Markdown takes at `width` columns, without its
|
|
174
|
+
* trailing blank rows. `width` undefined means no wrapping.
|
|
175
|
+
*/
|
|
176
|
+
export function layoutMarkdown(
|
|
177
|
+
markdown: string,
|
|
178
|
+
width?: number | undefined,
|
|
179
|
+
): readonly LayoutLine[] {
|
|
180
|
+
const rows: LayoutLine[] = [];
|
|
181
|
+
// Cleaned before the renderer adds its own styles, so a literal escape in
|
|
182
|
+
// the text cannot pass for one of them.
|
|
183
|
+
for (const line of renderMarkdownLines(sanitize(markdown), {
|
|
184
|
+
colour: true,
|
|
185
|
+
width,
|
|
186
|
+
})) {
|
|
187
|
+
// The fence's info string is not drawn.
|
|
188
|
+
if (line.label === true) continue;
|
|
189
|
+
const glyphs = line.code
|
|
190
|
+
? codeGlyphs(line.text, line.language ?? "")
|
|
191
|
+
: glyphsFor(line.text);
|
|
192
|
+
const wrapped =
|
|
193
|
+
width === undefined
|
|
194
|
+
? [glyphs]
|
|
195
|
+
: line.code
|
|
196
|
+
? cutCode(glyphs, width)
|
|
197
|
+
: wrapGlyphs(glyphs, width);
|
|
198
|
+
for (const row of wrapped) {
|
|
199
|
+
if (line.code && width !== undefined) {
|
|
200
|
+
// One rectangle: every row of the block is as wide as the pane.
|
|
201
|
+
const used = row.reduce((sum, glyph) => sum + Bun.stringWidth(glyph.char), 0);
|
|
202
|
+
for (let pad = used; pad < width; pad += 1) {
|
|
203
|
+
row.push({ char: " ", value: { role: undefined, attributes: 0 } });
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
rows.push({
|
|
207
|
+
text: row.map((glyph) => glyph.char).join(""),
|
|
208
|
+
code: line.code,
|
|
209
|
+
runs: runsOf(row),
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
while (rows.length > 0 && (rows[rows.length - 1]?.text ?? "").trim() === "") rows.pop();
|
|
214
|
+
return rows;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
interface Entry {
|
|
218
|
+
readonly version: number;
|
|
219
|
+
readonly markdown: string;
|
|
220
|
+
readonly width: number;
|
|
221
|
+
readonly lines: readonly LayoutLine[];
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const CACHE_LIMIT = 32;
|
|
225
|
+
const cache = new Map<string, Entry>();
|
|
226
|
+
|
|
227
|
+
/** How many layouts were computed, for a test that checks the cache is used. */
|
|
228
|
+
export const layoutStats = { computed: 0 };
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* The layout of one section's content, kept per `key` while its `version` and
|
|
232
|
+
* the `width` stay the same. A key names one section of one open object.
|
|
233
|
+
*/
|
|
234
|
+
export function cachedLayout(
|
|
235
|
+
key: string,
|
|
236
|
+
version: number,
|
|
237
|
+
markdown: string,
|
|
238
|
+
width: number,
|
|
239
|
+
): readonly LayoutLine[] {
|
|
240
|
+
const entry = cache.get(key);
|
|
241
|
+
// The text itself is compared too: the same string is one pointer check, and
|
|
242
|
+
// two states that happen to share a key and a version cannot share rows.
|
|
243
|
+
if (
|
|
244
|
+
entry !== undefined &&
|
|
245
|
+
entry.version === version &&
|
|
246
|
+
entry.width === width &&
|
|
247
|
+
entry.markdown === markdown
|
|
248
|
+
) {
|
|
249
|
+
return entry.lines;
|
|
250
|
+
}
|
|
251
|
+
layoutStats.computed += 1;
|
|
252
|
+
const lines = layoutMarkdown(markdown, width);
|
|
253
|
+
cache.delete(key);
|
|
254
|
+
cache.set(key, { version, markdown, width, lines });
|
|
255
|
+
if (cache.size > CACHE_LIMIT) {
|
|
256
|
+
const oldest = cache.keys().next().value;
|
|
257
|
+
if (oldest !== undefined) cache.delete(oldest);
|
|
258
|
+
}
|
|
259
|
+
return lines;
|
|
260
|
+
}
|