|
1 |
| -import { SUBTITLES_CONTAINER_QUERY_SELECTOR } from '@/constants/selectors'; |
2 |
| -import { Observable } from 'rxjs'; |
| 1 | +import { SUBTITLE_WRAPPER_QUERY_SELECTOR } from '@/constants/selectors'; |
| 2 | +import { distinctUntilChanged, map, Observable } from 'rxjs'; |
3 | 3 |
|
4 |
| -export const subtitles$ = new Observable<string[]>((subscriber) => { |
| 4 | +export const subtitles$ = new Observable<string>((subscriber) => { |
5 | 5 | const subtitlesObserver = new MutationObserver((mutations) => {
|
6 | 6 | mutations.forEach((mutation) => {
|
7 |
| - Array.from(mutation.addedNodes ?? []).forEach((node) => { |
8 |
| - node instanceof HTMLElement && |
9 |
| - node.getAttribute('data-translated') !== 'true' && |
10 |
| - subscriber.next( |
11 |
| - node.innerText |
12 |
| - .split('\n') |
13 |
| - .map((line) => line.trim()) |
14 |
| - .filter((line) => !!line) |
15 |
| - ); |
| 7 | + mutation.addedNodes.forEach((node) => { |
| 8 | + // Ensure that the added node is a subtitle and has not already been translated |
| 9 | + if (!(node instanceof HTMLElement)) return; |
| 10 | + if (!node.matches(SUBTITLE_WRAPPER_QUERY_SELECTOR)) return; |
| 11 | + if (node.matches('[data-translated]')) return; |
| 12 | + subscriber.next(node.innerText); |
16 | 13 | });
|
17 | 14 | });
|
18 | 15 | });
|
19 | 16 |
|
20 |
| - const subtitleParentObserver = new MutationObserver((mutations) => { |
21 |
| - mutations.forEach((mutation) => { |
22 |
| - const subtitlesContainer = Array.from(mutation.addedNodes ?? []).find( |
23 |
| - (node) => node instanceof HTMLElement && node.matches(SUBTITLES_CONTAINER_QUERY_SELECTOR) |
24 |
| - ); |
25 |
| - if (subtitlesContainer) { |
26 |
| - subtitlesObserver.observe(subtitlesContainer, { |
27 |
| - childList: true, |
28 |
| - subtree: true, |
29 |
| - attributes: false, |
30 |
| - characterData: false |
31 |
| - }); |
32 |
| - subtitleParentObserver.disconnect(); |
33 |
| - } |
34 |
| - }); |
35 |
| - }); |
36 |
| - |
37 |
| - subtitleParentObserver.observe(document, { |
| 17 | + subtitlesObserver.observe(document, { |
38 | 18 | childList: true,
|
39 | 19 | subtree: true,
|
40 | 20 | attributes: false,
|
41 | 21 | characterData: false
|
42 | 22 | });
|
43 | 23 |
|
44 |
| - return () => { |
45 |
| - subtitlesObserver.disconnect(); |
46 |
| - subtitleParentObserver.disconnect(); |
47 |
| - }; |
48 |
| -}); |
| 24 | + return () => subtitlesObserver.disconnect(); |
| 25 | +}) |
| 26 | + // Don't fire duplicate subtitle events |
| 27 | + .pipe(distinctUntilChanged()) |
| 28 | + // Transform the subtitle into trimmed lines |
| 29 | + .pipe( |
| 30 | + map((text) => |
| 31 | + text |
| 32 | + .split('\n') |
| 33 | + .map((line) => line.trim()) |
| 34 | + .filter((line) => !!line) |
| 35 | + ) |
| 36 | + ); |
0 commit comments