-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathXTerm.tsx
211 lines (198 loc) · 6.59 KB
/
XTerm.tsx
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/**
* (c) 2021, Micro:bit Educational Foundation and contributors
*
* SPDX-License-Identifier: MIT
*/
import { Box, BoxProps } from "@chakra-ui/layout";
import { useToken } from "@chakra-ui/react";
import React, { useEffect, useMemo, useRef } from "react";
import { Terminal } from "xterm";
import { FitAddon } from "xterm-addon-fit";
import "xterm/css/xterm.css";
import useActionFeedback from "../common/use-action-feedback";
import useIsUnmounted from "../common/use-is-unmounted";
import { backgroundColorTerm } from "../deployment/misc";
import { SerialDataEvent } from "@microbit/microbit-connection";
import { parseTraceLine, useDevice } from "../device/device-hooks";
import { useSelection } from "../workbench/use-selection";
import { WebLinkProvider } from "./link-provider";
import { useCurrentTerminalRef } from "./serial-hooks";
import "./xterm-custom.css";
import customKeyEventHandler from "./xterm-keyboard";
interface XTermProps extends BoxProps {
tabOutRef: HTMLElement;
fontSizePt: number;
}
/**
* xterm.js-based terminal.
*/
const XTerm = ({ fontSizePt, tabOutRef, ...props }: XTermProps) => {
const ref = useRef<HTMLDivElement>(null);
useManagedTermimal(ref, tabOutRef, fontSizePt);
return <Box {...props} ref={ref} backgroundColor={backgroundColorTerm} />;
};
const ptToPixelRatio = 96 / 72;
/**
* Manages an XTerm terminal object.
*
* The terminal is registered with the current terminal hook so only
* one instance is permitted without changing that design.
*/
const useManagedTermimal = (
ref: React.RefObject<HTMLDivElement>,
tabOutRef: HTMLElement,
fontSizePt: number
): void => {
const actionFeedback = useActionFeedback();
const codeFontFamily = useToken("fonts", "code");
const device = useDevice();
const isUnmounted = useIsUnmounted();
const [, setSelection] = useSelection();
const fitAddon = useMemo(() => new FitAddon(), []);
const currentTerminalRef = useCurrentTerminalRef();
const initialFontSizeRef = useRef<number>(fontSizePt);
useEffect(() => {
const parent = ref.current;
if (!parent) {
return;
}
if (currentTerminalRef.current) {
throw new Error("Only one instance supported.");
}
const terminal = new Terminal({
fontFamily: codeFontFamily,
fontSize: ptToPixelRatio * initialFontSizeRef.current,
letterSpacing: 1.1,
screenReaderMode: true,
theme: {
background: backgroundColorTerm,
},
});
const tracebackLinkHandler = (_e: MouseEvent, traceLine: string) => {
const { file, line } = parseTraceLine(traceLine);
if (file) {
setSelection({ file, location: { line } });
}
};
// Group 1 is underlined by xterm.js
const tracebackRegExpMatch = /^ {2}(File "[^"]+", line \d+)/;
terminal.registerLinkProvider(
new WebLinkProvider(
terminal,
tracebackRegExpMatch,
tracebackLinkHandler,
{}
)
);
terminal.loadAddon(fitAddon);
terminal.attachCustomKeyEventHandler((e) =>
customKeyEventHandler(e, tabOutRef)
);
const serialListener = (event: SerialDataEvent) => {
if (!isUnmounted()) {
terminal.write(event.data);
}
};
const resetListener = () => {
if (!isUnmounted()) {
terminal.reset();
}
};
device.addEventListener("serialdata", serialListener);
device.addEventListener("serialreset", resetListener);
terminal.onData((data: string) => {
if (!isUnmounted()) {
// Async for internal error handling, we don't need to wait.
device.serialWrite(data);
}
});
// Watch for resize and change terminal rows/cols accordingly.
// This can result in a slither of space at the bottom, so backgrounds
// should match.
const resizeObserver = new ResizeObserver((entries) => {
if (!Array.isArray(entries) || !entries.length) {
return;
}
try {
fitAddon.fit();
// Fix for scrollbar not being draggable.
// https://github.com/xtermjs/xterm.js/issues/2757
const xtermScreenEl = parent.querySelector(".xterm-screen");
const xtermAccessibilityEl = parent.querySelector(
".xterm-accessibility"
);
(xtermAccessibilityEl as HTMLElement).style.width =
(xtermScreenEl as HTMLElement).offsetWidth + "px";
} catch (e) {
// It throws if you resize it when not visible but it does no harm.
}
});
const terminalOpen = terminal.open.bind(terminal);
terminal.open = (parent: HTMLElement) => {
terminalOpen(parent);
resizeObserver.observe(parent);
};
// Fragile interception of paste events.
// Raised https://github.com/xtermjs/xterm.js/issues/3516
// for API in xterm.js
const coreTerminal = (terminal as any)._core;
const initGlobal = coreTerminal._initGlobal.bind(coreTerminal);
const customPasteEventHandler = (event: ClipboardEvent) => {
// Avoid the handler xterm.js will add.
event.stopImmediatePropagation();
event.stopPropagation();
event.preventDefault();
if (event.clipboardData) {
let text = event.clipboardData.getData("text/plain");
if (/[\n\r]/.test(text)) {
actionFeedback.info({
title:
"Started and finished MicroPython paste mode for the multi-line paste.",
position: "bottom-right",
});
// Wrap in start/end paste mode to prevent auto-indent.
text = `\x05${text}\x04`;
}
terminal.paste(text);
}
};
coreTerminal._initGlobal = () => {
// We don't need to remove these as we share a lifetime with this DOM.
terminal.element!.addEventListener("paste", customPasteEventHandler);
terminal.textarea!.addEventListener("paste", customPasteEventHandler);
initGlobal();
};
terminal.open(parent);
currentTerminalRef.current = terminal;
return () => {
currentTerminalRef.current = undefined;
device.removeEventListener("serialreset", resetListener);
device.removeEventListener("serialdata", serialListener);
resizeObserver.disconnect();
terminal.dispose();
};
}, [
actionFeedback,
codeFontFamily,
currentTerminalRef,
device,
isUnmounted,
setSelection,
fitAddon,
initialFontSizeRef,
tabOutRef,
ref,
]);
useEffect(() => {
currentTerminalRef.current?.setOption(
"fontSize",
fontSizePt * ptToPixelRatio
);
try {
fitAddon.fit();
} catch (e) {
// It throws if you resize it when not visible but it does no harm.
}
}, [currentTerminalRef, fitAddon, fontSizePt]);
};
export default XTerm;