Skip to content

Commit

Permalink
feat: upgrade to xterm v5 and remove xterm-for-react dependency
Browse files Browse the repository at this point in the history
Signed-off-by: Mason Hu <[email protected]>
  • Loading branch information
mas-who committed Jan 30, 2024
1 parent da6e258 commit dca3e44
Show file tree
Hide file tree
Showing 6 changed files with 255 additions and 75 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@
"react-useportal": "1.0.19",
"serve": "14.2.1",
"vanilla-framework": "4.6.0",
"xterm-addon-fit": "0.6.0",
"xterm-for-react": "1.0.4",
"xterm": "5.2.1",
"xterm-addon-fit": "0.8.0",
"yup": "1.3.3"
},
"devDependencies": {
Expand Down
213 changes: 213 additions & 0 deletions src/components/Xterm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
/**
MIT License
Copyright (c) 2020 Robert Harbison
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

import React, {
forwardRef,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
useState,
} from "react";
import { Terminal, ITerminalOptions, ITerminalAddon } from "xterm";
import "xterm/css/xterm.css";

interface Props {
/**
* Class name to add to the terminal container.
*/
className?: string;

/**
* Options to initialize the terminal with.
*/
options?: ITerminalOptions;

/**
* An array of XTerm addons to load along with the terminal.current.
*/
addons?: Array<ITerminalAddon>;

/**
* Adds an event listener for when a binary event fires. This is used to
* enable non UTF-8 conformant binary messages to be sent to the backend.
* Currently this is only used for a certain type of mouse reports that
* happen to be not UTF-8 compatible.
* The event value is a JS string, pass it to the underlying pty as
* binary data, e.g. `pty.write(Buffer.from(data, 'binary'))`.
*/
onBinary?(data: string): void;

/**
* Adds an event listener for the cursor moves.
*/
onCursorMove?(): void;

/**
* Adds an event listener for when a data event fires. This happens for
* example when the user types or pastes into the terminal.current. The event value
* is whatever `string` results, in a typical setup, this should be passed
* on to the backing pty.
*/
onData?(data: string): void;

/**
* Adds an event listener for when a key is pressed. The event value contains the
* string that will be sent in the data event as well as the DOM event that
* triggered it.
*/
onKey?(event: { key: string; domEvent: KeyboardEvent }): void;

/**
* Adds an event listener for when a line feed is added.
*/
onLineFeed?(): void;

/**
* Adds an event listener for when a scroll occurs. The event value is the
* new position of the viewport.
* @returns an `IDisposable` to stop listening.
*/
onScroll?(newPosition: number): void;

/**
* Adds an event listener for when a selection change occurs.
*/
onSelectionChange?(): void;

/**
* Adds an event listener for when rows are rendered. The event value
* contains the start row and end rows of the rendered area (ranges from `0`
* to `terminal.current.rows - 1`).
*/
onRender?(event: { start: number; end: number }): void;

/**
* Adds an event listener for when the terminal is resized. The event value
* contains the new size.
*/
onResize?(event: { cols: number; rows: number }): void;

/**
* Adds an event listener for when an OSC 0 or OSC 2 title change occurs.
* The event value is the new title.
*/
onTitleChange?(newTitle: string): void;

/**
* Attaches a custom key event handler which is run before keys are
* processed, giving consumers of xterm.js ultimate control as to what keys
* should be processed by the terminal and what keys should not.
*
* @param event The custom KeyboardEvent handler to attach.
* This is a function that takes a KeyboardEvent, allowing consumers to stop
* propagation and/or prevent the default action. The function returns
* whether the event should be processed by xterm.js.
*/
customKeyEventHandler?(event: KeyboardEvent): boolean;

/**
* This callback porovides an interface for running actions directly after
* the terminal is open. Some useful cations includes resizing the terminal
* or focusing on the terminal etc.
*/
onOpen?(): void;
}

