Repository navigation
Expand file tree
/
Copy pathTerminalView.tsx
More file actions
190 lines (184 loc) · 6.13 KB
/
Copy pathTerminalView.tsx
File metadata and controls
190 lines (184 loc) · 6.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
/** One terminal's screen: an xterm.js view of a shell the engine keeps.
* Mounting replays the engine's scrollback, so switching tabs or closing
* the drawer loses nothing; the shell itself keeps running. */
import { useEffect, useRef } from "react";
import { Terminal, type ITheme } from "@xterm/xterm";
import { FitAddon } from "@xterm/addon-fit";
import "@xterm/xterm/css/xterm.css";
import {
inputQueue,
outputReader,
subscribeTerminals,
terminalApi,
type TerminalChunk,
} from "../lib/terminal";
import { cssZoom, onCssZoom } from "../hooks/useZoom";
const FONT_SIZE = 12.5;
/** xterm.js maps the pointer with window coordinates over cell sizes it
* measured unzoomed, so under a CSS-zoomed root (a plain browser) clicks
* and selections would land on the wrong cells. The terminal undoes the
* zoom on its own box and scales its font instead; the desktop's webview
* zoom needs neither (the CSS zoom is 1 there). */
function unzoom(element: HTMLElement, zoom: number) {
element.style.zoom = zoom === 1 ? "" : String(1 / zoom);
}
function theme(): ITheme {
const css = getComputedStyle(document.documentElement);
const token = (name: string, fallback: string) =>
css.getPropertyValue(name).trim() || fallback;
return {
background: token("--surface-2", "#f5f5f2"),
foreground: token("--text", "#242824"),
cursor: token("--accent", "#386c51"),
cursorAccent: token("--surface-2", "#f5f5f2"),
selectionBackground: token("--accent-soft", "#e6eee7"),
selectionForeground: token("--text", "#242824"),
};
}
export function TerminalView({
id,
title,
onState,
onError,
onReady,
}: {
id: string;
title: string;
onState: (chunk: TerminalChunk) => void;
onError: (message: string) => void;
onReady?: (element: HTMLElement) => void;
}) {
const host = useRef<HTMLDivElement>(null);
const ready = useRef(onReady);
ready.current = onReady;
const state = useRef(onState);
state.current = onState;
const failed = useRef(onError);
failed.current = onError;
useEffect(() => {
const element = host.current;
if (!element) return;
const css = getComputedStyle(document.documentElement);
const motion = window.matchMedia?.("(prefers-reduced-motion: reduce)");
const term = new Terminal({
cursorBlink: !motion?.matches,
fontFamily:
css.getPropertyValue("--mono").trim() || "ui-monospace, monospace",
fontSize: FONT_SIZE * cssZoom(),
scrollback: 5000,
allowProposedApi: false,
theme: theme(),
});
const updateMotion = () => {
term.options.cursorBlink = !motion?.matches;
};
motion?.addEventListener("change", updateMotion);
const fit = new FitAddon();
term.loadAddon(fit);
unzoom(element, cssZoom());
term.open(element);
const input = inputQueue(
(data) => terminalApi.input(id, data),
(error) => failed.current(String(error)),
);
const typing = term.onData((data) => input.push(data));
let lastSize = "";
const sizing = term.onResize(({ cols, rows }) => {
const key = `${cols}x${rows}`;
if (key === lastSize) return;
lastSize = key;
void terminalApi.resize(id, cols, rows).catch(() => undefined);
});
const reader = outputReader({
id,
read: terminalApi.output,
write: (bytes) => term.write(bytes),
onState: (chunk) => state.current(chunk),
});
const refit = () => {
if (element.clientWidth > 0 && element.clientHeight > 0) {
try {
fit.fit();
// Reserve two complete rows in a dock, including the outer box's
// padding and borders. Measure rendered cells so platform fonts,
// fractional native zoom and our inverse CSS zoom are respected.
const screen = element.querySelector(".xterm-screen");
const box = element.parentElement;
if (screen && box && term.rows > 0) {
const rowHeight =
screen.getBoundingClientRect().height / term.rows / cssZoom();
if (rowHeight > 0) {
const style = getComputedStyle(box);
const inset = [
style.paddingTop,
style.paddingBottom,
style.borderTopWidth,
style.borderBottomWidth,
].reduce((sum, value) => sum + parseFloat(value), 0);
box.style.setProperty(
"--terminal-min-height",
`${Math.ceil(2 * rowHeight + inset)}px`,
);
}
}
} catch {
// Not laid out yet; the next resize fits it.
}
}
};
refit();
const { cols, rows } = term;
lastSize = `${cols}x${rows}`;
void terminalApi.resize(id, cols, rows).catch(() => undefined);
void reader.wake().catch((error) => failed.current(String(error)));
const stopWakeups = subscribeTerminals((terminal) => {
if (terminal === null || terminal === id)
void reader.wake().catch(() => undefined);
});
const observer = new ResizeObserver(() => refit());
observer.observe(element);
const stopZoom = onCssZoom((zoom) => {
unzoom(element, zoom);
term.options.fontSize = FONT_SIZE * zoom;
refit();
});
const recolour = new MutationObserver(() => {
term.options.theme = theme();
});
recolour.observe(document.documentElement, {
attributes: true,
attributeFilter: ["data-theme", "class"],
});
const inputElement = element.querySelector<HTMLElement>(
".xterm-helper-textarea",
);
if (inputElement) ready.current?.(inputElement);
return () => {
motion?.removeEventListener("change", updateMotion);
stopWakeups();
stopZoom();
observer.disconnect();
recolour.disconnect();
reader.stop();
input.close();
typing.dispose();
sizing.dispose();
term.dispose();
};
}, [id]);
return (
<div
className="terminal-screen"
data-terminal={id}
role="group"
aria-label={title}
onClick={(e) =>
(
e.currentTarget.querySelector("textarea") as HTMLElement | null
)?.focus()
}
>
<div ref={host} style={{ height: "100%" }} />
</div>
);
}