BBS/public/terminal.js

218 lines
7.4 KiB
JavaScript

(function () {
const PHONE = '1-303-674-5489';
const DIGITS = PHONE.replace(/\D/g, '');
const FONT = '"Perfect DOS VGA 437", "Px437 IBM VGA 8x16", Consolas, "DejaVu Sans Mono", "Courier New", monospace';
const audio = window.ModemAudio;
// Classic CGA/VGA 16-colour palette
const theme = {
background: '#000000', foreground: '#aaaaaa', cursor: '#aaaaaa', cursorAccent: '#000000',
black: '#000000', red: '#aa0000', green: '#00aa00', yellow: '#aa5500',
blue: '#0000aa', magenta: '#aa00aa', cyan: '#00aaaa', white: '#aaaaaa',
brightBlack: '#555555', brightRed: '#ff5555', brightGreen: '#55ff55', brightYellow: '#ffff55',
brightBlue: '#5555ff', brightMagenta: '#ff55ff', brightCyan: '#55ffff', brightWhite: '#ffffff',
};
const term = new Terminal({
cols: 80, rows: 25, scrollback: 0, cursorBlink: true, cursorStyle: 'underline',
fontFamily: FONT, fontSize: 16, lineHeight: 1, theme, allowTransparency: false,
customGlyphs: true, drawBoldTextInBrightColors: true,
});
term.open(document.getElementById('terminal'));
// ---- layout: scale the font so a full 80x25 screen fits the window ----
const screenEl = document.getElementById('terminal');
const statusEl = document.getElementById('status');
function fit() {
const availW = window.innerWidth - 90;
const availH = window.innerHeight - statusEl.offsetHeight - 90;
for (let i = 0; i < 4; i++) {
const r = screenEl.querySelector('.xterm-screen').getBoundingClientRect();
if (!r.width || !r.height) return;
const size = term.options.fontSize;
const next = Math.max(8, Math.floor(size * Math.min(availW / r.width, availH / r.height)));
if (next === size) break;
term.options.fontSize = next;
}
}
window.addEventListener('resize', fit);
(document.fonts ? document.fonts.ready : Promise.resolve()).then(fit);
fit();
// ---- status bar --------------------------------------------------------
const st = {
state: document.getElementById('st-state'),
timer: document.getElementById('st-timer'),
speed: document.getElementById('st-speed'),
node: document.getElementById('st-node'),
sound: document.getElementById('st-sound'),
};
let onlineSince = 0;
let timerId = null;
function setState(label, cls) {
st.state.textContent = label;
st.state.className = cls || '';
}
function startTimer() {
onlineSince = Date.now();
clearInterval(timerId);
timerId = setInterval(() => {
const s = Math.floor((Date.now() - onlineSince) / 1000);
const p = (n) => String(n).padStart(2, '0');
st.timer.textContent = `${p(Math.floor(s / 3600))}:${p(Math.floor(s / 60) % 60)}:${p(s % 60)}`;
}, 1000);
}
function stopTimer() { clearInterval(timerId); }
function loadSoundPref() {
try { return localStorage.getItem('bbs-sound') !== 'off'; } catch (e) { return true; }
}
function renderSound() { st.sound.textContent = audio.enabled ? 'SOUND: ON' : 'SOUND: OFF'; }
audio.enabled = loadSoundPref();
renderSound();
st.sound.addEventListener('click', () => {
audio.enabled = !audio.enabled;
try { localStorage.setItem('bbs-sound', audio.enabled ? 'on' : 'off'); } catch (e) { /* ignore */ }
if (!audio.enabled) audio.skip();
renderSound();
term.focus();
});
// ---- connection state machine -----------------------------------------
let state = 'idle'; // idle | dialing | online | offline
let ws = null;
let lineBaud = 14400;
function intro() {
term.reset();
term.write('\x1b[0;37;44m\x1b[2K ModemTerm v1.4 (c) 1991 Basement Softworks \x1b[0m\r\n\r\n');
term.write('\x1b[96m Dialing Directory\x1b[0m\r\n');
term.write('\x1b[90m ' + '─'.repeat(74) + '\x1b[0m\r\n');
term.write('\x1b[97m 1. \x1b[95mWarezHou$e BBS \x1b[90m.................... \x1b[97m' + PHONE + ' \x1b[37m14400 N81 ANSI\x1b[0m\r\n');
term.write('\x1b[90m ' + '─'.repeat(74) + '\x1b[0m\r\n\r\n');
term.write('\x1b[37m COM2: 14400 baud, 8 data bits, no parity, 1 stop bit\x1b[0m\r\n\r\n');
term.write('\x1b[93m Press any key to dial...\x1b[0m\x1b[90m (ESC skips the handshake)\x1b[0m');
setState('OFFLINE');
}
function wait(ms) { return audio.wait(ms); }
async function type(text, cps = 28) {
for (const ch of text) {
term.write(ch);
await wait(1000 / cps);
}
term.write('\r\n');
}
function openLine() {
return new Promise((resolve) => {
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
const sock = new WebSocket(`${proto}://${location.host}/ws`);
ws = sock;
let answered = false;
sock.onmessage = (ev) => {
let msg;
try { msg = JSON.parse(ev.data); } catch (e) { return; }
if (msg.t === 'ring' && !answered) {
answered = true;
lineBaud = msg.baud || 115200;
st.node.textContent = `NODE ${msg.node}`;
resolve('ring');
} else if (msg.t === 'busy' && !answered) {
answered = true;
resolve('busy');
} else if (msg.t === 'd' && state === 'online') {
term.write(msg.d);
} else if (msg.t === 'hangup') {
noCarrier();
}
};
sock.onerror = () => { if (!answered) { answered = true; resolve('error'); } };
sock.onclose = () => {
if (ws === sock) ws = null;
if (!answered) { answered = true; resolve('error'); }
if (state === 'online') noCarrier();
};
});
}
async function dial() {
state = 'dialing';
setState('DIALING', 'dialing');
st.timer.textContent = '00:00:00';
audio.reset();
audio.init();
term.reset();
term.write('\x1b[37m');
await type('ATZ');
await wait(250);
term.write('OK\r\n');
await wait(300);
await type('ATDT ' + PHONE);
const answer = openLine();
await audio.dialTone();
await audio.dial(DIGITS);
const result = await answer;
if (result === 'busy') {
await audio.busy();
term.write('BUSY\r\n');
return offline('All nodes are busy. Try again in a few minutes.');
}
if (result !== 'ring') {
await wait(1500);
term.write('NO ANSWER\r\n');
return offline('The BBS did not answer.');
}
term.write('RINGING\r\n');
await audio.ringback();
await audio.handshake();
if (!ws || ws.readyState !== WebSocket.OPEN) {
term.write('NO CARRIER\r\n');
return offline();
}
term.write(`CONNECT ${lineBaud}/ARQ/V32BIS/LAPM/V42BIS\r\n\x1b[0m`);
st.speed.textContent = `${lineBaud} 8N1`;
setState('ONLINE', 'online');
startTimer();
state = 'online';
ws.send(JSON.stringify({ t: 'start' }));
}
function offline(note) {
state = 'offline';
setState('OFFLINE');
stopTimer();
if (ws) { try { ws.close(); } catch (e) { /* ignore */ } ws = null; }
if (note) term.write(`\r\n\x1b[90m${note}\x1b[0m\r\n`);
term.write('\r\n\x1b[93mPress any key to redial...\x1b[0m');
}
function noCarrier() {
if (state !== 'online') return;
term.write('\x1b[0m\r\n\r\nNO CARRIER\r\n');
offline();
}
term.onData((data) => {
if (state === 'online') {
if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ t: 'd', d: data }));
} else if (state === 'dialing') {
if (data === '\x1b') audio.skip();
} else {
dial().catch((err) => {
console.error(err);
offline('Modem error.');
});
}
});
document.addEventListener('click', () => term.focus());
intro();
term.focus();
})();