export default forwardRef<Terminal, Props>(function Xterm(
{
options = {},
addons,
className,
onBinary,
onCursorMove,
onData,
onKey,
onLineFeed,
onScroll,
onSelectionChange,
onRender,
onResize,
onTitleChange,
customKeyEventHandler,
onOpen,
}: Props,
ref,
) {
const [terminalOpen, setTerminalOpen] = useState(false);
const terminalRef = useRef<HTMLDivElement>(null);
const xtermRef = useRef<Terminal>(new Terminal(options));

useImperativeHandle(ref, () => {
return xtermRef.current;
});

const initialiseXterm = () => {
// Load addons if the prop exists.
if (addons) {
addons.forEach((addon) => {
xtermRef.current?.loadAddon(addon);
});
}

// Create Listeners
if (onBinary) xtermRef.current.onBinary(onBinary);
if (onCursorMove) xtermRef.current.onCursorMove(onCursorMove);
if (onData) xtermRef.current.onData(onData);
if (onKey) xtermRef.current.onKey(onKey);
if (onLineFeed) xtermRef.current.onLineFeed;
if (onScroll) xtermRef.current.onScroll(onScroll);
if (onSelectionChange)
xtermRef.current.onSelectionChange(onSelectionChange);
if (onRender) xtermRef.current.onRender(onRender);
if (onResize) xtermRef.current.onResize(onResize);
if (onTitleChange) xtermRef.current.onTitleChange(onTitleChange);

// Add Custom Key Event Handler
if (customKeyEventHandler) {
xtermRef.current.attachCustomKeyEventHandler(customKeyEventHandler);
}
};

useEffect(() => {
const terminal = terminalRef.current;
if (terminal) {
initialiseXterm();
xtermRef.current?.open(terminal);
setTerminalOpen(true);
}

return () => {
xtermRef.current?.dispose();
};
}, []);

useLayoutEffect(() => {
if (terminalOpen && onOpen) {
onOpen();
}
}, [terminalOpen]);

return <div className={className} ref={terminalRef} />;
});
42 changes: 15 additions & 27 deletions src/pages/instances/InstanceTerminal.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import React, { FC, useEffect, useLayoutEffect, useRef, useState } from "react";
import React, { FC, useEffect, useRef, useState } from "react";
import { unstable_usePrompt as usePrompt, useParams } from "react-router-dom";
import { XTerm } from "xterm-for-react";
import Xterm from "xterm-for-react/dist/src/XTerm";
import { FitAddon } from "xterm-addon-fit";
import { connectInstanceExec } from "api/instances";
import { getWsErrorMsg } from "util/helpers";
Expand All @@ -20,6 +18,8 @@ import {
Icon,
NotificationType,
} from "@canonical/react-components";
import Xterm from "components/Xterm";
import { Terminal } from "xterm";

const XTERM_OPTIONS = {
theme: {
Expand Down Expand Up @@ -52,7 +52,6 @@ const InstanceTerminal: FC<Props> = ({ instance }) => {
name: string;
project: string;
}>();
const xtermRef = useRef<Xterm>(null);
const textEncoder = new TextEncoder();
const [inTabNotification, setInTabNotification] =
useState<NotificationType | null>(null);
Expand All @@ -62,6 +61,7 @@ const InstanceTerminal: FC<Props> = ({ instance }) => {
const [payload, setPayload] = useState(defaultPayload);
const [fitAddon] = useState<FitAddon>(new FitAddon());
const [userInteracted, setUserInteracted] = useState(false);
const xtermRef = useRef<Terminal>(null);

usePrompt({
when: userInteracted,
Expand Down Expand Up @@ -123,11 +123,6 @@ const InstanceTerminal: FC<Props> = ({ instance }) => {
setControlWs(null);
};

// TODO: remove this and other console.log calls
control.onmessage = (message) => {
console.log("control message", message);
};

data.onopen = () => {
setDataWs(data);
};
Expand All @@ -148,18 +143,14 @@ const InstanceTerminal: FC<Props> = ({ instance }) => {

data.binaryType = "arraybuffer";
data.onmessage = (message: MessageEvent<ArrayBuffer>) => {
xtermRef.current?.terminal.writeUtf8(new Uint8Array(message.data));
xtermRef.current?.write(new Uint8Array(message.data));
};

return [data, control];
};

useEffect(() => {
xtermRef.current?.terminal.focus();
}, [xtermRef.current, controlWs]);

useEffect(() => {
xtermRef.current?.terminal.clear();
xtermRef.current?.clear();
setInTabNotification(null);
const websocketPromise = openWebsockets(payload);
return () => {
Expand All @@ -176,13 +167,7 @@ const InstanceTerminal: FC<Props> = ({ instance }) => {

updateMaxHeight("p-terminal", undefined, 10);

xtermRef.current?.terminal.element?.style.setProperty("padding", "1rem");

// ensure options is not undefined. fitAddon.fit will crash otherwise
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (xtermRef.current && xtermRef.current.terminal.options === undefined) {
xtermRef.current.terminal.options = {};
}
xtermRef.current?.element?.style.setProperty("padding", "1rem");
fitAddon.fit();

const dimensions = fitAddon.proposeDimensions();
Expand All @@ -205,9 +190,11 @@ const InstanceTerminal: FC<Props> = ({ instance }) => {
handleResize();
setTimeout(handleResize, 500);
});
useLayoutEffect(() => {

const handleTerminalOpen = () => {
handleResize();
}, [controlWs, fitAddon, xtermRef]);
xtermRef.current?.focus();
};

const { handleStart, isLoading: isStartLoading } = useInstanceStart(instance);

Expand All @@ -224,15 +211,16 @@ const InstanceTerminal: FC<Props> = ({ instance }) => {
/>
{isLoading && <Loader text="Loading terminal session..." />}
{controlWs && (
<XTerm
<Xterm
ref={xtermRef}
addons={[fitAddon]}
className="p-terminal"
options={XTERM_OPTIONS}
onData={(data) => {
setUserInteracted(true);
dataWs?.send(textEncoder.encode(data));
}}
options={XTERM_OPTIONS}
onOpen={handleTerminalOpen}
className="p-terminal"
/>
)}
</>
Expand Down
Loading

0 comments on commit dca3e44

Please sign in to comment.