Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 | 1x 1x 144x 144x 144x 144x 144x 144x 144x 144x 144x 144x 144x 144x 144x 52x 144x 53x 9x 1x 53x 53x 144x 56x 144x 55x 5x 5x 4x 3x 3x 3x 5x 5x 5x 144x 54x 6x 6x 144x 40x 40x 40x 40x 40x 40x 144x 40x 1x 27x 144x 402x 144x 20x 20x 20x 20x 20x 20x 17x 17x 17x 6x 3x 6x 19x 13x 20x 20x 7x 5x 4x 2x 1x 1x 6x 6x 20x 5x 5x 20x 144x 8x 8x 8x 8x 8x 8x 144x 10x 10x 10x 144x 9x 9x 9x 3x 3x 144x 7x 6x 6x 6x 6x 6x 144x 144x 2x 144x 32x 12x 144x 144x 1x 1x 128x 2x 2x 2x 2x 2x 1x 5x 1x 15x 134x 201x 20x | // SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Max Boksem. See NOTICE for additional terms under GPLv3 section 7.
import { useState, useEffect, useRef, useCallback } from "react";
import { Check, LoaderCircle, X, Settings, ArrowLeft } from "lucide-react";
import {
searchSubtitles,
downloadSubtitle,
readSubtitleFile,
mpvSubAdd,
mpvSubRemove,
} from "@/lib/tauri";
import type { SubtitleEntry, SubtitleSearchResult, SubtitleCue } from "@/lib/types";
import { parseSrt } from "@/lib/subtitle-parser";
import { getDelayStep, getDelayInterval } from "@/lib/subtitle-delay";
import { cn } from "@/lib/utils";
import { hasOpenFocusTrap } from "@/hooks/useFocusTrap";
// ─── Font family options ───────────────────────────────────────────────────
const FONT_FAMILIES: { label: string; value: string }[] = [
{ label: "Default", value: "system-ui, sans-serif" },
{ label: "Sans-serif", value: "Arial, Helvetica, sans-serif" },
{ label: "Serif", value: "Georgia, 'Times New Roman', serif" },
{ label: "Monospace", value: "'Courier New', Courier, monospace" },
];
// ─── Props ─────────────────────────────────────────────────────────────────
/** A subtitle choice, which the next one, made by the viewer, replaces. */
export interface SubtitlePick {
/** False once the viewer has picked again. */
latest: () => boolean;
/**
* The stream to add the subtitles to. Null once the viewer has picked
* again, the page has closed or the player has moved on to another item,
* and while the player starts the item.
*/
stream: () => string | null;
/**
* Called when mpv has added a track it draws for the stream `url`, and the
* player has no stream for the pick any more, as when the page closed.
* Keeps the pick for when the page opens again, and returns false when the
* player can't keep it, as when it has moved on.
*/
keep: (url: string, entry: SubtitleEntry, rankInLanguage: number) => boolean;
}
interface SubtitlePickerProps {
imdbId: string;
season?: number;
episode?: number;
onClose: () => void;
/**
* Called as the viewer picks a subtitle or None. A subtitle that finishes
* downloading once its pick has no stream is dropped.
*/
startPick: () => SubtitlePick;
onSubtitleSelected?: (
fileId: number | null,
cues?: SubtitleCue[],
entry?: SubtitleEntry | null,
rankInLanguage?: number
) => void;
// State from VideoPlayer (persists across remounts)
currentSelectedId?: number | null;
currentSelectedEntry?: SubtitleEntry | null;
subtitleFontSize?: number;
subtitleFontFamily?: string;
subtitleDelay?: number;
onFontSizeChange?: (size: number) => void;
onFontFamilyChange?: (family: string) => void;
onDelayChange?: (delay: number) => void;
onSettingsModeChange?: (active: boolean) => void;
}
export const SubtitlePicker = ({
imdbId,
season,
episode,
onClose,
startPick,
onSubtitleSelected,
currentSelectedId = null,
currentSelectedEntry = null,
subtitleFontSize = 18,
subtitleFontFamily = "system-ui, sans-serif",
subtitleDelay = 0,
onFontSizeChange,
onFontFamilyChange,
onDelayChange,
onSettingsModeChange,
}: SubtitlePickerProps) => {
// ── Local UI state ──────────────────────────────────────────────────────
const [loading, setLoading] = useState(true);
const [result, setResult] = useState<SubtitleSearchResult | null>(null);
// Initialise selectedFileId from the prop so checkmark is correct on reopen
const [selectedFileId, setSelectedFileId] = useState<number | null>(currentSelectedId);
const [downloadingId, setDownloadingId] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
const [showSettings, setShowSettings] = useState(false);
const [delayHovered, setDelayHovered] = useState(false);
// ── Refs ────────────────────────────────────────────────────────────────
const pickerRef = useRef<HTMLDivElement>(null);
const holdTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const holdStartRef = useRef<number>(0);
const holdDirectionRef = useRef<1 | -1>(1);
// The hold timer outlives the render that started it, so it reads the delay
// from here. Each step writes an absolute value, so a stale one would repeat.
const delayRef = useRef(subtitleDelay);
useEffect(() => {
delayRef.current = subtitleDelay;
}, [subtitleDelay]);
// ── Click-outside to close ──────────────────────────────────────────────
useEffect(() => {
const handleMouseDown = (e: MouseEvent) => {
if (pickerRef.current && !pickerRef.current.contains(e.target as Node)) {
onClose();
}
};
document.addEventListener("mousedown", handleMouseDown);
return () => document.removeEventListener("mousedown", handleMouseDown);
}, [onClose]);
// ── Notify parent when settings pane opens/closes ──────────────────────
useEffect(() => {
onSettingsModeChange?.(showSettings);
}, [showSettings, onSettingsModeChange]);
// ── Arrow keys ←/→ for delay when delay row is hovered ─────────────────
useEffect(() => {
if (!delayHovered) return;
const handleKey = (e: KeyboardEvent) => {
if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
// A modal open over the picker, such as a confirm, keeps its keys.
if (hasOpenFocusTrap()) return;
e.preventDefault();
e.stopPropagation();
const delta = e.key === "ArrowRight" ? 0.1 : -0.1;
onDelayChange?.(Math.round((subtitleDelay + delta) * 10) / 10);
};
document.addEventListener("keydown", handleKey);
return () => document.removeEventListener("keydown", handleKey);
}, [delayHovered, subtitleDelay, onDelayChange]);
// ── Stop a hold the buttons never hear end ──────────────────────────────
const clearHoldTimer = useCallback(() => {
if (holdTimerRef.current !== null) {
clearTimeout(holdTimerRef.current);
holdTimerRef.current = null;
}
}, []);
// A release outside the window, or switching apps mid-hold, sends the button
// no mouseup, so the window's mouseup and blur end the hold too.
useEffect(() => {
window.addEventListener("mouseup", clearHoldTimer);
window.addEventListener("blur", clearHoldTimer);
return () => {
window.removeEventListener("mouseup", clearHoldTimer);
window.removeEventListener("blur", clearHoldTimer);
clearHoldTimer();
};
}, [clearHoldTimer]);
// ── Search on mount ─────────────────────────────────────────────────────
useEffect(() => {
searchSubtitles(imdbId, season, episode)
.then(setResult)
.catch((e) => setError(String(e)))
.finally(() => setLoading(false));
}, [imdbId, season, episode]);
// ── Group entries by language ────────────────────────────────────────────
const grouped = (result?.languages ?? []).map((lang) => ({
lang,
entries: result?.entries?.filter((e) => e.languageCode === lang) ?? [],
}));
// ─── Subtitle selection ─────────────────────────────────────────────────
const handleSelect = async (entry: SubtitleEntry) => {
Iif (downloadingId !== null) return;
const pick = startPick();
setDownloadingId(entry.fileId);
setError(null);
try {
const localPath = await downloadSubtitle(entry.fileId);
// mpv also reads a file that isn't UTF-8, and draws any file the
// overlay can't read. A file that neither can read is an error.
const cues = await readSubtitleFile(localPath).then(parseSrt, () => []);
// The new track takes the place of the one in use, and a failed add
// leaves the old one. Nothing is added once the viewer has picked
// again, the page has closed or the player has moved on. While the
// player starts the item, there's no stream to add it to yet.
const url = pick.stream();
if (url === null) {
if (pick.latest())
setError("The video was still starting. Pick the subtitle again.");
return;
}
// Compute rank within this language group for auto-selection on next episode.
const langGroup = grouped.find((g) => g.lang === entry.languageCode);
const rankInLanguage =
langGroup?.entries.findIndex((e) => e.fileId === entry.fileId) ?? 0;
const added = mpvSubAdd(localPath, cues.length > 0, url);
if (cues.length > 0) added.catch(() => {});
else {
await added;
// mpv draws this track itself. A newer pick replaces it on its
// own. mpv took the old track out for it, so when the page
// closed during the add, the player keeps this pick for when
// the page opens again. When it can't, or the item changed, the
// track comes out again, so it doesn't show over the subtitles
// the player keeps.
if (!pick.latest()) return;
if (pick.stream() === null) {
if (pick.keep(url, entry, rankInLanguage)) return;
await mpvSubRemove(-1, url).catch(() => {});
return;
}
}
setSelectedFileId(entry.fileId);
onSubtitleSelected?.(entry.fileId, cues, entry, rankInLanguage);
onClose();
} catch (e) {
console.error("[SubtitlePicker] subtitle load error:", e);
if (pick.latest()) setError("Failed to load subtitle. Try another.");
} finally {
if (pick.latest()) setDownloadingId(null);
}
};
// None also drops a subtitle still downloading, and frees the list to
// pick another. An add already on its way to mpv runs first, so the
// remove takes its track out too. None only shows once the search found
// subtitles, so a message then is about an earlier pick, and goes.
const handleNone = () => {
startPick();
setDownloadingId(null);
setSelectedFileId(null);
setError(null);
mpvSubRemove(-1).catch(() => {});
onSubtitleSelected?.(null, [], null, undefined);
};
// ─── Hold-to-accelerate delay buttons ──────────────────────────────────
const stepDelay = (delta: number) => {
const next = Math.round((delayRef.current + delta) * 10) / 10;
delayRef.current = next;
onDelayChange?.(next);
};
/** Waits for the next step of a hold that started `elapsed` ms ago. */
const scheduleNextStep = (elapsed: number) => {
const step = getDelayStep(elapsed);
const interval = getDelayInterval(elapsed);
holdTimerRef.current = setTimeout(() => {
stepDelay(holdDirectionRef.current * step);
scheduleNextStep(Date.now() - holdStartRef.current);
}, interval);
};
const startHold = (e: React.MouseEvent, direction: 1 | -1) => {
// Only the main button holds. A right click opens the menu and never sends mouseup.
if (e.button !== 0) return;
clearHoldTimer();
holdDirectionRef.current = direction;
holdStartRef.current = Date.now();
stepDelay(direction * getDelayStep(0));
scheduleNextStep(0);
};
const stopHold = () => clearHoldTimer();
// A mouse press already stepped in startHold. A click with no pointer press
// behind it comes from Enter, Space or a screen reader, so step once here.
const stepOnKeyboardClick = (e: React.MouseEvent, direction: 1 | -1) => {
if (e.detail === 0) stepDelay(direction * getDelayStep(0));
};
// ─── Helpers ────────────────────────────────────────────────────────────
const formatDelay = (d: number) => {
if (d === 0) return "0.0s";
return d > 0 ? `+${d.toFixed(1)}s` : `${d.toFixed(1)}s`;
};
const panelClass =
"rounded-xl bg-black/90 backdrop-blur-xs border border-white/10 shadow-2xl text-white text-sm";
// ─── Render ─────────────────────────────────────────────────────────────
return (
// Outer wrapper anchors both panels; pickerRef covers the whole area for click-outside.
<div ref={pickerRef} className="absolute bottom-20 right-4 z-50 flex items-end gap-2">
{/* ── Settings panel (floats to the left of the list) ── */}
{showSettings && (
<div className={cn(panelClass, "w-64 max-h-[60vh] overflow-y-auto")}>
<div className="flex items-center justify-between px-3 py-2.5 border-b border-white/10 sticky top-0 bg-black/90 backdrop-blur-xs">
<span className="font-semibold text-xs tracking-wide uppercase text-white/70">
Subtitle Settings
</span>
<button
onClick={() => setShowSettings(false)}
className="p-1 rounded text-white/50 hover:text-white hover:bg-white/10"
aria-label="Close settings"
>
<ArrowLeft className="h-4 w-4" />
</button>
</div>
<div className="px-3 py-3 space-y-4">
{/* Font */}
<div className="space-y-2">
<div className="text-[10px] uppercase tracking-wide text-white/40 font-medium">
Font
</div>
<select
value={subtitleFontFamily}
onChange={(e) => onFontFamilyChange?.(e.target.value)}
className="w-full bg-white/10 border border-white/10 rounded px-2 py-1 text-xs text-white focus:outline-hidden focus:border-white/30"
>
{FONT_FAMILIES.map((f) => (
<option key={f.value} value={f.value} className="bg-black">
{f.label}
</option>
))}
</select>
<div className="flex items-center justify-between">
<span className="text-[10px] text-white/40">Size</span>
<div className="flex items-center gap-2">
<button
onClick={() =>
onFontSizeChange?.(Math.max(12, subtitleFontSize - 2))
}
className="px-2 py-0.5 rounded bg-white/10 hover:bg-white/20 text-white text-xs font-bold"
aria-label="Smaller subtitles"
>
A−
</button>
<span className="text-white/60 text-xs w-10 text-center">
{subtitleFontSize}px
</span>
<button
onClick={() =>
onFontSizeChange?.(Math.min(40, subtitleFontSize + 2))
}
className="px-2 py-0.5 rounded bg-white/10 hover:bg-white/20 text-white text-sm font-bold"
aria-label="Larger subtitles"
>
A+
</button>
</div>
</div>
</div>
{/* Delay */}
<div
className="space-y-1.5"
onMouseEnter={() => setDelayHovered(true)}
onMouseLeave={() => setDelayHovered(false)}
>
<div className="text-[10px] uppercase tracking-wide text-white/40 font-medium">
Delay
</div>
<div className="flex items-center gap-2">
<button
className="px-3 py-1 rounded bg-white/10 hover:bg-white/20 text-white text-xs select-none"
onMouseDown={(e) => startHold(e, -1)}
onMouseUp={stopHold}
onMouseLeave={stopHold}
onClick={(e) => stepOnKeyboardClick(e, -1)}
aria-label="Decrease subtitle delay"
>
−
</button>
<span className="flex-1 text-center text-white/80 text-xs tabular-nums">
{formatDelay(subtitleDelay)}
</span>
<button
className="px-3 py-1 rounded bg-white/10 hover:bg-white/20 text-white text-xs select-none"
onMouseDown={(e) => startHold(e, 1)}
onMouseUp={stopHold}
onMouseLeave={stopHold}
onClick={(e) => stepOnKeyboardClick(e, 1)}
aria-label="Increase subtitle delay"
>
+
</button>
</div>
<p className="text-[10px] text-white/30">
Hold for faster · ←/→ keys for ±0.1s
</p>
</div>
{/* Position */}
<div className="space-y-1">
<div className="text-[10px] uppercase tracking-wide text-white/40 font-medium">
Position
</div>
<p className="text-[10px] text-white/40 leading-relaxed">
Drag the subtitle text on screen, or use ↑ ↓ ← → arrow keys to
reposition.
</p>
</div>
</div>
</div>
)}
{/* ── Main subtitle list panel ── */}
<div className={cn(panelClass, "w-80 max-h-[60vh] overflow-y-auto")}>
{/* Header */}
<div className="flex items-center justify-between px-3 py-2.5 border-b border-white/10 sticky top-0 bg-black/90 backdrop-blur-xs z-10">
<span className="font-semibold text-xs tracking-wide uppercase text-white/70">
Subtitles
</span>
<div className="flex items-center gap-1">
<button
onClick={() => setShowSettings((v) => !v)}
className={cn(
"p-1 rounded text-white/50 hover:text-white hover:bg-white/10",
showSettings && "text-white bg-white/10"
)}
aria-label="Subtitle settings"
>
<Settings className="h-4 w-4" />
</button>
<button
onClick={onClose}
className="p-1 rounded text-white/50 hover:text-white hover:bg-white/10"
aria-label="Close"
>
<X className="h-4 w-4" />
</button>
</div>
</div>
{/* Search loading */}
{loading && (
<div className="flex items-center gap-2 p-3 text-white/60">
<LoaderCircle className="h-4 w-4 animate-spin" />
<span>Searching…</span>
</div>
)}
{!loading && !result?.entries.length && (
<div className="p-3 text-white/50 text-xs">No subtitles found</div>
)}
{/* Subtitle list */}
{!loading && result && result.entries.length > 0 && (
<div className="p-1">
{/* Pinned active subtitle (at very top) */}
{selectedFileId !== null && currentSelectedEntry && (
<div className="mb-1">
<div className="px-3 py-1 text-[10px] uppercase tracking-wide text-white/40 font-medium">
Active
</div>
<div className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-white/5 text-xs">
<Check className="h-3 w-3 shrink-0 text-blue-400" />
<span className="truncate text-white font-medium">
{currentSelectedEntry.releaseName ??
`Subtitle ${currentSelectedEntry.fileId}`}
</span>
<span className="text-white/30 shrink-0 ml-auto">
{currentSelectedEntry.languageCode}
</span>
</div>
</div>
)}
{/* None option */}
<button
onClick={handleNone}
className={cn(
"w-full text-left px-3 py-1.5 rounded-lg text-xs hover:bg-white/10 flex items-center gap-1.5",
selectedFileId === null && "text-white font-medium"
)}
>
{selectedFileId === null ? (
<Check className="h-3 w-3 shrink-0" />
) : (
<span className="w-3 shrink-0" />
)}
None
</button>
{/* Language-grouped entries */}
{grouped.map(({ lang, entries }) => (
<div key={lang}>
<div className="px-3 py-1 text-[10px] uppercase tracking-wide text-white/40 font-medium mt-1">
{lang} ({entries.length})
</div>
{entries.map((entry) => (
<button
key={entry.fileId}
onClick={() => handleSelect(entry)}
disabled={downloadingId !== null}
className="w-full text-left px-3 py-1.5 rounded-lg text-xs hover:bg-white/10 disabled:opacity-50 flex items-center gap-1.5"
>
{downloadingId === entry.fileId ? (
<LoaderCircle className="h-3 w-3 animate-spin shrink-0" />
) : selectedFileId === entry.fileId ? (
<Check className="h-3 w-3 shrink-0 text-blue-400" />
) : (
<span className="w-3 shrink-0" />
)}
<span className="truncate">
{entry.releaseName ?? `Subtitle ${entry.fileId}`}
</span>
<span className="text-white/30 shrink-0">
.{entry.format}
</span>
</button>
))}
</div>
))}
</div>
)}
{/* Error */}
{error && (
<div className="px-3 py-2 text-xs text-red-400 border-t border-white/10">
{error}
</div>
)}
</div>
</div>
);
};
|