rucan 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.
@@ -0,0 +1,614 @@
1
+ import { posix } from "node:path";
2
+ import { availableUpdate, installUpdate, skipUpdate, } from "../release/updates.js";
3
+ import { version } from "../release/version.js";
4
+ import { Explorer } from "../explorer/explorer.js";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { connectRemoteAgent } from "../agent/ssh.js";
7
+ import { connectLocalAgent } from "../agent/local.js";
8
+ import { mountRawInput } from "./raw-input.js";
9
+ import { footerFor, menuFor, selectionLines } from "./view.js";
10
+ import { listTmux, openTmux } from "./tmux.js";
11
+ import { TerminalWatch } from "./watch.js";
12
+ import { terminalMouse } from "./mouse.js";
13
+ import { geometry, Screen } from "./screen.js";
14
+ import { decodeSnapshot } from "./snapshot.js";
15
+ import { createWorkspace, decodeWorkspace, listWorkspaces, workspaceLabels, } from "./workspaces.js";
16
+ export async function runInteractive(config, requested, host) {
17
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
18
+ throw new Error("The workspace UI requires a terminal.");
19
+ let next;
20
+ let target = requested;
21
+ let currentHost = host;
22
+ let prepared;
23
+ do {
24
+ const alias = currentHost;
25
+ const connect = alias ? () => connectRemoteAgent(alias) : connectLocalAgent;
26
+ const client = prepared ?? (await connect());
27
+ prepared = undefined;
28
+ try {
29
+ next = await new InteractiveWorkspace(client, config, alias, connect).run(target);
30
+ }
31
+ finally {
32
+ client.close();
33
+ }
34
+ target = undefined;
35
+ if (next?.type === "update")
36
+ await installUpdate(next.version);
37
+ if (next?.type === "host") {
38
+ currentHost = next.host;
39
+ prepared = next.client;
40
+ }
41
+ } while (prepared);
42
+ }
43
+ function hasLease(reply) {
44
+ if (typeof reply !== "object" ||
45
+ reply === null ||
46
+ !("controlsInput" in reply) ||
47
+ typeof reply.controlsInput !== "boolean") {
48
+ throw new Error("Invalid attachment response");
49
+ }
50
+ return reply.controlsInput;
51
+ }
52
+ class InteractiveWorkspace {
53
+ #client;
54
+ #config;
55
+ #host;
56
+ #connect;
57
+ #screen = new Screen(process.stdout);
58
+ #explorer;
59
+ #layout = geometry(process.stdout.rows || 24, process.stdout.columns || 80);
60
+ #mode = "terminal";
61
+ #status = "";
62
+ #update;
63
+ #result;
64
+ #hosts = [];
65
+ #hostIndex = 0;
66
+ #newEntries = [];
67
+ #newIndex = 0;
68
+ #hostTrial = 0;
69
+ #history;
70
+ #offset = 0;
71
+ #name = "";
72
+ #tmux = [];
73
+ #tmuxIndex = 0;
74
+ #workspaces = [];
75
+ #selected;
76
+ #snapshot;
77
+ #controlsInput = false;
78
+ #watcher;
79
+ #stopped = false;
80
+ #resizePending = false;
81
+ #jobs = Promise.resolve();
82
+ #resolveExit;
83
+ constructor(client, config, host, connect) {
84
+ this.#client = client;
85
+ this.#config = config;
86
+ this.#host = host;
87
+ this.#connect = connect;
88
+ this.#watcher = new TerminalWatch(connect);
89
+ this.#explorer = new Explorer(connect, config.explorer.exclusions, () => this.#draw());
90
+ }
91
+ async run(requested) {
92
+ this.#workspaces = await listWorkspaces(this.#client);
93
+ const target = requested
94
+ ? this.#workspaces.find(({ id, name }) => id === requested || name === requested)
95
+ : this.#workspaces.find(({ running }) => running);
96
+ if (requested && !target)
97
+ throw new Error(`Unknown session ${requested}`);
98
+ await this.#select(target ?? (await this.#new()), false);
99
+ const onResize = () => {
100
+ if (this.#resizePending)
101
+ return;
102
+ this.#resizePending = true;
103
+ this.#enqueue(async () => {
104
+ this.#resizePending = false;
105
+ this.#layout = geometry(process.stdout.rows || 24, process.stdout.columns || 80);
106
+ await this.#resize();
107
+ this.#draw();
108
+ });
109
+ };
110
+ const done = new Promise((resolve) => {
111
+ this.#resolveExit = resolve;
112
+ });
113
+ this.#screen.enter();
114
+ let unmount;
115
+ try {
116
+ unmount = mountRawInput(this.#config.terminal.prefix_key, {
117
+ input: (events) => this.#enqueue(async () => {
118
+ for (const event of events) {
119
+ if (this.#stopped)
120
+ break;
121
+ await this.#input(event);
122
+ }
123
+ }),
124
+ resize: onResize,
125
+ stop: () => this.#stop(),
126
+ });
127
+ this.#draw();
128
+ if (this.#config.updates.check_on_startup) {
129
+ void availableUpdate()
130
+ .then((target) => {
131
+ if (this.#stopped || !target)
132
+ return;
133
+ this.#update = target;
134
+ this.#draw();
135
+ })
136
+ .catch(() => { });
137
+ }
138
+ await done;
139
+ }
140
+ finally {
141
+ this.#stop();
142
+ this.#client.close();
143
+ unmount?.();
144
+ this.#screen.leave();
145
+ }
146
+ return this.#result;
147
+ }
148
+ #stop() {
149
+ this.#stopped = true;
150
+ this.#hostTrial++;
151
+ this.#explorer.leave();
152
+ this.#watcher.stop();
153
+ this.#resolveExit?.();
154
+ }
155
+ #enqueue(task) {
156
+ this.#jobs = this.#jobs.then(async () => {
157
+ if (this.#stopped)
158
+ return;
159
+ try {
160
+ await task();
161
+ }
162
+ catch (error) {
163
+ this.#status = error instanceof Error ? error.message : String(error);
164
+ this.#draw();
165
+ if (this.#client.closed && !this.#stopped)
166
+ await this.#recoverControl();
167
+ }
168
+ });
169
+ return this.#jobs;
170
+ }
171
+ async #new(requested) {
172
+ const workspace = await createWorkspace(this.#client, this.#config, this.#layout, this.#host, requested);
173
+ this.#workspaces.push(workspace);
174
+ return workspace;
175
+ }
176
+ async #select(workspace, render = true) {
177
+ const previous = this.#selected;
178
+ const controls = hasLease(await this.#client.request({ type: "attach", session: workspace.id }));
179
+ if (previous && previous.id !== workspace.id)
180
+ await this.#client.request({ type: "detach", session: previous.id });
181
+ this.#watcher.stop();
182
+ this.#selected = workspace;
183
+ this.#controlsInput = controls;
184
+ this.#status = controls ? "" : "Read-only · input held by another client";
185
+ this.#snapshot = decodeSnapshot(await this.#client.request({ type: "snapshot", session: workspace.id }));
186
+ await this.#resize();
187
+ if (render)
188
+ this.#draw();
189
+ this.#watcher.start(workspace.id, this.#snapshot, (snapshot) => {
190
+ this.#snapshot = snapshot;
191
+ this.#draw();
192
+ }, (error) => {
193
+ this.#status = error instanceof Error ? error.message : String(error);
194
+ this.#draw();
195
+ });
196
+ }
197
+ async #recoverControl() {
198
+ const selected = this.#selected;
199
+ for (const wait of [150, 350, 900]) {
200
+ if (this.#stopped)
201
+ return;
202
+ await delay(wait);
203
+ try {
204
+ const client = await this.#connect();
205
+ if (this.#stopped) {
206
+ client.close();
207
+ return;
208
+ }
209
+ this.#client = client;
210
+ if (selected)
211
+ await this.#select(selected);
212
+ return;
213
+ }
214
+ catch (error) {
215
+ this.#client.close();
216
+ if (this.#stopped)
217
+ return;
218
+ this.#status = error instanceof Error ? error.message : String(error);
219
+ this.#draw();
220
+ }
221
+ }
222
+ }
223
+ async #resize() {
224
+ if (!this.#controlsInput || !this.#selected?.running)
225
+ return;
226
+ await this.#client.request({
227
+ type: "resize",
228
+ session: this.#selected.id,
229
+ rows: this.#layout.terminalRows,
230
+ cols: this.#layout.terminalCols,
231
+ });
232
+ }
233
+ async #forward(bytes) {
234
+ if (!this.#controlsInput ||
235
+ !this.#selected ||
236
+ this.#snapshot?.state !== "running")
237
+ return;
238
+ for (let offset = 0; offset < bytes.length; offset += 8192) {
239
+ await this.#client.sendInput(this.#selected.id, bytes.subarray(offset, offset + 8192));
240
+ }
241
+ }
242
+ async #input(event) {
243
+ if (event.type === "prefix") {
244
+ if (this.#mode === "explorer")
245
+ this.#explorer.leave();
246
+ if (this.#mode === "hosts")
247
+ this.#hostTrial++;
248
+ this.#mode = this.#mode === "terminal" ? "menu" : "terminal";
249
+ this.#draw();
250
+ return;
251
+ }
252
+ if (event.type === "mouse") {
253
+ if (this.#mode !== "terminal" && this.#mode !== "menu")
254
+ return;
255
+ if (event.col <= this.#layout.sidebar &&
256
+ event.row >= 3 &&
257
+ !event.release &&
258
+ event.button === 0) {
259
+ const workspace = this.#workspaces[event.row - 3];
260
+ if (workspace && event.col === 4 && workspace.ownership === "managed")
261
+ await this.#pin(workspace);
262
+ else if (workspace)
263
+ await this.#select(workspace);
264
+ }
265
+ else if (this.#mode === "terminal" && this.#snapshot) {
266
+ const bytes = terminalMouse(event, this.#layout, this.#snapshot.grid);
267
+ if (bytes)
268
+ await this.#forward(bytes);
269
+ }
270
+ return;
271
+ }
272
+ if (event.type !== "bytes") {
273
+ if (this.#mode === "terminal" && this.#snapshot?.grid.bracketedPaste) {
274
+ await this.#forward(Buffer.from(event.type === "paste-start" ? "\x1b[200~" : "\x1b[201~"));
275
+ }
276
+ return;
277
+ }
278
+ if (this.#mode === "terminal") {
279
+ await this.#forward(event.bytes);
280
+ return;
281
+ }
282
+ const key = event.bytes.toString("utf8");
283
+ if (this.#mode === "explorer") {
284
+ if (key === "\x1b") {
285
+ this.#explorer.leave();
286
+ this.#mode = "menu";
287
+ }
288
+ else if (key === "\x1b[A")
289
+ this.#explorer.move(-1);
290
+ else if (key === "\x1b[B")
291
+ this.#explorer.move(1);
292
+ else if (key === "\r")
293
+ this.#explorer.activate();
294
+ else if (key === "r")
295
+ this.#explorer.refresh();
296
+ else if (key === "o" && this.#explorer.file)
297
+ await this.#openEditor(this.#explorer.file);
298
+ }
299
+ else if (this.#mode === "create") {
300
+ if (key === "\x1b")
301
+ this.#mode = "menu";
302
+ else if (key === "\x1b[A")
303
+ this.#newIndex = Math.max(0, this.#newIndex - 1);
304
+ else if (key === "\x1b[B")
305
+ this.#newIndex = Math.min(this.#newEntries.length, this.#newIndex + 1);
306
+ else if (key === "\r") {
307
+ const requested = this.#newEntries[this.#newIndex - 1];
308
+ if (requested?.backend === "tmux") {
309
+ await this.#openTmux(requested.session ?? null, requested.cwd);
310
+ }
311
+ else {
312
+ await this.#select(await this.#new(requested));
313
+ this.#mode = "terminal";
314
+ }
315
+ }
316
+ }
317
+ else if (this.#mode === "hosts") {
318
+ if (key === "\x1b") {
319
+ this.#hostTrial++;
320
+ this.#mode = "menu";
321
+ this.#status = "";
322
+ }
323
+ else if (key === "\x1b[A")
324
+ this.#hostIndex = Math.max(0, this.#hostIndex - 1);
325
+ else if (key === "\x1b[B")
326
+ this.#hostIndex = Math.min(this.#hosts.length - 1, this.#hostIndex + 1);
327
+ else if (key === "\r")
328
+ this.#switchHost(this.#hosts[this.#hostIndex]);
329
+ }
330
+ else if (this.#mode === "history") {
331
+ if (key === "\x1b") {
332
+ this.#mode = "menu";
333
+ this.#history = undefined;
334
+ }
335
+ else if (key === "\x1b[5~" || key === "\x1b[A")
336
+ await this.#scroll(this.#offset + this.#layout.terminalRows);
337
+ else if (key === "\x1b[6~" || key === "\x1b[B")
338
+ await this.#scroll(Math.max(0, this.#offset - this.#layout.terminalRows));
339
+ }
340
+ else if (this.#mode === "rename") {
341
+ if (key === "\x1b")
342
+ this.#mode = "menu";
343
+ else if (key === "\x7f")
344
+ this.#name = [...this.#name].slice(0, -1).join("");
345
+ else if (key === "\r")
346
+ await this.#rename();
347
+ else if (!/\p{Cc}/u.test(key) &&
348
+ Buffer.byteLength(this.#name + key) <= 128)
349
+ this.#name += key;
350
+ }
351
+ else if (this.#mode === "update") {
352
+ if (key === "1") {
353
+ if (this.#update) {
354
+ this.#result = { type: "update", version: this.#update };
355
+ this.#stop();
356
+ }
357
+ }
358
+ else if (key === "2" || key === "\x1b" || key === "3") {
359
+ if (key === "3" && this.#update)
360
+ await skipUpdate(this.#update);
361
+ this.#update = undefined;
362
+ this.#mode = "terminal";
363
+ }
364
+ }
365
+ else if (this.#mode === "tmux") {
366
+ if (key === "\x1b")
367
+ this.#mode = "menu";
368
+ else if (key === "\x1b[A")
369
+ this.#tmuxIndex = Math.max(0, this.#tmuxIndex - 1);
370
+ else if (key === "\x1b[B")
371
+ this.#tmuxIndex = Math.min(Math.max(0, this.#tmux.length - 1), this.#tmuxIndex + 1);
372
+ else if (key === "n")
373
+ await this.#openTmux(null);
374
+ else if (key === "\r" && this.#tmux[this.#tmuxIndex]) {
375
+ await this.#openTmux(this.#tmux[this.#tmuxIndex]?.id ?? null);
376
+ }
377
+ }
378
+ else if (this.#mode === "exit") {
379
+ if (key === "1")
380
+ await this.#exit("keep-all");
381
+ if (key === "2")
382
+ await this.#exit("keep-pinned");
383
+ if (key === "3")
384
+ await this.#exit("terminate");
385
+ if (key === "\x1b" || key === "4")
386
+ this.#mode = "menu";
387
+ }
388
+ else {
389
+ await this.#menu(key);
390
+ }
391
+ this.#draw();
392
+ }
393
+ #switchHost(host) {
394
+ if (host === this.#host) {
395
+ this.#mode = "terminal";
396
+ return;
397
+ }
398
+ const trial = ++this.#hostTrial;
399
+ this.#status = `Connecting to ${host ?? "local agent"}…`;
400
+ const attempt = host ? connectRemoteAgent(host) : connectLocalAgent();
401
+ void attempt
402
+ .then((client) => {
403
+ if (trial !== this.#hostTrial || this.#stopped) {
404
+ client.close();
405
+ return;
406
+ }
407
+ this.#result = { type: "host", host, client };
408
+ this.#stop();
409
+ })
410
+ .catch((error) => {
411
+ if (trial !== this.#hostTrial || this.#stopped)
412
+ return;
413
+ this.#status = error instanceof Error ? error.message : String(error);
414
+ this.#draw();
415
+ });
416
+ }
417
+ async #pin(selected) {
418
+ const workspace = decodeWorkspace(await this.#client.request({
419
+ type: "pin",
420
+ session: selected.id,
421
+ persistent: !selected.persistent,
422
+ }));
423
+ this.#workspaces = this.#workspaces.map((entry) => entry.id === workspace.id ? workspace : entry);
424
+ if (this.#selected?.id === workspace.id)
425
+ this.#selected = workspace;
426
+ this.#draw();
427
+ }
428
+ async #rename() {
429
+ if (!this.#selected)
430
+ return;
431
+ const renamed = decodeWorkspace(await this.#client.request({
432
+ type: "rename",
433
+ session: this.#selected.id,
434
+ name: this.#name,
435
+ }));
436
+ this.#workspaces = this.#workspaces.map((workspace) => workspace.id === renamed.id ? renamed : workspace);
437
+ this.#selected = renamed;
438
+ this.#mode = "menu";
439
+ }
440
+ async #scroll(offset) {
441
+ if (!this.#selected)
442
+ return;
443
+ const data = await this.#client.request({
444
+ type: "scroll",
445
+ session: this.#selected.id,
446
+ offset,
447
+ });
448
+ if (typeof data !== "object" ||
449
+ data === null ||
450
+ !("scrollback" in data) ||
451
+ typeof data.scrollback !== "number") {
452
+ throw new Error("Invalid scrollback response");
453
+ }
454
+ this.#history = decodeSnapshot(data);
455
+ this.#offset = data.scrollback;
456
+ }
457
+ async #openTmux(target, cwd = this.#selected?.cwd ?? "~") {
458
+ const opened = await openTmux(this.#client, this.#layout, cwd, target);
459
+ if (!this.#workspaces.some(({ id }) => id === opened.id))
460
+ this.#workspaces.push(opened);
461
+ await this.#select(opened);
462
+ this.#mode = "terminal";
463
+ }
464
+ async #openEditor(path) {
465
+ const editor = this.#config.explorer.editor;
466
+ const workspace = decodeWorkspace(await this.#client.request({
467
+ type: "create",
468
+ name: `Edit ${posix.basename(path).replace(/\p{Cc}/gu, "")}`,
469
+ cwd: posix.dirname(path),
470
+ command: editor.command,
471
+ args: [...editor.args, path],
472
+ rows: this.#layout.terminalRows,
473
+ cols: this.#layout.terminalCols,
474
+ persistent: false,
475
+ }));
476
+ this.#workspaces.push(workspace);
477
+ this.#explorer.leave();
478
+ await this.#select(workspace);
479
+ this.#mode = "terminal";
480
+ }
481
+ async #menu(key) {
482
+ if (key === "\x1b") {
483
+ this.#mode = "terminal";
484
+ }
485
+ else if (key === "d") {
486
+ await this.#exit("keep-all");
487
+ }
488
+ else if (key === "q") {
489
+ const policy = this.#config.defaults.on_exit;
490
+ if (policy === "ask")
491
+ this.#mode = "exit";
492
+ else
493
+ await this.#exit(policy);
494
+ }
495
+ else if (key === "r" && this.#selected) {
496
+ this.#name = "";
497
+ this.#mode = "rename";
498
+ }
499
+ else if (key === "s" && this.#selected) {
500
+ await this.#scroll(this.#layout.terminalRows);
501
+ this.#mode = "history";
502
+ }
503
+ else if (key === "u" && this.#update) {
504
+ this.#mode = "update";
505
+ }
506
+ else if (key === "t") {
507
+ const inventory = await listTmux(this.#client);
508
+ if (!inventory.available)
509
+ throw new Error("tmux is unavailable on this host");
510
+ this.#tmux = inventory.sessions;
511
+ this.#tmuxIndex = 0;
512
+ this.#mode = "tmux";
513
+ }
514
+ else if (key === "e") {
515
+ this.#mode = "explorer";
516
+ this.#explorer.enter(this.#selected?.cwd ?? "~");
517
+ }
518
+ else if (key === "n") {
519
+ this.#newEntries = this.#config.workspaces.filter(({ host }) => host === this.#host);
520
+ this.#newIndex = 0;
521
+ this.#mode = "create";
522
+ }
523
+ else if (key === "h") {
524
+ this.#hosts = [
525
+ undefined,
526
+ ...new Set(this.#config.workspaces.flatMap(({ host }) => (host ? [host] : []))),
527
+ ];
528
+ this.#hostIndex = Math.max(0, this.#hosts.indexOf(this.#host));
529
+ this.#mode = "hosts";
530
+ }
531
+ else if (key === "p" && this.#selected) {
532
+ await this.#pin(this.#selected);
533
+ }
534
+ else {
535
+ const current = this.#workspaces.findIndex(({ id }) => id === this.#selected?.id);
536
+ const index = /^[1-9]$/u.test(key)
537
+ ? Number(key) - 1
538
+ : key === "\x1b[A"
539
+ ? Math.max(0, current - 1)
540
+ : key === "\x1b[B"
541
+ ? current + 1
542
+ : -1;
543
+ const next = this.#workspaces[index];
544
+ if (next) {
545
+ await this.#select(next);
546
+ this.#mode = "terminal";
547
+ }
548
+ }
549
+ }
550
+ async #exit(policy) {
551
+ if (policy !== "keep-all") {
552
+ for (const workspace of await listWorkspaces(this.#client)) {
553
+ if (workspace.ownership === "managed" &&
554
+ workspace.running &&
555
+ (policy === "terminate" || !workspace.persistent)) {
556
+ await this.#client.request({ type: "kill", session: workspace.id });
557
+ }
558
+ }
559
+ }
560
+ this.#stop();
561
+ }
562
+ #draw() {
563
+ if (this.#stopped)
564
+ return;
565
+ const selected = this.#selected;
566
+ const title = selected
567
+ ? `${selected.name}${selected.persistent ? " ◆" : ""}`
568
+ : "No session";
569
+ const footer = footerFor(this.#mode, this.#config.terminal.prefix_key, this.#name, this.#offset, this.#update);
570
+ const explorer = this.#mode === "explorer"
571
+ ? this.#explorer.layout(this.#layout.rows - 2)
572
+ : undefined;
573
+ if (this.#mode === "update" && this.#update) {
574
+ this.#screen.draw({
575
+ layout: this.#layout,
576
+ header: `Update available: v${version} → v${this.#update}`,
577
+ footer,
578
+ sidebarLines: [],
579
+ snapshot: undefined,
580
+ showCursor: false,
581
+ });
582
+ return;
583
+ }
584
+ this.#screen.draw({
585
+ layout: this.#layout,
586
+ header: `rucan │ ${title} │ ${this.#status || (this.#snapshot?.state === "running" ? (this.#host ? `${this.#host} connected` : "Local agent connected") : "Session exited")}`,
587
+ footer: this.#update && this.#mode !== "exit"
588
+ ? `${footer} · U Review v${this.#update}`
589
+ : footer,
590
+ sidebarLines: (this.#mode === "create"
591
+ ? selectionLines("OPEN WORKSPACE", ["Default shell", ...this.#newEntries.map(({ name }) => name)], this.#newIndex, this.#layout.rows - 2)
592
+ : undefined) ??
593
+ (this.#mode === "hosts"
594
+ ? selectionLines("HOSTS", this.#hosts.map((host) => host ?? "Local"), this.#hostIndex, this.#layout.rows - 2)
595
+ : undefined) ??
596
+ (this.#mode === "tmux"
597
+ ? selectionLines("TMUX SESSIONS", this.#tmux.map((entry) => entry.name), this.#tmuxIndex, this.#layout.rows - 2)
598
+ : undefined) ??
599
+ explorer?.sidebar ??
600
+ workspaceLabels(this.#config, this.#workspaces, selected?.id, this.#mode === "menu" ? menuFor(this.#update) : undefined),
601
+ ...(explorer
602
+ ? { contentLines: explorer.content }
603
+ : this.#mode === "menu" && !this.#snapshot
604
+ ? { contentLines: menuFor(this.#update) }
605
+ : {}),
606
+ snapshot: explorer
607
+ ? undefined
608
+ : this.#mode === "history"
609
+ ? this.#history
610
+ : this.#snapshot,
611
+ showCursor: this.#mode === "terminal" && this.#controlsInput,
612
+ });
613
+ }
614
+ }
@@ -0,0 +1,27 @@
1
+ export function terminalMouse(event, layout, grid) {
2
+ const col = event.col - layout.sidebar;
3
+ const row = event.row - 1;
4
+ if (col < 1 ||
5
+ col > grid.cols ||
6
+ row < 1 ||
7
+ row > grid.rows ||
8
+ grid.mouse === "none")
9
+ return undefined;
10
+ const motion = (event.button & 32) !== 0;
11
+ if (grid.mouse === "press" && (motion || event.release))
12
+ return undefined;
13
+ if (grid.mouse === "press-release" && motion)
14
+ return undefined;
15
+ if (grid.mouse === "button-motion" && motion && (event.button & 3) === 3)
16
+ return undefined;
17
+ if (grid.mouseEncoding === "sgr") {
18
+ return Buffer.from(`\x1b[<${event.button};${col};${row}${event.release ? "m" : "M"}`);
19
+ }
20
+ const button = 32 + (event.release ? (event.button & ~3) | 3 : event.button);
21
+ const values = [button, col + 32, row + 32];
22
+ if (grid.mouseEncoding === "utf8")
23
+ return Buffer.from("\x1b[M" + String.fromCodePoint(...values));
24
+ if (values.some((value) => value > 255))
25
+ return undefined;
26
+ return Buffer.from([0x1b, 0x5b, 0x4d, ...values]);
27
+ }
@@ -0,0 +1,42 @@
1
+ import { InputRouter } from "./input.js";
2
+ /** Set terminal input state for the lifetime of a mounted view. */
3
+ export function mountRawInput(prefix, handler) {
4
+ const router = new InputRouter(prefix);
5
+ const prior = process.stdin.isRaw;
6
+ let active = true;
7
+ let timer;
8
+ const data = (chunk) => {
9
+ process.stdin.pause();
10
+ clearTimeout(timer);
11
+ void handler.input(router.route(chunk)).finally(() => {
12
+ if (!active)
13
+ return;
14
+ if (router.hasPending) {
15
+ timer = setTimeout(() => {
16
+ const bytes = router.takePending();
17
+ if (bytes.length)
18
+ void handler.input([{ type: "bytes", bytes }]);
19
+ }, 18);
20
+ }
21
+ process.stdin.resume();
22
+ });
23
+ };
24
+ process.stdin.setRawMode(true);
25
+ process.stdin.on("data", data);
26
+ process.stdin.once("end", handler.stop);
27
+ process.stdout.on("resize", handler.resize);
28
+ for (const signal of ["SIGTERM", "SIGHUP", "SIGINT"])
29
+ process.once(signal, handler.stop);
30
+ process.stdin.resume();
31
+ return () => {
32
+ active = false;
33
+ clearTimeout(timer);
34
+ process.stdin.off("data", data);
35
+ process.stdin.off("end", handler.stop);
36
+ process.stdout.off("resize", handler.resize);
37
+ for (const signal of ["SIGTERM", "SIGHUP", "SIGINT"])
38
+ process.off(signal, handler.stop);
39
+ process.stdin.pause();
40
+ process.stdin.setRawMode(prior);
41
+ };
42
+ }