Line data Source code
1 : import { FitAddon } from '@xterm/addon-fit'
2 : import { Terminal } from '@xterm/xterm'
3 : import '@xterm/xterm/css/xterm.css'
4 : import { debounce } from 'es-toolkit/compat'
5 : import type { Ref } from 'vue'
6 : import { markRaw, onMounted, onUnmounted } from 'vue'
7 :
8 : import { isDesktop } from '@/platform/distribution/types'
9 :
10 24 : export function useTerminal(element: Ref<HTMLElement | undefined>) {
11 24 : const fitAddon = new FitAddon()
12 24 : const terminal = markRaw(
13 : new Terminal({
14 : convertEol: true,
15 : theme: isDesktop ? { background: '#171717' } : undefined
16 : })
17 : )
18 24 : terminal.loadAddon(fitAddon)
19 :
20 24 : terminal.attachCustomKeyEventHandler((event) => {
21 : // Allow default browser copy/paste handling
22 0 : if (
23 : event.type === 'keydown' &&
24 : (event.ctrlKey || event.metaKey) &&
25 : ((event.key === 'c' && terminal.hasSelection()) || event.key === 'v')
26 : ) {
27 : // TODO: Deselect text after copy/paste; use IPC.
28 0 : return false
29 : }
30 0 : return true
31 : })
32 :
33 24 : onMounted(async () => {
34 24 : if (element.value) {
35 24 : terminal.open(element.value)
36 : }
37 : })
38 :
39 24 : onUnmounted(() => {
40 6 : terminal.dispose()
41 : })
42 :
43 24 : return {
44 : terminal,
45 : useAutoSize({
46 : root,
47 : autoRows = true,
48 : autoCols = true,
49 : minCols = Number.NEGATIVE_INFINITY,
50 : minRows = Number.NEGATIVE_INFINITY,
51 : onResize
52 : }: {
53 : root: Ref<HTMLElement | undefined>
54 : autoRows?: boolean
55 : autoCols?: boolean
56 : minCols?: number
57 : minRows?: number
58 : onResize?: () => void
59 : }) {
60 24 : const ensureValidRows = (rows: number | undefined): number => {
61 68 : if (rows == null || isNaN(rows)) {
62 2 : return (root.value?.clientHeight ?? 80) / 20
63 : }
64 66 : return rows
65 : }
66 :
67 24 : const ensureValidCols = (cols: number | undefined): number => {
68 68 : if (cols == null || isNaN(cols)) {
69 : // Sometimes this is NaN if so, estimate.
70 42 : return (root.value?.clientWidth ?? 80) / 8
71 : }
72 26 : return cols
73 : }
74 :
75 24 : const resize = () => {
76 68 : const dims = fitAddon.proposeDimensions()
77 : // Sometimes propose returns NaN, so we may need to estimate.
78 68 : terminal.resize(
79 : Math.max(
80 : autoCols ? ensureValidCols(dims?.cols) : terminal.cols,
81 : minCols
82 : ),
83 : Math.max(
84 : autoRows ? ensureValidRows(dims?.rows) : terminal.rows,
85 : minRows
86 : )
87 : )
88 68 : onResize?.()
89 : }
90 :
91 24 : const resizeObserver = new ResizeObserver(debounce(resize, 25))
92 :
93 24 : onMounted(async () => {
94 24 : if (root.value) {
95 24 : resizeObserver.observe(root.value)
96 24 : resize()
97 : }
98 : })
99 :
100 24 : onUnmounted(() => {
101 6 : resizeObserver.disconnect()
102 : })
103 :
104 24 : return { resize }
105 : }
106 : }
107 : }
|