Add Ctrl+Click to open links in terminal

Implement URL detection from PTY output since Restty's canvas-based
rendering doesn't expose a text layer for link detection.

- TerminalLinkDetector tracks PTY output, strips ANSI codes, and
  maintains a line buffer to detect URLs at screen positions
- Each pane gets its own detector fed via beforeRenderOutput hook
- Ctrl+Click (or Cmd+Click) on a detected URL opens it in the
  default browser via shell.openExternal
- Ctrl+hover shows pointer cursor when over a URL, reverts on release

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Matheus Nogueira
2026-03-19 21:29:39 -03:00
co-authored by Claude Opus 4.6
parent 032362bd13
commit c13d8a725e
3 changed files with 219 additions and 45 deletions
+112 -2
View File
@@ -35,6 +35,7 @@ import {
resolvePaneStyleOptions,
resolveEffectiveTerminalAppearance
} from '@/lib/terminal-theme'
import { TerminalLinkDetector } from '@/lib/terminal-link-detector'
type PtyTransport = {
connect: (options: {
@@ -363,6 +364,8 @@ export default function TerminalPane({
}: TerminalPaneProps): React.JSX.Element {
const containerRef = useRef<HTMLDivElement>(null)
const resttyRef = useRef<Restty | null>(null)
const linkDetectorsRef = useRef<Map<number, TerminalLinkDetector>>(new Map())
const cellSizeRef = useRef<{ w: number; h: number }>({ w: 0, h: 0 })
const contextPaneIdRef = useRef<number | null>(null)
const wasActiveRef = useRef(false)
const expandedPaneIdRef = useRef<number | null>(null)
@@ -619,6 +622,11 @@ export default function TerminalPane({
}
restty.closePane(id)
}
// Link detector for this pane
const linkDetector = new TerminalLinkDetector()
linkDetectorsRef.current.set(id, linkDetector)
return {
renderer: 'auto',
fontSize: currentSettings?.terminalFontSize ?? 14,
@@ -632,7 +640,17 @@ export default function TerminalPane({
onPtySpawn,
onBell
) as never,
fontSources: buildTerminalFontSources(currentSettings?.terminalFontFamily ?? 'SF Mono')
fontSources: buildTerminalFontSources(currentSettings?.terminalFontFamily ?? 'SF Mono'),
callbacks: {
onGridSize: (cols: number, rows: number) => linkDetector.setGridSize(cols, rows),
onCellSize: (cellW: number, cellH: number) => {
cellSizeRef.current = { w: cellW, h: cellH }
}
},
beforeRenderOutput: (payload: { text: string; source: string }) => {
if (payload.source === 'pty') linkDetector.feed(payload.text)
return payload.text
}
}
},
onPaneCreated: async (pane) => {
@@ -643,7 +661,9 @@ export default function TerminalPane({
pane.canvas.focus({ preventScroll: true })
queueResizeAll(true)
},
onPaneClosed: () => {},
onPaneClosed: (pane) => {
linkDetectorsRef.current.delete(pane.id)
},
onActivePaneChange: () => {
if (shouldPersistLayout) persistLayoutSnapshot()
},
@@ -687,6 +707,7 @@ export default function TerminalPane({
restoreExpandedLayout()
restty.destroy()
resttyRef.current = null
linkDetectorsRef.current.clear()
setTabPaneExpanded(tabId, false)
setTabCanExpandPane(tabId, false)
}
@@ -845,6 +866,95 @@ export default function TerminalPane({
return () => window.removeEventListener('keydown', onKeyDown, { capture: true })
}, [isActive])
// Ctrl+Click to open terminal links and Ctrl+hover for pointer cursor
useEffect(() => {
if (!isActive) return
const container = containerRef.current
if (!container) return
const resolveClickPane = (target: Node) => {
const restty = resttyRef.current
if (!restty) return null
return restty.getPanes().find((pane) => pane.container.contains(target)) ?? null
}
const getCellAtEvent = (e: MouseEvent, canvas: HTMLCanvasElement) => {
const { w, h } = cellSizeRef.current
if (!w || !h) return null
const rect = canvas.getBoundingClientRect()
const x = e.clientX - rect.left
const y = e.clientY - rect.top
return { col: Math.floor(x / w), row: Math.floor(y / h) }
}
const onPointerUp = (e: PointerEvent): void => {
if (e.button !== 0) return
if (!e.ctrlKey && !e.metaKey) return
if (!(e.target instanceof Node)) return
const pane = resolveClickPane(e.target)
if (!pane) return
const cell = getCellAtEvent(e, pane.canvas)
if (!cell) return
const detector = linkDetectorsRef.current.get(pane.id)
const url = detector?.getLinkAt(cell.row, cell.col)
if (url) {
e.preventDefault()
e.stopPropagation()
window.api.shell.openExternal(url)
}
}
const onPointerMove = (e: PointerEvent): void => {
if (!e.ctrlKey && !e.metaKey) {
// Restore cursor when Ctrl is released while moving
for (const canvas of container.querySelectorAll('canvas')) {
if ((canvas as HTMLCanvasElement).style.cursor === 'pointer') {
;(canvas as HTMLCanvasElement).style.cursor = ''
}
}
return
}
if (!(e.target instanceof Node)) return
const pane = resolveClickPane(e.target)
if (!pane) return
const cell = getCellAtEvent(e, pane.canvas)
if (!cell) return
const detector = linkDetectorsRef.current.get(pane.id)
const hasLink = detector?.hasLinkAt(cell.row, cell.col) ?? false
pane.canvas.style.cursor = hasLink ? 'pointer' : ''
}
const onKeyDown = (e: KeyboardEvent): void => {
if (e.key === 'Control' || e.key === 'Meta') {
// Trigger a cursor check when Ctrl/Cmd is pressed
// (onPointerMove won't fire until the mouse moves)
}
}
const onKeyUp = (e: KeyboardEvent): void => {
if (e.key === 'Control' || e.key === 'Meta') {
for (const canvas of container.querySelectorAll('canvas')) {
if ((canvas as HTMLCanvasElement).style.cursor === 'pointer') {
;(canvas as HTMLCanvasElement).style.cursor = ''
}
}
}
}
container.addEventListener('pointerup', onPointerUp, { capture: true })
container.addEventListener('pointermove', onPointerMove)
window.addEventListener('keyup', onKeyUp)
return () => {
container.removeEventListener('pointerup', onPointerUp, { capture: true })
container.removeEventListener('pointermove', onPointerMove)
window.removeEventListener('keyup', onKeyUp)
}
}, [isActive])
const resolveMenuPane = () => {
const restty = resttyRef.current
if (!restty) return null
@@ -0,0 +1,107 @@
/**
* Detects URLs in terminal output by tracking PTY data and maintaining
* a simplified screen buffer. Supports Ctrl+Click to open links.
*/
// Matches http(s) URLs and bare domain-style URLs (e.g. github.com/foo)
const URL_RE =
/https?:\/\/[^\s<>"'`)\]},;]+|(?:[\w-]+\.)+(?:com|org|net|io|dev|app|co|me|sh|cc|info|xyz|ai)(?:\/[^\s<>"'`)\]},;]*)*/g
// Strips most common ANSI escape sequences (SGR, cursor, erase, OSC, etc.)
const ANSI_RE =
// eslint-disable-next-line no-control-regex
/\x1b\[[0-9;]*[A-Za-z]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][AB012]|\x1b[>=<]|\x1b\x1b|\x1b./g
export type TerminalLink = { url: string; col: number; len: number }
export class TerminalLinkDetector {
private lines: string[] = []
private cols = 80
private rows = 24
private cursorRow = 0
/** Update grid dimensions (call on terminal resize). */
setGridSize(cols: number, rows: number): void {
this.cols = cols
this.rows = rows
// Resize line buffer to match visible rows
while (this.lines.length < rows) this.lines.push('')
if (this.lines.length > rows) this.lines.length = rows
if (this.cursorRow >= rows) this.cursorRow = rows - 1
}
/** Feed a chunk of raw PTY output. */
feed(data: string): void {
// Strip ANSI escape sequences to get visible text
const clean = data.replace(ANSI_RE, '')
for (let i = 0; i < clean.length; i++) {
const ch = clean[i]
if (ch === '\n') {
this.cursorRow++
if (this.cursorRow >= this.rows) {
// Scroll: shift lines up
this.lines.shift()
this.lines.push('')
this.cursorRow = this.rows - 1
}
continue
}
if (ch === '\r') {
// Carriage return: overwrite current line from start
this.lines[this.cursorRow] = ''
continue
}
// eslint-disable-next-line no-control-regex
if (ch.charCodeAt(0) < 0x20) continue // skip other control chars
// Append character to current line
this.lines[this.cursorRow] = (this.lines[this.cursorRow] ?? '') + ch
}
}
/** Clear the screen buffer (e.g. on Ctrl+L / clear). */
clear(): void {
this.lines = Array.from({ length: this.rows }, () => '')
this.cursorRow = 0
}
/** Find all URLs in the line at the given row. */
getLinksAtRow(row: number): TerminalLink[] {
const line = this.lines[row]
if (!line) return []
const links: TerminalLink[] = []
let match: RegExpExecArray | null
URL_RE.lastIndex = 0
while ((match = URL_RE.exec(line)) !== null) {
let url = match[0]
// Strip trailing punctuation that's unlikely part of the URL
url = url.replace(/[.,;:!?)]+$/, '')
// Ensure http(s) prefix for bare domains
if (!url.startsWith('http://') && !url.startsWith('https://')) {
url = 'https://' + url
}
links.push({ url, col: match.index, len: match[0].length })
}
return links
}
/** Find the URL at a specific row/col, or null. */
getLinkAt(row: number, col: number): string | null {
for (const link of this.getLinksAtRow(row)) {
if (col >= link.col && col < link.col + link.len) {
return link.url
}
}
return null
}
/** Check if there is any URL at the given row/col. */
hasLinkAt(row: number, col: number): boolean {
return this.getLinkAt(row, col) !== null
}
}
-43
View File
@@ -13,49 +13,6 @@ function applySystemTheme(): void {
applySystemTheme()
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', applySystemTheme)
// ---------------------------------------------------------------------------
// Ctrl+Click to open terminal links
// ---------------------------------------------------------------------------
// Restty (the terminal renderer) detects URLs in terminal output and calls
// window.open() on any left-click over a detected link. In Electron,
// window.open with "noopener,noreferrer" may not properly trigger
// setWindowOpenHandler. We override window.open to:
// 1. Route http/https URLs through shell.openExternal (reliable in Electron)
// 2. Only open when Ctrl (Linux/Windows) or Cmd (macOS) was held — matching
// the standard Ctrl+Click-to-open-link UX in terminals like VS Code.
// ---------------------------------------------------------------------------
let lastPointerModifiers = { ctrlKey: false, metaKey: false }
window.addEventListener(
'pointerup',
(e) => {
lastPointerModifiers = { ctrlKey: e.ctrlKey, metaKey: e.metaKey }
},
{ capture: true }
)
const originalWindowOpen = window.open.bind(window)
window.open = function (
url?: string | URL,
target?: string,
features?: string
): WindowProxy | null {
if (url) {
const urlStr = url.toString()
try {
const parsed = new URL(urlStr)
if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
if (lastPointerModifiers.ctrlKey || lastPointerModifiers.metaKey) {
window.api.shell.openExternal(urlStr)
}
return null
}
} catch {
// not a valid URL — fall through to original
}
}
return originalWindowOpen(url, target, features)
} as typeof window.open
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />