/ ink / hooks / use-terminal-title.ts
use-terminal-title.ts
 1  import { useContext, useEffect } from 'react'
 2  import stripAnsi from 'strip-ansi'
 3  import { OSC, osc } from '../termio/osc.js'
 4  import { TerminalWriteContext } from '../useTerminalNotification.js'
 5  
 6  /**
 7   * Declaratively set the terminal tab/window title.
 8   *
 9   * Pass a string to set the title. ANSI escape sequences are stripped
10   * automatically so callers don't need to know about terminal encoding.
11   * Pass `null` to opt out — the hook becomes a no-op and leaves the
12   * terminal title untouched.
13   *
14   * On Windows, uses `process.title` (classic conhost doesn't support OSC).
15   * Elsewhere, writes OSC 0 (set title+icon) via Ink's stdout.
16   */
17  export function useTerminalTitle(title: string | null): void {
18    const writeRaw = useContext(TerminalWriteContext)
19  
20    useEffect(() => {
21      if (title === null || !writeRaw) return
22  
23      const clean = stripAnsi(title)
24  
25      if (process.platform === 'win32') {
26        process.title = clean
27      } else {
28        writeRaw(osc(OSC.SET_TITLE_AND_ICON, clean))
29      }
30    }, [title, writeRaw])
31  }