/** * Wires a copied selection to a popup. * * The controller owns the short-lived state a popup needs: the overlay handle, * the auto-dismiss timer, the in-flight request, and a small cache so that * double-clicking the same word twice does not buy the same translation twice. */ import type { ExtensionContext } from "@earendil-works/pi-coding-agent"; import type { OverlayHandle, TUI } from "@earendil-works/pi-tui"; import type { Config } from "./config.ts"; import { isTranslatableSelection, normalizeSelection } from "./filter.ts"; import { attachCopyHook, type CopyHookTarget } from "./hook.ts"; import { TranslatePopup } from "./popup.ts"; import { translate, type TranslateInput } from "./translate.ts"; const TRANSLATION_TIMEOUT_MS = 20_000; const CACHE_ENTRIES = 200; export interface ControllerDeps { translate?: (input: TranslateInput) => Promise; } export function popupWidth(columns: number): number { const room = Math.max(20, Math.min(56, columns - 4)); return Math.max(20, Math.min(Math.max(28, Math.floor(columns * 0.5)), room)); } export function popupHint(seconds: number): string { return seconds > 0 ? `click to close ยท ${seconds}s` : "click to close"; } export class QuickTranslate { readonly config: Config; private readonly runTranslate: (input: TranslateInput) => Promise; private readonly cache = new Map(); private ctx?: ExtensionContext; private tui?: TUI; private overlay?: OverlayHandle; private popup?: TranslatePopup; private dismissTimer?: ReturnType; private abort?: AbortController; private inFlight?: string; private last?: string; constructor(config: Config, deps: ControllerDeps = {}) { this.config = config; this.runTranslate = deps.translate ?? translate; } /** The freshest context, so the popup follows `/model` and other session changes. */ setContext(ctx: ExtensionContext): void { this.ctx = ctx; } get lastSelection(): string | undefined { return this.last; } attach(tui: TUI): CopyHookTarget { this.tui = tui; return attachCopyHook(tui, (text) => this.onCopy(text)); } private onCopy(text: string): void { this.last = normalizeSelection(text); if (!this.config.enabled) return; if (!isTranslatableSelection(text, this.config)) return; void this.show(text); } /** Open the popup for `raw`. Resolves once the translation is on screen or has failed. */ async show(raw: string): Promise { const text = normalizeSelection(raw); if (!text) return; const popup = this.openPopup(text); if (!popup) return; const key = `${this.config.provider}|${this.config.target}|${text}`; const cached = this.cache.get(key); if (cached !== undefined) { popup.setResult(cached); this.scheduleDismiss(); this.tui?.requestRender(); return; } const ctx = this.ctx; if (!ctx) return; const abort = new AbortController(); this.abort = abort; this.inFlight = text; let timedOut = false; const timeout = setTimeout(() => { timedOut = true; abort.abort(); }, TRANSLATION_TIMEOUT_MS); try { const result = await this.runTranslate({ text, config: this.config, ctx, signal: abort.signal }); this.remember(key, result); if (this.inFlight !== text) return; popup.setResult(result); this.scheduleDismiss(); this.tui?.requestRender(); } catch (error) { // A closed popup has nothing to report; a real failure explains itself. if (this.inFlight !== text) return; const message = timedOut ? "translation timed out" : error instanceof Error ? error.message : String(error); popup.setError(message); this.scheduleDismiss(); this.tui?.requestRender(); } finally { clearTimeout(timeout); if (this.abort === abort) this.abort = undefined; } } close(): void { this.clearDismissTimer(); this.abort?.abort(); this.abort = undefined; this.inFlight = undefined; this.overlay?.hide(); this.overlay = undefined; this.popup = undefined; } private openPopup(text: string): TranslatePopup | undefined { const ctx = this.ctx; const tui = this.tui; if (!ctx || !tui) return undefined; this.close(); const popup = new TranslatePopup(ctx.ui.theme, text, popupHint(this.config.popupSeconds), () => this.close()); this.popup = popup; this.overlay = tui.showOverlay(popup, { anchor: "center", width: popupWidth(tui.terminal.columns), maxHeight: "60%", margin: 1, nonCapturing: true, }); this.scheduleDismiss(); tui.requestRender(); return popup; } private scheduleDismiss(): void { this.clearDismissTimer(); if (this.config.popupSeconds <= 0) return; const timer = setTimeout(() => this.close(), this.config.popupSeconds * 1000); timer.unref(); this.dismissTimer = timer; } private clearDismissTimer(): void { if (this.dismissTimer === undefined) return; clearTimeout(this.dismissTimer); this.dismissTimer = undefined; } private remember(key: string, value: string): void { this.cache.delete(key); this.cache.set(key, value); while (this.cache.size > CACHE_ENTRIES) { const oldest = this.cache.keys().next(); if (oldest.done) break; this.cache.delete(oldest.value); } } }