| 1 | import { useStdout } from "ink"; |
| 2 | import { useEffect, useState } from "react"; |
| 3 | |
| 4 | const DEFAULT_ROWS = 24; |
| 5 | const DEFAULT_COLS = 80; |
| 6 | |
| 7 | const useTerminalSize = (debounce = 100) => { |
| 8 | const { stdout } = useStdout(); |
| 9 | const [dimensions, setDimensions] = useState({ |
| 10 | columns: stdout.columns || DEFAULT_COLS, |
| 11 | rows: stdout.rows || DEFAULT_ROWS, |
| 12 | }); |
| 13 | const [isResizing, setIsResizing] = useState(false); |
| 14 | |
| 15 | useEffect(() => { |
| 16 | let debounceTimer: NodeJS.Timeout | null = null; |
| 17 | |
| 18 | const handleResize = () => { |
| 19 | setIsResizing(true); |
| 20 | |
| 21 | if (debounceTimer) { |
| 22 | clearTimeout(debounceTimer); |
| 23 | } |
| 24 | |
| 25 | debounceTimer = setTimeout(() => { |
| 26 | setDimensions({ |
| 27 | columns: stdout.columns || DEFAULT_COLS, |
| 28 | rows: stdout.rows || DEFAULT_ROWS, |
| 29 | }); |
| 30 | setIsResizing(false); |
| 31 | }, debounce); |
| 32 | }; |
| 33 | |
| 34 | stdout.on("resize", handleResize); |
| 35 | return () => { |
| 36 | stdout.removeListener("resize", handleResize); |
| 37 | if (debounceTimer) { |
| 38 | clearTimeout(debounceTimer); |
| 39 | } |
| 40 | }; |
| 41 | }, [stdout, debounce]); |
| 42 | |
| 43 | return { ...dimensions, isResizing }; |
| 44 | }; |
| 45 | |
| 46 | export { useTerminalSize }; |