shellquest
Version:
Terminal-based procedurally generated dungeon crawler
45 lines (37 loc) • 1.14 kB
text/typescript
export function watchTerminalSize(cb: (w: number, h: number) => void, pollMs = 200) {
let w = process.stdout.columns || 80;
let h = process.stdout.rows || 24;
const fire = () => cb(w, h);
// Bun ≤ 1.2 on Windows: force-refresh before every read
const refreshIfNeeded = () => {
if (process.versions.bun && process.platform === 'win32') {
// ⚠️ private API, may change without notice
(process.stdout as any)._refreshSize?.();
}
};
const poll = () => {
refreshIfNeeded();
const nw = process.stdout.columns || 80;
const nh = process.stdout.rows || 24;
if (nw !== w || nh !== h) {
w = nw;
h = nh;
fire();
}
};
// 1️⃣ TTY “resize” (Node & future Bun)
if (process.stdout.isTTY) {
process.stdout.on?.('resize', () => {
refreshIfNeeded();
poll();
});
}
// 2️⃣ POSIX signal (works in WSL/WSA/Unix)
try {
process.on('SIGWINCH', poll);
} catch {}
// 3️⃣ fallback polling – covers current Bun on Windows & CI
setInterval(poll, pollMs);
// initial
fire();
}