Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

terminalPaste.ts

59 lines1.5 KB

1import { chunkTerminalWrite, encodeTerminalPaste } from "./terminalInput";
2​
3interface TerminalPasteInput {
4 readonly readText: () => Promise<string>;
5 readonly write: (data: string) => Promise<boolean>;
6 readonly onReadError: (cause: unknown) => void;
7}
8​
9export interface TerminalPasteSession {
10 readonly reset: (active: boolean) => void;
11 readonly paste: (input: TerminalPasteInput) => Promise<void>;
13​
14export function createTerminalPasteSession(): TerminalPasteSession {
15 let liveTarget: object | null = null;
16 let latestRequest = 0;
17 let writeTail: Promise<void> = Promise.resolve();
18​
19 return {
20 reset(active) {
21 liveTarget = active ? {} : null;
22 },
23​
24 async paste({ readText, write, onReadError }) {
25 const target = liveTarget;
26 if (target === null) {
27 return;
28 }
29 const request = ++latestRequest;
30 const isCurrent = () => liveTarget === target && latestRequest === request;
31​
32 let text: string;
33 try {
34 text = await readText();
35 } catch (cause) {
36 onReadError(cause);
37 return;
38 }
39​
40 if (!isCurrent()) {
41 return;
42 }
43​
44 const writePaste = async () => {
45 for (const chunk of chunkTerminalWrite(encodeTerminalPaste(text))) {
46 if (!isCurrent() || !(await write(chunk))) {
47 return;
48 }
49 }
50 };
51 const queuedWrite = writeTail.then(writePaste, writePaste);
52 writeTail = queuedWrite.then(
53 () => undefined,
54 () => undefined,
55 );
56 await queuedWrite;
57 },
58 };