/** * Arrow-key movement between titles, for keyboard users. Focus moves to the * nearest card in the pressed direction (by on-screen geometry), so it works * the same across shelves, grids, episode lists and people rows. */ const TARGETS = '.card, .person-card:not(:disabled), .episode-row, .shelf-title-link'; function center(r: DOMRect) { return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; } function nearest(from: HTMLElement, dir: 'left' | 'right' | 'up' | 'down'): HTMLElement | null { const a = from.getBoundingClientRect(); const ac = center(a); const scope = from.closest('.main-scroll') ?? document; let best: HTMLElement | null = null; let bestScore = Infinity; for (const el of scope.querySelectorAll(TARGETS)) { if (el === from || el.offsetParent === null) continue; const b = el.getBoundingClientRect(); const bc = center(b); const dx = bc.x - ac.x; const dy = bc.y - ac.y; let primary: number; let secondary: number; switch (dir) { case 'right': if (b.left < a.right - 4 || Math.abs(dy) > a.height * 0.6) continue; primary = dx; secondary = Math.abs(dy); break; case 'left': if (b.right > a.left + 4 || Math.abs(dy) > a.height * 0.6) continue; primary = -dx; secondary = Math.abs(dy); break; case 'down': if (b.top < a.bottom - 4) continue; primary = dy; secondary = Math.abs(dx); break; case 'up': if (b.bottom > a.top + 4) continue; primary = -dy; secondary = Math.abs(dx); break; } // Prefer the next row/column first, then the closest within it. const score = primary + secondary * (dir === 'up' || dir === 'down' ? 0.35 : 2); if (score < bestScore) { bestScore = score; best = el; } } return best; } export function installKeyboardNav() { window.addEventListener('keydown', (e) => { if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return; const target = e.target as HTMLElement; if (document.documentElement.classList.contains('player-open')) return; if (document.querySelector('.menu-layer, .dialog-layer')) return; // "/" focuses the nearest search field. if (e.key === '/' && !target.closest('input, textarea')) { const field = document.querySelector('.lib-search input, .search-field input'); if (field) { e.preventDefault(); field.focus(); field.select(); } return; } if (!target.matches?.(TARGETS)) return; if ((e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10')) && !target.matches('.shelf-title-link')) { e.preventDefault(); const r = target.getBoundingClientRect(); target.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: r.left + 24, clientY: r.top + 24 })); return; } const dir = ({ ArrowLeft: 'left', ArrowRight: 'right', ArrowUp: 'up', ArrowDown: 'down' } as const)[e.key as 'ArrowLeft']; if (!dir) return; const next = nearest(target, dir); if (!next) return; e.preventDefault(); next.focus({ preventScroll: true }); next.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'smooth' }); }); }