188 lines
5.1 KiB
TypeScript
188 lines
5.1 KiB
TypeScript
import '@fontsource/jetbrains-mono/400.css';
|
|
import '@fontsource/jetbrains-mono/700.css';
|
|
import '@xterm/xterm/css/xterm.css';
|
|
import './style.css';
|
|
|
|
import { FitAddon } from '@xterm/addon-fit';
|
|
import { WebLinksAddon } from '@xterm/addon-web-links';
|
|
import { WebglAddon } from '@xterm/addon-webgl';
|
|
import { Terminal } from '@xterm/xterm';
|
|
import { CONNECTING_MESSAGE, endMessage, playBoot, queueMessage, solvingMessage } from './boot.ts';
|
|
import { TerminalConnection, terminalUrl, type EndReason, type Ready } from './connection.ts';
|
|
import { createKeybar } from './keybar.ts';
|
|
import { savedToken } from './token.ts';
|
|
|
|
type State = 'booting' | 'idle' | 'connecting' | 'active' | 'reconnecting';
|
|
|
|
/** Reconnecting stops shortly before the server's grace period would end anyway. */
|
|
const RECONNECT_DEADLINE_MS = 40_000;
|
|
const RECONNECT_DELAYS_MS = [500, 1000, 2000, 4000, 8000];
|
|
|
|
const touch = window.matchMedia('(pointer: coarse)').matches;
|
|
const element = document.getElementById('terminal')!;
|
|
const notice = document.getElementById('notice')!;
|
|
|
|
const terminal = new Terminal({
|
|
fontFamily: '"JetBrains Mono", monospace',
|
|
fontSize: touch ? 13 : 15,
|
|
cursorBlink: true,
|
|
scrollback: 5000,
|
|
theme: {
|
|
background: '#0b0d10',
|
|
foreground: '#d6dde6',
|
|
cursor: '#7ee787',
|
|
selectionBackground: '#2b3a4a',
|
|
},
|
|
});
|
|
|
|
// The key bar takes its space before the first fit, so the grid never overflows.
|
|
if (touch)
|
|
{
|
|
createKeybar(document.getElementById('keybar')!, () => terminal.modes.applicationCursorKeysMode, input);
|
|
element.addEventListener('click', () => { if (state === 'idle') start(); });
|
|
}
|
|
|
|
const fit = new FitAddon();
|
|
terminal.loadAddon(fit);
|
|
terminal.loadAddon(new WebLinksAddon());
|
|
|
|
// Measuring cells before the font is ready would size the grid wrongly.
|
|
await Promise.all([document.fonts.load('15px "JetBrains Mono"'), document.fonts.load('bold 15px "JetBrains Mono"')]);
|
|
terminal.open(element);
|
|
|
|
try
|
|
{
|
|
const webgl = new WebglAddon();
|
|
webgl.onContextLoss(() => webgl.dispose());
|
|
terminal.loadAddon(webgl);
|
|
}
|
|
catch { /* The DOM renderer remains as a fallback without WebGL. */ }
|
|
|
|
fit.fit();
|
|
terminal.focus();
|
|
|
|
let state: State = 'booting';
|
|
let connection: TerminalConnection | undefined;
|
|
let reconnectStarted = 0;
|
|
let reconnectAttempt = 0;
|
|
|
|
function showNotice(text: string): void
|
|
{
|
|
notice.textContent = text;
|
|
notice.hidden = false;
|
|
}
|
|
|
|
function hideNotice(): void {
|
|
notice.hidden = true;
|
|
}
|
|
|
|
function size() {
|
|
return { cols: terminal.cols, rows: terminal.rows };
|
|
}
|
|
|
|
/**
|
|
* Opens a connection. With a token it resumes; after a page reload the
|
|
* screen is empty, so Ctrl-L asks the shell or program to redraw itself.
|
|
*/
|
|
function connect(token?: string, redraw = false): void
|
|
{
|
|
connection = new TerminalConnection(terminalUrl(window.location), size(), token, {
|
|
solving: (difficulty) => terminal.write(solvingMessage(difficulty)),
|
|
queued: (position) => terminal.write(queueMessage(position)),
|
|
ready: (session: Ready) =>
|
|
{
|
|
savedToken.set(session.token);
|
|
hideNotice();
|
|
reconnectAttempt = 0;
|
|
|
|
if (!session.resumed) terminal.reset();
|
|
state = 'active';
|
|
terminal.focus();
|
|
|
|
if (session.resumed && redraw) connection?.input('\x0c');
|
|
},
|
|
output: (data) => terminal.write(data),
|
|
idle: (secondsLeft) => showNotice(`no input for a while, the session ends in ${secondsLeft} seconds unless you type`),
|
|
ended: (reason) => ended(reason),
|
|
});
|
|
}
|
|
|
|
function ended(reason: EndReason): void
|
|
{
|
|
connection = undefined;
|
|
|
|
const dropped = reason === 'lost' || reason === 'rejected';
|
|
if (dropped && (state === 'active' || state === 'reconnecting') && savedToken.get())
|
|
{
|
|
reconnect();
|
|
return;
|
|
}
|
|
|
|
savedToken.clear();
|
|
hideNotice();
|
|
|
|
if (state === 'booting')
|
|
{
|
|
void boot();
|
|
return;
|
|
}
|
|
|
|
state = 'idle';
|
|
terminal.write(endMessage(reason, touch));
|
|
}
|
|
|
|
function reconnect(): void
|
|
{
|
|
if (state !== 'reconnecting')
|
|
{
|
|
state = 'reconnecting';
|
|
reconnectStarted = Date.now();
|
|
}
|
|
|
|
if (Date.now() - reconnectStarted > RECONNECT_DEADLINE_MS)
|
|
{
|
|
state = 'active';
|
|
savedToken.clear();
|
|
ended('lost');
|
|
return;
|
|
}
|
|
|
|
showNotice('connection lost, reconnecting...');
|
|
const delay = RECONNECT_DELAYS_MS[Math.min(reconnectAttempt++, RECONNECT_DELAYS_MS.length - 1)];
|
|
setTimeout(() => connect(savedToken.get()), delay);
|
|
}
|
|
|
|
function start(): void
|
|
{
|
|
state = 'connecting';
|
|
terminal.write(CONNECTING_MESSAGE);
|
|
connect();
|
|
}
|
|
|
|
function input(data: string): void
|
|
{
|
|
if (state === 'active')
|
|
{
|
|
hideNotice();
|
|
connection?.input(data);
|
|
}
|
|
else if (state === 'idle') start();
|
|
}
|
|
|
|
async function boot(): Promise<void>
|
|
{
|
|
state = 'booting';
|
|
await playBoot(terminal, touch);
|
|
state = 'idle';
|
|
}
|
|
|
|
terminal.onData(input);
|
|
terminal.onBinary((data) => { if (state === 'active') connection?.inputBinary(data); });
|
|
terminal.onResize(({ cols, rows }) => connection?.resize({ cols, rows }));
|
|
new ResizeObserver(() => fit.fit()).observe(element);
|
|
|
|
// A reload within the grace period picks the running sandbox up again.
|
|
const token = savedToken.get();
|
|
if (token) connect(token, true);
|
|
else void boot();
|