Repository navigation
Expand file tree
/
Copy pathcontent.js
More file actions
428 lines (357 loc) · 11.8 KB
/
Copy pathcontent.js
File metadata and controls
428 lines (357 loc) · 11.8 KB
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
let videoEl = null;
let videoId = null;
let overlayEl = null;
let renderer = null;
let isRomajiActive = false;
let menuWired = false;
let lastUrl = null;
let captionMenuObserver = null;
const SERVER_URL = 'https://youtube-romaji-api.fly.dev';
const lyricsCache = new Map();
function $(sel, root = document) { return root.querySelector(sel); }
function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
function getCurrentVideoId() {
try {
const u = new URL(location.href);
const v = u.searchParams.get("v");
if (v) return v;
const m = location.pathname.match(/\/shorts\/([A-Za-z0-9_-]+)/);
if (m) return m[1];
} catch {
return null;
}
return null;
}
function getVideoTitle() {
const el = document.querySelector('#title h1 yt-formatted-string, #title h1');
if (el?.textContent) return el.textContent.trim();
return (document.title || '').replace(/\s*-\s*YouTube\s*$/i, '').trim();
}
function getChannelName() {
const el = document.querySelector('#channel-name a, ytd-channel-name a');
return el?.textContent?.trim() || '';
}
function getVideoDuration() {
const v = document.querySelector('video');
return v?.duration || 0;
}
// ============================================================================
// LYRICS FETCHING
// ============================================================================
async function fetchRomajiLyrics(vid) {
if (lyricsCache.has(vid)) return lyricsCache.get(vid);
const title = getVideoTitle();
const artist = getChannelName();
const duration = getVideoDuration();
console.log(`[romaji] fetching: "${title}" by "${artist}" (${Math.round(duration)}s)`);
try {
const res = await fetch(`${SERVER_URL}/lyrics`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ videoId: vid, title, artist, duration })
});
const data = await res.json();
lyricsCache.set(vid, data);
return data;
} catch (err) {
console.error('[romaji] fetch error:', err);
const result = { ok: false, error: err.message };
lyricsCache.set(vid, result);
return result;
}
}
// ============================================================================
// INIT
// ============================================================================
start();
async function start() {
console.log("[romaji] starting");
await waitForPlayer();
console.log("[romaji] player ready");
setupNavigationListener();
observeSettingsMenu();
}
async function waitForPlayer() {
for (;;) {
videoEl = $("video");
if ($("ytd-player") && videoEl) return;
await sleep(300);
}
}
// ============================================================================
// NAVIGATION
// ============================================================================
function setupNavigationListener() {
document.addEventListener('yt-navigate-finish', () => {
setTimeout(() => onNavigation(), 250);
});
const mo = new MutationObserver(() => {
if (location.href !== lastUrl) {
lastUrl = location.href;
setTimeout(() => onNavigation(), 250);
}
});
mo.observe(document.documentElement, { childList: true, subtree: true });
}
function onNavigation() {
const newVideoId = getCurrentVideoId();
if (newVideoId === videoId) return;
videoId = newVideoId;
console.log("[romaji] nav:", videoId);
if (renderer) renderer.stop();
renderer = null;
ensureOverlay(false);
setNativeCaptionsVisible(true);
isRomajiActive = false;
if (captionMenuObserver) {
captionMenuObserver.disconnect();
captionMenuObserver = null;
}
menuWired = false;
}
// ============================================================================
// MENU INJECTION
// ============================================================================
function observeSettingsMenu() {
const mo = new MutationObserver(() => {
if ($(".ytp-settings-menu")) tryWireCaptionMenu();
});
mo.observe(document.documentElement, { childList: true, subtree: true });
}
function tryWireCaptionMenu() {
if (menuWired) return;
const holder = $(".ytp-popup.ytp-settings-menu");
if (!holder) return;
if (captionMenuObserver) captionMenuObserver.disconnect();
captionMenuObserver = new MutationObserver(muts => {
for (const mut of muts) {
for (const node of mut.addedNodes) {
if (node.nodeType === 1 && node.classList.contains("ytp-panel")) {
const title = $(".ytp-panel-title", node);
if (title && /Subtitles|Captions|字幕|자막/i.test(title.textContent || "")) {
injectRomajiEntry($(".ytp-panel-menu", node));
}
}
}
}
});
captionMenuObserver.observe(holder, { childList: true, subtree: true });
menuWired = true;
}
function injectRomajiEntry(menuEl) {
if (!menuEl) return;
menuEl.querySelectorAll("[data-romaji-entry]").forEach(n => n.remove());
const li = document.createElement("div");
li.className = "ytp-menuitem";
li.setAttribute("role", "menuitemradio");
li.setAttribute("aria-checked", isRomajiActive ? "true" : "false");
li.tabIndex = 0;
li.dataset.romajiEntry = "romaji:auto";
const label = document.createElement("div");
label.className = "ytp-menuitem-label";
label.textContent = "Romaji";
const content = document.createElement("div");
content.className = "ytp-menuitem-content";
li.appendChild(label);
li.appendChild(content);
const handler = () => onToggleRomaji();
li.addEventListener("click", handler);
li.addEventListener("keydown", e => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
handler();
}
});
menuEl.appendChild(li);
// custom subtitle tracks
listCustomTracks().then(tracks => {
for (const t of tracks) {
if (!t.value?.name) continue;
const item = buildCustomMenuItem(t.value.name, t.key);
menuEl.appendChild(item);
}
});
// wire native items to turn off romaji
menuEl.querySelectorAll('.ytp-menuitem[role="menuitemradio"]:not([data-romaji-entry])').forEach(item => {
item.addEventListener('click', () => {
if (isRomajiActive) {
if (renderer) renderer.stop();
renderer = null;
ensureOverlay(false);
setNativeCaptionsVisible(true);
isRomajiActive = false;
updateMenuCheckmarks();
}
});
});
}
function buildCustomMenuItem(label, storageKey) {
const li = document.createElement("div");
li.className = "ytp-menuitem";
li.setAttribute("role", "menuitemradio");
li.setAttribute("aria-checked", "false");
li.tabIndex = 0;
li.dataset.romajiEntry = `custom:${storageKey}`;
const name = document.createElement("div");
name.className = "ytp-menuitem-label";
name.textContent = label;
const filler = document.createElement("div");
filler.className = "ytp-menuitem-content";
li.appendChild(name);
li.appendChild(filler);
li.addEventListener("click", async () => {
const rec = await storageGet(storageKey);
if (rec?.cues) showOverlay(rec.cues);
});
return li;
}
// ============================================================================
// ROMAJI TOGGLE
// ============================================================================
let fetchingLyrics = false;
async function onToggleRomaji() {
if (isRomajiActive) {
if (renderer) renderer.stop();
renderer = null;
ensureOverlay(false);
setNativeCaptionsVisible(true);
isRomajiActive = false;
updateMenuCheckmarks();
return;
}
const vid = getCurrentVideoId();
if (!vid || fetchingLyrics) return;
// close the menu
const backBtn = document.querySelector('.ytp-panel-back-button');
if (backBtn) backBtn.click();
fetchingLyrics = true;
console.log("[romaji] fetching lyrics for:", vid);
try {
const result = await fetchRomajiLyrics(vid);
if (!result.ok) {
alert(result.error || 'No romaji lyrics found.');
return;
}
if (!result.cues?.length) {
alert('No lyrics found.');
return;
}
if (!result.synced) {
console.warn('[romaji] only unsynced lyrics available');
}
if (result.trackName) {
console.log(`[romaji] matched: "${result.trackName}" by ${result.artistName}`);
}
showOverlay(result.cues);
} catch (err) {
console.error('[romaji] error:', err);
alert('Failed to fetch lyrics. Check console.');
} finally {
fetchingLyrics = false;
}
}
// ============================================================================
// OVERLAY
// ============================================================================
function ensureOverlay(visible) {
if (!overlayEl) {
const player = document.querySelector('.html5-video-player');
if (!player) return;
overlayEl = document.createElement("div");
overlayEl.id = "romaji-caption-overlay";
player.appendChild(overlayEl);
}
overlayEl.style.display = visible ? "block" : "none";
}
function showOverlay(cues) {
if (!cues?.length) return;
videoEl = document.querySelector('video');
ensureOverlay(true);
if (renderer) renderer.stop();
renderer = new CaptionRenderer(videoEl, overlayEl, cues);
renderer.start();
setNativeCaptionsVisible(false);
isRomajiActive = true;
updateMenuCheckmarks();
}
function setNativeCaptionsVisible(visible) {
const container = document.querySelector('.ytp-caption-window-container');
if (container) container.style.display = visible ? '' : 'none';
document.querySelectorAll('.caption-window').forEach(el => {
el.style.display = visible ? '' : 'none';
});
}
function updateMenuCheckmarks() {
const romajiItem = document.querySelector('[data-romaji-entry="romaji:auto"]');
if (romajiItem) {
romajiItem.setAttribute('aria-checked', isRomajiActive ? 'true' : 'false');
}
if (isRomajiActive) {
document.body.classList.add('romaji-active');
document.querySelectorAll('.ytp-menuitem[role="menuitemradio"]:not([data-romaji-entry])').forEach(item => {
item.setAttribute('aria-checked', 'false');
});
} else {
document.body.classList.remove('romaji-active');
}
}
// ============================================================================
// CAPTION RENDERER
// ============================================================================
class CaptionRenderer {
constructor(video, host, cues) {
this.video = video;
this.host = host;
this.cues = cues;
this.raf = null;
this.index = 0;
this.active = -1;
}
start() {
this.stop();
const loop = () => {
const t = this.video.currentTime;
let i = this.index;
while (i < this.cues.length && this.cues[i].end < t - 0.02) i++;
while (i > 0 && this.cues[i - 1].start > t) i--;
this.index = i;
const cue = this.cues[i];
if (cue && t >= cue.start && t <= cue.end) {
if (this.active !== i) {
this.active = i;
this.host.textContent = cue.text;
}
} else {
if (this.active !== -1) {
this.active = -1;
this.host.textContent = "";
}
}
this.raf = requestAnimationFrame(loop);
};
this.raf = requestAnimationFrame(loop);
}
stop() {
if (this.raf) cancelAnimationFrame(this.raf);
this.raf = null;
this.host.textContent = "";
this.index = 0;
this.active = -1;
setNativeCaptionsVisible(true);
}
}
// ============================================================================
// STORAGE (custom subtitle tracks)
// ============================================================================
async function listCustomTracks() {
const vid = getCurrentVideoId();
if (!vid) return [];
const all = await chrome.storage.local.get(null);
return Object.entries(all)
.filter(([k, v]) => k.startsWith("subs:" + vid + ":") && v && typeof v === "object")
.map(([key, value]) => ({ key, value }))
.sort((a, b) => (b.value?.ts || 0) - (a.value?.ts || 0));
}
function storageGet(key) {
return chrome.storage.local.get([key]).then(v => v[key]);
}