|
| 1 | +/** |
| 2 | + * Force Auto-Scroll for ttyd/xterm.js |
| 3 | + * |
| 4 | + * This script is injected into ttyd's HTML page to override xterm.js scroll behavior. |
| 5 | + * It ensures the terminal always scrolls to bottom when new content arrives, |
| 6 | + * even if the user has scrolled up to view history. |
| 7 | + * |
| 8 | + * Strategy: |
| 9 | + * 1. Wait for xterm.js instance (window.term) |
| 10 | + * 2. Hook into data/write events |
| 11 | + * 3. Force scroll to bottom during active streaming |
| 12 | + * 4. Report status to parent window via postMessage |
| 13 | + */ |
| 14 | + |
| 15 | +(function() { |
| 16 | + 'use strict'; |
| 17 | + |
| 18 | + const DEBUG = true; |
| 19 | + const log = (...args) => DEBUG && console.log('[AutoScroll]', ...args); |
| 20 | + |
| 21 | + log('Initializing...'); |
| 22 | + |
| 23 | + // Configuration |
| 24 | + const CONFIG = { |
| 25 | + // Time window to consider "active streaming" (ms) |
| 26 | + STREAMING_WINDOW: 800, |
| 27 | + // Scroll check interval during streaming (ms) |
| 28 | + SCROLL_INTERVAL: 100, |
| 29 | + // Idle timeout before stopping scroll checks (ms) |
| 30 | + IDLE_TIMEOUT: 2000, |
| 31 | + }; |
| 32 | + |
| 33 | + /** |
| 34 | + * Wait for xterm.js instance to be available |
| 35 | + */ |
| 36 | + function waitForTerminal() { |
| 37 | + return new Promise((resolve) => { |
| 38 | + const startTime = Date.now(); |
| 39 | + const checkInterval = setInterval(() => { |
| 40 | + if (window.term && window.term.element) { |
| 41 | + clearInterval(checkInterval); |
| 42 | + log(`✓ Terminal found after ${Date.now() - startTime}ms`); |
| 43 | + resolve(window.term); |
| 44 | + } |
| 45 | + |
| 46 | + // Timeout after 10 seconds |
| 47 | + if (Date.now() - startTime > 10000) { |
| 48 | + clearInterval(checkInterval); |
| 49 | + log('✗ Terminal not found (timeout)'); |
| 50 | + resolve(null); |
| 51 | + } |
| 52 | + }, 50); |
| 53 | + }); |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * Check if terminal is at bottom |
| 58 | + */ |
| 59 | + function isAtBottom(term) { |
| 60 | + try { |
| 61 | + const viewport = term.element.querySelector('.xterm-viewport'); |
| 62 | + if (!viewport) return true; |
| 63 | + |
| 64 | + const scrollTop = viewport.scrollTop; |
| 65 | + const scrollHeight = viewport.scrollHeight; |
| 66 | + const clientHeight = viewport.clientHeight; |
| 67 | + |
| 68 | + // Consider "at bottom" if within 50px |
| 69 | + return scrollTop + clientHeight >= scrollHeight - 50; |
| 70 | + } catch (e) { |
| 71 | + return true; |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + /** |
| 76 | + * Force scroll to bottom |
| 77 | + */ |
| 78 | + function forceScrollToBottom(term) { |
| 79 | + try { |
| 80 | + term.scrollToBottom(); |
| 81 | + } catch (e) { |
| 82 | + log('Error scrolling:', e); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + /** |
| 87 | + * Notify parent window about scroll status |
| 88 | + */ |
| 89 | + function notifyParent(status) { |
| 90 | + try { |
| 91 | + window.parent.postMessage({ |
| 92 | + type: 'ttyd-scroll-status', |
| 93 | + status: status, |
| 94 | + timestamp: Date.now(), |
| 95 | + }, '*'); |
| 96 | + } catch (e) { |
| 97 | + // Ignore postMessage errors |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + /** |
| 102 | + * Main auto-scroll logic |
| 103 | + */ |
| 104 | + async function initAutoScroll() { |
| 105 | + const term = await waitForTerminal(); |
| 106 | + if (!term) { |
| 107 | + log('✗ Failed to initialize - terminal not found'); |
| 108 | + return; |
| 109 | + } |
| 110 | + |
| 111 | + log('✓ Terminal instance detected'); |
| 112 | + |
| 113 | + let lastActivityTime = 0; |
| 114 | + let scrollInterval = null; |
| 115 | + let isStreaming = false; |
| 116 | + |
| 117 | + /** |
| 118 | + * Start aggressive auto-scroll during streaming |
| 119 | + */ |
| 120 | + function startScrolling() { |
| 121 | + if (scrollInterval) return; |
| 122 | + |
| 123 | + isStreaming = true; |
| 124 | + notifyParent('streaming'); |
| 125 | + log('→ Streaming detected, starting auto-scroll'); |
| 126 | + |
| 127 | + scrollInterval = setInterval(() => { |
| 128 | + const timeSinceActivity = Date.now() - lastActivityTime; |
| 129 | + |
| 130 | + // Active streaming: force scroll |
| 131 | + if (timeSinceActivity < CONFIG.STREAMING_WINDOW) { |
| 132 | + forceScrollToBottom(term); |
| 133 | + } |
| 134 | + // Idle for too long: stop scrolling |
| 135 | + else if (timeSinceActivity > CONFIG.IDLE_TIMEOUT) { |
| 136 | + stopScrolling(); |
| 137 | + } |
| 138 | + }, CONFIG.SCROLL_INTERVAL); |
| 139 | + } |
| 140 | + |
| 141 | + /** |
| 142 | + * Stop auto-scroll when idle |
| 143 | + */ |
| 144 | + function stopScrolling() { |
| 145 | + if (!scrollInterval) return; |
| 146 | + |
| 147 | + clearInterval(scrollInterval); |
| 148 | + scrollInterval = null; |
| 149 | + isStreaming = false; |
| 150 | + notifyParent('idle'); |
| 151 | + log('→ Streaming stopped, auto-scroll disabled'); |
| 152 | + } |
| 153 | + |
| 154 | + /** |
| 155 | + * Record activity and trigger scrolling |
| 156 | + */ |
| 157 | + function recordActivity() { |
| 158 | + lastActivityTime = Date.now(); |
| 159 | + |
| 160 | + // Start scrolling if not already active |
| 161 | + if (!isStreaming) { |
| 162 | + startScrolling(); |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + // Hook 1: Monitor data events (keyboard input, etc.) |
| 167 | + try { |
| 168 | + term.onData(() => { |
| 169 | + recordActivity(); |
| 170 | + }); |
| 171 | + log('✓ Hooked into onData'); |
| 172 | + } catch (e) { |
| 173 | + log('⚠ Failed to hook onData:', e); |
| 174 | + } |
| 175 | + |
| 176 | + // Hook 2: Override write method (terminal output) |
| 177 | + try { |
| 178 | + const originalWrite = term.write.bind(term); |
| 179 | + const originalWriteln = term.writeln.bind(term); |
| 180 | + |
| 181 | + term.write = function(...args) { |
| 182 | + recordActivity(); |
| 183 | + return originalWrite(...args); |
| 184 | + }; |
| 185 | + |
| 186 | + term.writeln = function(...args) { |
| 187 | + recordActivity(); |
| 188 | + return originalWriteln(...args); |
| 189 | + }; |
| 190 | + |
| 191 | + log('✓ Hooked into write/writeln'); |
| 192 | + } catch (e) { |
| 193 | + log('⚠ Failed to hook write methods:', e); |
| 194 | + } |
| 195 | + |
| 196 | + // Hook 3: Monitor terminal buffer changes (fallback) |
| 197 | + try { |
| 198 | + let lastBufferLength = term.buffer.active.length; |
| 199 | + |
| 200 | + setInterval(() => { |
| 201 | + const currentBufferLength = term.buffer.active.length; |
| 202 | + if (currentBufferLength !== lastBufferLength) { |
| 203 | + recordActivity(); |
| 204 | + lastBufferLength = currentBufferLength; |
| 205 | + } |
| 206 | + }, 200); |
| 207 | + |
| 208 | + log('✓ Monitoring buffer changes'); |
| 209 | + } catch (e) { |
| 210 | + log('⚠ Failed to monitor buffer:', e); |
| 211 | + } |
| 212 | + |
| 213 | + log('✓✓✓ Auto-scroll fully initialized ✓✓✓'); |
| 214 | + notifyParent('ready'); |
| 215 | + |
| 216 | + // Test: Trigger initial scroll |
| 217 | + setTimeout(() => { |
| 218 | + forceScrollToBottom(term); |
| 219 | + }, 500); |
| 220 | + } |
| 221 | + |
| 222 | + // Start initialization |
| 223 | + if (document.readyState === 'loading') { |
| 224 | + document.addEventListener('DOMContentLoaded', initAutoScroll); |
| 225 | + } else { |
| 226 | + initAutoScroll(); |
| 227 | + } |
| 228 | + |
| 229 | +})(); |
0 commit comments