Files
rhema-together/web/app/components/TerminalPane.vue
T
vhaudiquet e579653f75 feat(web): bundle Fira Code Nerd Font for the terminal
Use Fira Code Nerd Font Mono in the monospace UI, including the
terminal. The font carries Nerd Font glyphs for prompts and tools, and
Fira Code's contextual ligatures apply in xterm's DOM renderer because
it groups same-style cells into spans.

The terminal waits for the regular and bold faces before opening so
xterm measures cell widths with the final font.
2026-11-28 10:48:10 +01:00

274 lines
7.1 KiB
Vue

<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
import '@xterm/xterm/css/xterm.css'
import type { FitAddon as FitAddonInstance } from '@xterm/addon-fit'
import type { Terminal as TerminalInstance } from '@xterm/xterm'
const props = defineProps<{ roomId: string }>()
type Status = 'connecting' | 'connected' | 'disconnected'
const host = ref<HTMLElement | null>(null)
const status = ref<Status>('connecting')
const detail = ref('')
const exitCode = ref<number | null>(null)
let term: TerminalInstance | null = null
let fit: FitAddonInstance | null = null
let socket: WebSocket | null = null
let observer: ResizeObserver | null = null
let resizeFrame = 0
let disposed = false
function token(name: string): string {
return getComputedStyle(document.documentElement).getPropertyValue(name).trim()
}
function terminalFontSize(): number {
return Number.parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--fs-code')) || 13
}
async function loadTerminalFont(fontFamily: string, fontSize: number): Promise<void> {
if (typeof document === 'undefined' || !document.fonts) return
try {
await Promise.all([
document.fonts.load(`400 ${fontSize}px ${fontFamily}`),
document.fonts.load(`700 ${fontSize}px ${fontFamily}`),
])
} catch {
// The terminal falls back to the system monospace font.
}
}
function terminalTheme() {
return {
background: token('--surface-2'),
foreground: token('--text'),
cursor: token('--accent'),
cursorAccent: token('--surface-2'),
selectionBackground: token('--accent-soft'),
black: token('--ansi-black'),
red: token('--ansi-red'),
green: token('--ansi-green'),
yellow: token('--ansi-yellow'),
blue: token('--ansi-blue'),
magenta: token('--ansi-magenta'),
cyan: token('--ansi-cyan'),
white: token('--ansi-white'),
brightBlack: token('--ansi-bright-black'),
brightRed: token('--ansi-bright-red'),
brightGreen: token('--ansi-bright-green'),
brightYellow: token('--ansi-bright-yellow'),
brightBlue: token('--ansi-bright-blue'),
brightMagenta: token('--ansi-bright-magenta'),
brightCyan: token('--ansi-bright-cyan'),
brightWhite: token('--ansi-bright-white'),
}
}
function sendResize() {
if (!term || !socket || socket.readyState !== WebSocket.OPEN) return
socket.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows }))
}
function fitTerminal() {
if (!fit) return
try {
fit.fit()
} catch {
return
}
sendResize()
}
function scheduleFit() {
if (typeof window === 'undefined') return
if (resizeFrame) window.cancelAnimationFrame(resizeFrame)
resizeFrame = window.requestAnimationFrame(() => {
resizeFrame = 0
fitTerminal()
})
}
function closeSocket() {
if (!socket) return
socket.onopen = null
socket.onmessage = null
socket.onerror = null
socket.onclose = null
try {
socket.close()
} catch {
// Already closed.
}
socket = null
}
function connect() {
if (disposed) return
closeSocket()
term?.reset()
status.value = 'connecting'
detail.value = ''
exitCode.value = null
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
const url = `${protocol}//${window.location.host}/api/rooms/${encodeURIComponent(props.roomId)}/terminal`
const next = new WebSocket(url)
next.binaryType = 'arraybuffer'
socket = next
next.onopen = () => {
if (socket !== next) return
scheduleFit()
}
next.onmessage = (event) => {
if (socket !== next) return
if (typeof event.data === 'string') {
try {
const message: unknown = JSON.parse(event.data)
if (!message || typeof message !== 'object') return
const type = 'type' in message ? message.type : null
if (type === 'ready') {
status.value = 'connected'
detail.value = ''
sendResize()
term?.focus()
} else if (type === 'error') {
status.value = 'disconnected'
detail.value = typeof (message as { message?: unknown }).message === 'string'
? String((message as { message: unknown }).message)
: 'The terminal reported an error.'
} else if (type === 'exit') {
status.value = 'disconnected'
const code = (message as { code?: unknown }).code
exitCode.value = typeof code === 'number' ? code : null
}
} catch {
return
}
return
}
if (event.data instanceof ArrayBuffer) {
term?.write(new Uint8Array(event.data))
} else if (event.data instanceof Blob) {
void event.data.arrayBuffer().then((buffer) => term?.write(new Uint8Array(buffer)))
}
}
next.onerror = () => {
if (socket !== next) return
if (status.value !== 'disconnected') {
status.value = 'disconnected'
detail.value = 'The connection failed.'
}
}
next.onclose = () => {
if (socket !== next) return
socket = null
if (status.value !== 'disconnected') {
status.value = 'disconnected'
detail.value = 'The connection closed.'
}
}
}
function reconnect() {
connect()
}
onMounted(async () => {
await nextTick()
const [{ Terminal }, { FitAddon }] = await Promise.all([
import('@xterm/xterm'),
import('@xterm/addon-fit'),
])
if (!host.value) return
const fontFamily = getComputedStyle(document.documentElement).getPropertyValue('--font-mono').trim()
const fontSize = terminalFontSize()
await loadTerminalFont(fontFamily, fontSize)
term = new Terminal({
convertEol: false,
cursorBlink: true,
fontFamily,
fontSize,
fontWeight: 400,
fontWeightBold: 700,
letterSpacing: 0,
lineHeight: 1.2,
scrollback: 3000,
theme: terminalTheme(),
})
fit = new FitAddon()
term.loadAddon(fit)
term.open(host.value)
term.onData((data) => {
if (!socket || socket.readyState !== WebSocket.OPEN) return
socket.send(new TextEncoder().encode(data))
})
observer = new ResizeObserver(() => {
scheduleFit()
})
observer.observe(host.value)
term.focus()
scheduleFit()
connect()
})
onBeforeUnmount(() => {
disposed = true
if (observer) {
observer.disconnect()
observer = null
}
if (resizeFrame) {
window.cancelAnimationFrame(resizeFrame)
resizeFrame = 0
}
closeSocket()
term?.dispose()
term = null
fit = null
})
const statusText = computed(() => {
if (status.value === 'connected') return 'Connected'
if (status.value === 'connecting') return 'Connecting'
return 'Disconnected'
})
function focusTerminal() {
term?.focus()
}
</script>
<template>
<div class="terminal-wrap">
<div class="terminal-bar">
<span class="terminal-status">
{{ statusText }}
<template v-if="exitCode !== null">, exit {{ exitCode }}</template>
</span>
<button
type="button"
class="btn btn-sm"
:disabled="status === 'connecting'"
aria-label="Reconnect terminal"
title="Reconnect terminal"
@click="reconnect"
>
Reconnect
</button>
</div>
<p v-if="detail" class="form-error pane-pad">{{ detail }}</p>
<div ref="host" class="terminal-host" @click="focusTerminal" />
</div>
</template>