mirror of
https://github.com/th-ch/youtube-music.git
synced 2026-01-13 11:21:46 +00:00
feat(synced-lyrics): multiple lyric sources (#2383)
Co-authored-by: JellyBrick <shlee1503@naver.com>
This commit is contained in:
@ -0,0 +1,64 @@
|
||||
import { t } from '@/i18n';
|
||||
|
||||
import { getSongInfo } from '@/providers/song-info-front';
|
||||
|
||||
import { lyricsStore, retrySearch } from '../../providers';
|
||||
|
||||
interface ErrorDisplayProps {
|
||||
error: Error;
|
||||
}
|
||||
|
||||
// prettier-ignore
|
||||
export const ErrorDisplay = (props: ErrorDisplayProps) => {
|
||||
return (
|
||||
<div style={{ 'margin-bottom': '5%' }}>
|
||||
<pre
|
||||
style={{
|
||||
'background-color': 'var(--ytmusic-color-black1)',
|
||||
'border-radius': '8px',
|
||||
'color': '#58f000',
|
||||
'max-width': '100%',
|
||||
'margin-top': '1em',
|
||||
'margin-bottom': '0',
|
||||
'padding': '0.5em',
|
||||
'font-family': 'serif',
|
||||
'font-size': 'large',
|
||||
}}
|
||||
>
|
||||
{t('plugins.synced-lyrics.errors.fetch')}
|
||||
</pre>
|
||||
<pre
|
||||
style={{
|
||||
'background-color': 'var(--ytmusic-color-black1)',
|
||||
'border-radius': '8px',
|
||||
'color': '#f0a500',
|
||||
'white-space': 'pre',
|
||||
'overflow-x': 'auto',
|
||||
'max-width': '100%',
|
||||
'margin-top': '0.5em',
|
||||
'padding': '0.5em',
|
||||
'font-family': 'monospace',
|
||||
'font-size': 'large',
|
||||
}}
|
||||
>
|
||||
{props.error.stack}
|
||||
</pre>
|
||||
|
||||
<yt-button-renderer
|
||||
onClick={() => retrySearch(lyricsStore.provider, getSongInfo())}
|
||||
data={{
|
||||
icon: { iconType: 'REFRESH' },
|
||||
isDisabled: false,
|
||||
style: 'STYLE_DEFAULT',
|
||||
text: {
|
||||
simpleText: t('plugins.synced-lyrics.refetch-btn.normal')
|
||||
},
|
||||
}}
|
||||
style={{
|
||||
'margin-top': '1em',
|
||||
'width': '100%'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@ -0,0 +1,33 @@
|
||||
import { createSignal, onMount } from 'solid-js';
|
||||
|
||||
const states = [
|
||||
'(>_<)',
|
||||
'{ (>_<) }',
|
||||
'{{ (>_<) }}',
|
||||
'{{{ (>_<) }}}',
|
||||
'{{ (>_<) }}',
|
||||
'{ (>_<) }',
|
||||
];
|
||||
export const LoadingKaomoji = () => {
|
||||
const [counter, setCounter] = createSignal(0);
|
||||
|
||||
onMount(() => {
|
||||
const interval = setInterval(() => setCounter((old) => old + 1), 500);
|
||||
return () => clearInterval(interval);
|
||||
});
|
||||
|
||||
return (
|
||||
<yt-formatted-string
|
||||
class="text-lyrics description ytmusic-description-shelf-renderer"
|
||||
style={{
|
||||
'display': 'inline-flex',
|
||||
'justify-content': 'center',
|
||||
'width': '100%',
|
||||
'user-select': 'none',
|
||||
}}
|
||||
text={{
|
||||
runs: [{ text: states[counter() % states.length] }],
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@ -2,145 +2,54 @@ import { createSignal, For, Match, Show, Switch } from 'solid-js';
|
||||
|
||||
import { SyncedLine } from './SyncedLine';
|
||||
|
||||
import { t } from '@/i18n';
|
||||
import { getSongInfo } from '@/providers/song-info-front';
|
||||
import { ErrorDisplay } from './ErrorDisplay';
|
||||
import { LoadingKaomoji } from './LoadingKaomoji';
|
||||
import { PlainLyrics } from './PlainLyrics';
|
||||
|
||||
import {
|
||||
differentDuration,
|
||||
hadSecondAttempt,
|
||||
isFetching,
|
||||
isInstrumental,
|
||||
makeLyricsRequest,
|
||||
} from '../lyrics/fetch';
|
||||
|
||||
import type { LineLyrics } from '../../types';
|
||||
import { currentLyrics, lyricsStore } from '../../providers';
|
||||
|
||||
export const [debugInfo, setDebugInfo] = createSignal<string>();
|
||||
export const [lineLyrics, setLineLyrics] = createSignal<LineLyrics[]>([]);
|
||||
export const [currentTime, setCurrentTime] = createSignal<number>(-1);
|
||||
|
||||
// prettier-ignore
|
||||
export const LyricsContainer = () => {
|
||||
const [error, setError] = createSignal('');
|
||||
|
||||
const onRefetch = async () => {
|
||||
if (isFetching()) return;
|
||||
setError('');
|
||||
|
||||
const info = getSongInfo();
|
||||
await makeLyricsRequest(info).catch((err) => {
|
||||
setError(String(err));
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div class={'lyric-container'}>
|
||||
<div class="lyric-container">
|
||||
<Switch>
|
||||
<Match when={isFetching()}>
|
||||
<div style="margin-bottom: 8px;">
|
||||
<tp-yt-paper-spinner-lite
|
||||
active
|
||||
class="loading-indicator style-scope"
|
||||
/>
|
||||
</div>
|
||||
<Match when={currentLyrics()?.state === 'fetching'}>
|
||||
<LoadingKaomoji />
|
||||
</Match>
|
||||
<Match when={error()}>
|
||||
<Match when={!currentLyrics().data?.lines && !currentLyrics().data?.lyrics}>
|
||||
<yt-formatted-string
|
||||
class="warning-lyrics description ytmusic-description-shelf-renderer"
|
||||
class="text-lyrics description ytmusic-description-shelf-renderer"
|
||||
style={{
|
||||
'display': 'inline-flex',
|
||||
'justify-content': 'center',
|
||||
'width': '100%',
|
||||
'user-select': 'none',
|
||||
}}
|
||||
text={{
|
||||
runs: [
|
||||
{
|
||||
text: t('plugins.synced-lyrics.errors.fetch'),
|
||||
},
|
||||
],
|
||||
runs: [{ text: '\(〇_o)/' }],
|
||||
}}
|
||||
/>
|
||||
</Match>
|
||||
</Switch>
|
||||
|
||||
<Show when={lyricsStore.current.error}>
|
||||
<ErrorDisplay error={lyricsStore.current.error!} />
|
||||
</Show>
|
||||
|
||||
<Switch>
|
||||
<Match when={!lineLyrics().length}>
|
||||
<Show
|
||||
when={isInstrumental()}
|
||||
fallback={
|
||||
<>
|
||||
<yt-formatted-string
|
||||
class="warning-lyrics description ytmusic-description-shelf-renderer"
|
||||
text={{
|
||||
runs: [
|
||||
{
|
||||
text: t('plugins.synced-lyrics.errors.not-found'),
|
||||
},
|
||||
],
|
||||
}}
|
||||
style={'margin-bottom: 16px;'}
|
||||
/>
|
||||
<yt-button-renderer
|
||||
disabled={isFetching()}
|
||||
data={{
|
||||
icon: { iconType: 'REFRESH' },
|
||||
isDisabled: false,
|
||||
style: 'STYLE_DEFAULT',
|
||||
text: {
|
||||
simpleText: isFetching()
|
||||
? t('plugins.synced-lyrics.refetch-btn.fetching')
|
||||
: t('plugins.synced-lyrics.refetch-btn.normal'),
|
||||
},
|
||||
}}
|
||||
onClick={onRefetch}
|
||||
/>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<yt-formatted-string
|
||||
class="warning-lyrics description ytmusic-description-shelf-renderer"
|
||||
text={{
|
||||
runs: [
|
||||
{
|
||||
text: t('plugins.synced-lyrics.warnings.instrumental'),
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>
|
||||
</Show>
|
||||
<Match when={currentLyrics().data?.lines}>
|
||||
<For each={currentLyrics().data?.lines}>
|
||||
{(item) => <SyncedLine line={item} />}
|
||||
</For>
|
||||
</Match>
|
||||
<Match when={lineLyrics().length && !hadSecondAttempt()}>
|
||||
<yt-formatted-string
|
||||
class="warning-lyrics description ytmusic-description-shelf-renderer"
|
||||
text={{
|
||||
runs: [
|
||||
{
|
||||
text: t('plugins.synced-lyrics.warnings.inexact'),
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>
|
||||
</Match>
|
||||
<Match when={lineLyrics().length && !differentDuration()}>
|
||||
<yt-formatted-string
|
||||
class="warning-lyrics description ytmusic-description-shelf-renderer"
|
||||
text={{
|
||||
runs: [
|
||||
{
|
||||
text: t('plugins.synced-lyrics.warnings.duration-mismatch'),
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>
|
||||
|
||||
<Match when={currentLyrics().data?.lyrics}>
|
||||
<PlainLyrics lyrics={currentLyrics().data?.lyrics!} />
|
||||
</Match>
|
||||
</Switch>
|
||||
|
||||
<For each={lineLyrics()}>{(item) => <SyncedLine line={item} />}</For>
|
||||
|
||||
<yt-formatted-string
|
||||
class="footer style-scope ytmusic-description-shelf-renderer"
|
||||
text={{
|
||||
runs: [
|
||||
{
|
||||
text: 'Source: LRCLIB',
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
198
src/plugins/synced-lyrics/renderer/components/LyricsPicker.tsx
Normal file
198
src/plugins/synced-lyrics/renderer/components/LyricsPicker.tsx
Normal file
@ -0,0 +1,198 @@
|
||||
import {
|
||||
createEffect,
|
||||
createMemo,
|
||||
createSignal,
|
||||
For,
|
||||
Index,
|
||||
Match,
|
||||
onMount,
|
||||
Switch,
|
||||
} from 'solid-js';
|
||||
|
||||
import {
|
||||
currentLyrics,
|
||||
lyricsStore,
|
||||
ProviderName,
|
||||
providerNames,
|
||||
ProviderState,
|
||||
setLyricsStore,
|
||||
} from '../../providers';
|
||||
|
||||
import { _ytAPI } from '../index';
|
||||
|
||||
import type { YtIcons } from '@/types/icons';
|
||||
|
||||
export const providerIdx = createMemo(() =>
|
||||
providerNames.indexOf(lyricsStore.provider),
|
||||
);
|
||||
|
||||
const shouldSwitchProvider = (providerData: ProviderState) => {
|
||||
if (providerData.state === 'error') return true;
|
||||
if (providerData.state === 'fetching') return true;
|
||||
return (
|
||||
providerData.state === 'done' &&
|
||||
!providerData.data?.lines &&
|
||||
!providerData.data?.lyrics
|
||||
);
|
||||
};
|
||||
|
||||
const providerBias = (p: ProviderName) =>
|
||||
(lyricsStore.lyrics[p].state === 'done' ? 1 : -1) +
|
||||
(lyricsStore.lyrics[p].data?.lines?.length ? 2 : -1) +
|
||||
(lyricsStore.lyrics[p].data?.lines?.length && p === 'YTMusic' ? 1 : 0) +
|
||||
(lyricsStore.lyrics[p].data?.lyrics ? 1 : -1);
|
||||
|
||||
// prettier-ignore
|
||||
const pickBestProvider = () => {
|
||||
const providers = Array.from(providerNames);
|
||||
|
||||
providers.sort((a, b) => providerBias(b) - providerBias(a));
|
||||
|
||||
return providers[0];
|
||||
};
|
||||
|
||||
// prettier-ignore
|
||||
export const LyricsPicker = () => {
|
||||
const [hasManuallySwitchedProvider, setHasManuallySwitchedProvider] = createSignal(false);
|
||||
createEffect(() => {
|
||||
// fallback to the next source, if the current one has an error
|
||||
if (!hasManuallySwitchedProvider()
|
||||
) {
|
||||
const bestProvider = pickBestProvider();
|
||||
|
||||
const allProvidersFailed = providerNames.every((p) => shouldSwitchProvider(lyricsStore.lyrics[p]));
|
||||
if (allProvidersFailed) return;
|
||||
|
||||
if (providerBias(lyricsStore.provider) < providerBias(bestProvider)) {
|
||||
setLyricsStore('provider', bestProvider);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
const listener = (name: string) => {
|
||||
if (name !== 'dataloaded') return;
|
||||
setHasManuallySwitchedProvider(false);
|
||||
};
|
||||
|
||||
_ytAPI?.addEventListener('videodatachange', listener);
|
||||
return () => _ytAPI?.removeEventListener('videodatachange', listener);
|
||||
});
|
||||
|
||||
const next = (automatic: boolean = false) => {
|
||||
if (!automatic) setHasManuallySwitchedProvider(true);
|
||||
setLyricsStore('provider', (prevProvider) => {
|
||||
const idx = providerNames.indexOf(prevProvider);
|
||||
return providerNames[(idx + 1) % providerNames.length];
|
||||
});
|
||||
};
|
||||
|
||||
const previous = (automatic: boolean = false) => {
|
||||
if (!automatic) setHasManuallySwitchedProvider(true);
|
||||
setLyricsStore('provider', (prevProvider) => {
|
||||
const idx = providerNames.indexOf(prevProvider);
|
||||
return providerNames[(idx + providerNames.length - 1) % providerNames.length];
|
||||
});
|
||||
};
|
||||
|
||||
const chevronLeft: YtIcons = 'yt-icons:chevron_left';
|
||||
const chevronRight: YtIcons = 'yt-icons:chevron_right';
|
||||
|
||||
const successIcon: YtIcons = 'yt-icons:check-circle';
|
||||
const errorIcon: YtIcons = 'yt-icons:error';
|
||||
const notFoundIcon: YtIcons = 'yt-icons:warning';
|
||||
|
||||
|
||||
return (
|
||||
<div class="lyrics-picker">
|
||||
<div class="lyrics-picker-left">
|
||||
<tp-yt-paper-icon-button icon={chevronLeft} onClick={() => previous()} />
|
||||
</div>
|
||||
|
||||
<div class="lyrics-picker-content">
|
||||
<div class="lyrics-picker-content-label">
|
||||
<Index each={providerNames}>
|
||||
{(provider) => (
|
||||
<div
|
||||
class="lyrics-picker-item"
|
||||
tabindex="-1"
|
||||
style={{
|
||||
transform: `translateX(${providerIdx() * -100 - 5}%)`,
|
||||
}}
|
||||
>
|
||||
<Switch>
|
||||
<Match
|
||||
when={
|
||||
// prettier-ignore
|
||||
currentLyrics().state === 'fetching'
|
||||
}
|
||||
>
|
||||
<tp-yt-paper-spinner-lite
|
||||
active
|
||||
tabindex="-1"
|
||||
class="loading-indicator style-scope"
|
||||
style={{ padding: '5px', transform: 'scale(0.5)' }}
|
||||
/>
|
||||
</Match>
|
||||
<Match when={currentLyrics().state === 'error'}>
|
||||
<tp-yt-paper-icon-button
|
||||
icon={errorIcon}
|
||||
tabindex="-1"
|
||||
style={{ padding: '5px', transform: 'scale(0.5)' }}
|
||||
/>
|
||||
</Match>
|
||||
<Match
|
||||
when={
|
||||
currentLyrics().state === 'done' &&
|
||||
(currentLyrics().data?.lines ||
|
||||
currentLyrics().data?.lyrics)
|
||||
}
|
||||
>
|
||||
<tp-yt-paper-icon-button
|
||||
icon={successIcon}
|
||||
tabindex="-1"
|
||||
style={{ padding: '5px', transform: 'scale(0.5)' }}
|
||||
/>
|
||||
</Match>
|
||||
<Match when={
|
||||
currentLyrics().state === 'done'
|
||||
&& !currentLyrics().data?.lines
|
||||
&& !currentLyrics().data?.lyrics
|
||||
}>
|
||||
<tp-yt-paper-icon-button
|
||||
icon={notFoundIcon}
|
||||
tabindex="-1"
|
||||
style={{ padding: '5px', transform: 'scale(0.5)' }}
|
||||
/>
|
||||
</Match>
|
||||
</Switch>
|
||||
<yt-formatted-string
|
||||
class="description ytmusic-description-shelf-renderer"
|
||||
text={{ runs: [{ text: provider() }] }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</Index>
|
||||
</div>
|
||||
|
||||
<ul class="lyrics-picker-content-dots">
|
||||
<For each={providerNames}>
|
||||
{(_, idx) => (
|
||||
<li
|
||||
class="lyrics-picker-dot"
|
||||
onClick={() => setLyricsStore('provider', providerNames[idx()])}
|
||||
style={{
|
||||
background: idx() === providerIdx() ? 'white' : 'black',
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</For>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="lyrics-picker-right">
|
||||
<tp-yt-paper-icon-button icon={chevronRight} onClick={() => next()} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@ -0,0 +1,30 @@
|
||||
import { createMemo, For } from 'solid-js';
|
||||
|
||||
interface PlainLyricsProps {
|
||||
lyrics: string;
|
||||
}
|
||||
|
||||
export const PlainLyrics = (props: PlainLyricsProps) => {
|
||||
const lines = createMemo(() => props.lyrics.split('\n'));
|
||||
|
||||
return (
|
||||
<div class="plain-lyrics">
|
||||
<For each={lines()}>
|
||||
{(line) => {
|
||||
if (line.trim() === '') {
|
||||
return <br />;
|
||||
} else {
|
||||
return (
|
||||
<yt-formatted-string
|
||||
class="text-lyrics description ytmusic-description-shelf-renderer"
|
||||
text={{
|
||||
runs: [{ text: line }],
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}}
|
||||
</For>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@ -20,16 +20,22 @@ export const SyncedLine = ({ line }: SyncedLineProps) => {
|
||||
return 'current';
|
||||
});
|
||||
|
||||
let ref: HTMLDivElement;
|
||||
let ref: HTMLDivElement | undefined;
|
||||
createEffect(() => {
|
||||
if (status() === 'current') {
|
||||
ref.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
ref?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
}
|
||||
});
|
||||
|
||||
const text = createMemo(() => {
|
||||
if (line.text.trim()) return line.text;
|
||||
return config()?.defaultTextString ?? '';
|
||||
});
|
||||
|
||||
// prettier-ignore
|
||||
return (
|
||||
<div
|
||||
ref={ref!}
|
||||
ref={ref}
|
||||
class={`synced-line ${status()}`}
|
||||
onClick={() => {
|
||||
_ytAPI?.seekTo(line.timeInMs / 1000);
|
||||
@ -39,13 +45,8 @@ export const SyncedLine = ({ line }: SyncedLineProps) => {
|
||||
class="text-lyrics description ytmusic-description-shelf-renderer"
|
||||
text={{
|
||||
runs: [
|
||||
{
|
||||
text: '',
|
||||
},
|
||||
{
|
||||
text: `${config()?.showTimeCodes ? `[${line.time}] ` : ''}${line.text}`,
|
||||
},
|
||||
],
|
||||
{ text: config()?.showTimeCodes ? `[${line.time}]` : '' },
|
||||
{ text: text() }],
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@ -1,15 +1,15 @@
|
||||
import { createRenderer } from '@/utils';
|
||||
import { waitForElement } from '@/utils/wait-for-element';
|
||||
|
||||
import { makeLyricsRequest } from './lyrics';
|
||||
import { selectors, tabStates } from './utils';
|
||||
import { setConfig } from './renderer';
|
||||
import { setCurrentTime } from './components/LyricsContainer';
|
||||
|
||||
import { fetchLyrics } from '../providers';
|
||||
|
||||
import type { RendererContext } from '@/types/contexts';
|
||||
import type { YoutubePlayer } from '@/types/youtube-player';
|
||||
import type { SongInfo } from '@/providers/song-info';
|
||||
|
||||
import type { SyncedLyricsPluginConfig } from '../types';
|
||||
|
||||
export let _ytAPI: YoutubePlayer | null = null;
|
||||
@ -36,9 +36,7 @@ export const renderer = createRenderer<
|
||||
header.removeAttribute('disabled');
|
||||
break;
|
||||
case 'aria-selected':
|
||||
tabStates[header.ariaSelected as 'true' | 'false']?.(
|
||||
_ytAPI?.getVideoData(),
|
||||
);
|
||||
tabStates[header.ariaSelected ?? 'false']();
|
||||
break;
|
||||
}
|
||||
}
|
||||
@ -51,7 +49,6 @@ export const renderer = createRenderer<
|
||||
|
||||
await this.videoDataChange();
|
||||
},
|
||||
|
||||
async videoDataChange() {
|
||||
if (!this.updateTimestampInterval) {
|
||||
this.updateTimestampInterval = setInterval(
|
||||
@ -60,12 +57,17 @@ export const renderer = createRenderer<
|
||||
);
|
||||
}
|
||||
|
||||
// prettier-ignore
|
||||
this.observer ??= new MutationObserver(this.observerCallback);
|
||||
|
||||
// Force the lyrics tab to be enabled at all times.
|
||||
this.observer.disconnect();
|
||||
|
||||
// Force the lyrics tab to be enabled at all times.
|
||||
const header = await waitForElement<HTMLElement>(selectors.head);
|
||||
{
|
||||
header.removeAttribute('disabled');
|
||||
tabStates[header.ariaSelected ?? 'false']();
|
||||
}
|
||||
|
||||
this.observer.observe(header, { attributes: true });
|
||||
header.removeAttribute('disabled');
|
||||
},
|
||||
@ -73,8 +75,8 @@ export const renderer = createRenderer<
|
||||
async start(ctx: RendererContext<SyncedLyricsPluginConfig>) {
|
||||
setConfig(await ctx.getConfig());
|
||||
|
||||
ctx.ipc.on('ytmd:update-song-info', async (info: SongInfo) => {
|
||||
await makeLyricsRequest(info);
|
||||
ctx.ipc.on('ytmd:update-song-info', (info: SongInfo) => {
|
||||
fetchLyrics(info);
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
@ -1,198 +0,0 @@
|
||||
import { createSignal } from 'solid-js';
|
||||
import { jaroWinkler } from '@skyra/jaro-winkler';
|
||||
|
||||
import { config } from '../renderer';
|
||||
|
||||
import { setDebugInfo, setLineLyrics } from '../components/LyricsContainer';
|
||||
|
||||
import type { SongInfo } from '@/providers/song-info';
|
||||
import type { LineLyrics, LRCLIBSearchResponse } from '../../types';
|
||||
|
||||
export const [isInstrumental, setIsInstrumental] = createSignal(false);
|
||||
export const [isFetching, setIsFetching] = createSignal(false);
|
||||
export const [hadSecondAttempt, setHadSecondAttempt] = createSignal(false);
|
||||
export const [differentDuration, setDifferentDuration] = createSignal(false);
|
||||
|
||||
export const extractTimeAndText = (
|
||||
line: string,
|
||||
index: number,
|
||||
): LineLyrics | null => {
|
||||
const groups = /\[(\d+):(\d+)\.(\d+)](.+)/.exec(line);
|
||||
if (!groups) return null;
|
||||
|
||||
const [, rMinutes, rSeconds, rMillis, text] = groups;
|
||||
const [minutes, seconds, millis] = [
|
||||
parseInt(rMinutes),
|
||||
parseInt(rSeconds),
|
||||
parseInt(rMillis),
|
||||
];
|
||||
|
||||
const timeInMs = minutes * 60 * 1000 + seconds * 1000 + millis;
|
||||
|
||||
return {
|
||||
index,
|
||||
timeInMs,
|
||||
time: `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}:${millis}`,
|
||||
text: text?.trim() || config()!.defaultTextString,
|
||||
status: 'upcoming',
|
||||
duration: 0,
|
||||
};
|
||||
};
|
||||
|
||||
export const makeLyricsRequest = async (extractedSongInfo: SongInfo) => {
|
||||
setIsFetching(true);
|
||||
setLineLyrics([]);
|
||||
|
||||
const songData: Parameters<typeof getLyricsList>[0] = {
|
||||
title: `${extractedSongInfo.title}`,
|
||||
artist: `${extractedSongInfo.artist}`,
|
||||
songDuration: extractedSongInfo.songDuration,
|
||||
};
|
||||
|
||||
if (extractedSongInfo.album) {
|
||||
songData.album = extractedSongInfo.album;
|
||||
}
|
||||
|
||||
let lyrics;
|
||||
try {
|
||||
lyrics = await getLyricsList(songData);
|
||||
} catch {}
|
||||
|
||||
setLineLyrics(lyrics ?? []);
|
||||
setIsFetching(false);
|
||||
};
|
||||
|
||||
export const getLyricsList = async (
|
||||
songData: Pick<SongInfo, 'title' | 'artist' | 'album' | 'songDuration'>,
|
||||
): Promise<LineLyrics[] | null> => {
|
||||
setIsInstrumental(false);
|
||||
setHadSecondAttempt(false);
|
||||
setDifferentDuration(false);
|
||||
setDebugInfo('Searching for lyrics...');
|
||||
|
||||
let query = new URLSearchParams({
|
||||
artist_name: songData.artist,
|
||||
track_name: songData.title,
|
||||
});
|
||||
|
||||
if (songData.album) {
|
||||
query.set('album_name', songData.album);
|
||||
}
|
||||
|
||||
let url = `https://lrclib.net/api/search?${query.toString()}`;
|
||||
let response = await fetch(url);
|
||||
|
||||
if (!response.ok) {
|
||||
setDebugInfo('Got non-OK response from server.');
|
||||
return null;
|
||||
}
|
||||
|
||||
let data = (await response.json()) as LRCLIBSearchResponse;
|
||||
if (!data || !Array.isArray(data)) {
|
||||
setDebugInfo('Unexpected server response.');
|
||||
return null;
|
||||
}
|
||||
|
||||
// Note: If no lyrics are found, try again with a different search query
|
||||
if (data.length === 0) {
|
||||
if (!config()?.showLyricsEvenIfInexact) {
|
||||
return null;
|
||||
}
|
||||
|
||||
query = new URLSearchParams({ q: songData.title });
|
||||
url = `https://lrclib.net/api/search?${query.toString()}`;
|
||||
|
||||
response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
setDebugInfo('Got non-OK response from server. (2)');
|
||||
return null;
|
||||
}
|
||||
|
||||
data = (await response.json()) as LRCLIBSearchResponse;
|
||||
if (!Array.isArray(data)) {
|
||||
setDebugInfo('Unexpected server response. (2)');
|
||||
return null;
|
||||
}
|
||||
|
||||
setHadSecondAttempt(true);
|
||||
}
|
||||
|
||||
const filteredResults: LRCLIBSearchResponse = [];
|
||||
for (const item of data) {
|
||||
const { artist } = songData;
|
||||
const { artistName } = item;
|
||||
|
||||
const artists = artist.split(/[&,]/g).map((i) => i.trim());
|
||||
const itemArtists = artistName.split(/[&,]/g).map((i) => i.trim());
|
||||
|
||||
const permutations = artists.flatMap((artistA) =>
|
||||
itemArtists.map((artistB) => [
|
||||
artistA.toLowerCase(),
|
||||
artistB.toLowerCase(),
|
||||
]),
|
||||
);
|
||||
|
||||
const ratio = Math.max(...permutations.map(([x, y]) => jaroWinkler(x, y)));
|
||||
if (ratio > 0.9) filteredResults.push(item);
|
||||
}
|
||||
|
||||
const duration = songData.songDuration;
|
||||
filteredResults.sort(({ duration: durationA }, { duration: durationB }) => {
|
||||
const left = Math.abs(durationA - duration);
|
||||
const right = Math.abs(durationB - duration);
|
||||
|
||||
return left - right;
|
||||
});
|
||||
|
||||
const closestResult = filteredResults[0];
|
||||
if (!closestResult) {
|
||||
setDebugInfo('No search result matched the criteria.');
|
||||
return null;
|
||||
}
|
||||
|
||||
setDebugInfo(JSON.stringify(closestResult, null, 4));
|
||||
|
||||
if (Math.abs(closestResult.duration - duration) > 15) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (Math.abs(closestResult.duration - duration) > 5) {
|
||||
// show message that the timings may be wrong
|
||||
setDifferentDuration(true);
|
||||
}
|
||||
|
||||
setIsInstrumental(closestResult.instrumental);
|
||||
if (closestResult.instrumental) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Separate the lyrics into lines
|
||||
const raw = closestResult.syncedLyrics?.split('\n') ?? [];
|
||||
if (!raw.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Add a blank line at the beginning
|
||||
raw.unshift('[0:0.0] ');
|
||||
|
||||
const syncedLyricList = raw.reduce<LineLyrics[]>((acc, line) => {
|
||||
const syncedLine = extractTimeAndText(line, acc.length);
|
||||
if (syncedLine) {
|
||||
acc.push(syncedLine);
|
||||
}
|
||||
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
for (const line of syncedLyricList) {
|
||||
const next = syncedLyricList[line.index + 1];
|
||||
if (!next) {
|
||||
line.duration = Infinity;
|
||||
break;
|
||||
}
|
||||
|
||||
line.duration = next.timeInMs - line.timeInMs;
|
||||
}
|
||||
|
||||
return syncedLyricList;
|
||||
};
|
||||
@ -1,44 +0,0 @@
|
||||
import { createEffect } from 'solid-js';
|
||||
|
||||
import { config } from '../renderer';
|
||||
|
||||
export { makeLyricsRequest } from './fetch';
|
||||
|
||||
createEffect(() => {
|
||||
if (!config()?.enabled) return;
|
||||
const root = document.documentElement;
|
||||
|
||||
// Set the line effect
|
||||
switch (config()?.lineEffect) {
|
||||
case 'scale':
|
||||
root.style.setProperty(
|
||||
'--previous-lyrics',
|
||||
'var(--ytmusic-text-primary)',
|
||||
);
|
||||
root.style.setProperty('--current-lyrics', 'var(--ytmusic-text-primary)');
|
||||
root.style.setProperty('--size-lyrics', '1.2');
|
||||
root.style.setProperty('--offset-lyrics', '0');
|
||||
root.style.setProperty('--lyric-width', '83%');
|
||||
break;
|
||||
case 'offset':
|
||||
root.style.setProperty(
|
||||
'--previous-lyrics',
|
||||
'var(--ytmusic-text-primary)',
|
||||
);
|
||||
root.style.setProperty('--current-lyrics', 'var(--ytmusic-text-primary)');
|
||||
root.style.setProperty('--size-lyrics', '1');
|
||||
root.style.setProperty('--offset-lyrics', '5%');
|
||||
root.style.setProperty('--lyric-width', '100%');
|
||||
break;
|
||||
case 'focus':
|
||||
root.style.setProperty(
|
||||
'--previous-lyrics',
|
||||
'var(--ytmusic-text-secondary)',
|
||||
);
|
||||
root.style.setProperty('--current-lyrics', 'var(--ytmusic-text-primary)');
|
||||
root.style.setProperty('--size-lyrics', '1');
|
||||
root.style.setProperty('--offset-lyrics', '0');
|
||||
root.style.setProperty('--lyric-width', '100%');
|
||||
break;
|
||||
}
|
||||
});
|
||||
@ -1,22 +1,93 @@
|
||||
import { createSignal, Show } from 'solid-js';
|
||||
import { createEffect, createSignal, onMount, Show } from 'solid-js';
|
||||
|
||||
import { LyricsContainer } from './components/LyricsContainer';
|
||||
import { LyricsPicker } from './components/LyricsPicker';
|
||||
|
||||
import { selectors } from './utils';
|
||||
|
||||
import type { VideoDetails } from '@/types/video-details';
|
||||
import type { SyncedLyricsPluginConfig } from '../types';
|
||||
|
||||
export const [isVisible, setIsVisible] = createSignal<boolean>(false);
|
||||
|
||||
export const [config, setConfig] =
|
||||
createSignal<SyncedLyricsPluginConfig | null>(null);
|
||||
export const [playerState, setPlayerState] = createSignal<VideoDetails | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
createEffect(() => {
|
||||
if (!config()?.enabled) return;
|
||||
const root = document.documentElement;
|
||||
|
||||
// Set the line effect
|
||||
switch (config()?.lineEffect) {
|
||||
case 'scale':
|
||||
root.style.setProperty(
|
||||
'--previous-lyrics',
|
||||
'var(--ytmusic-text-primary)',
|
||||
);
|
||||
root.style.setProperty('--current-lyrics', 'var(--ytmusic-text-primary)');
|
||||
root.style.setProperty('--size-lyrics', '1.2');
|
||||
root.style.setProperty('--offset-lyrics', '0');
|
||||
root.style.setProperty('--lyric-width', '83%');
|
||||
break;
|
||||
case 'offset':
|
||||
root.style.setProperty(
|
||||
'--previous-lyrics',
|
||||
'var(--ytmusic-text-primary)',
|
||||
);
|
||||
root.style.setProperty('--current-lyrics', 'var(--ytmusic-text-primary)');
|
||||
root.style.setProperty('--size-lyrics', '1');
|
||||
root.style.setProperty('--offset-lyrics', '5%');
|
||||
root.style.setProperty('--lyric-width', '100%');
|
||||
break;
|
||||
case 'focus':
|
||||
root.style.setProperty(
|
||||
'--previous-lyrics',
|
||||
'var(--ytmusic-text-secondary)',
|
||||
);
|
||||
root.style.setProperty('--current-lyrics', 'var(--ytmusic-text-primary)');
|
||||
root.style.setProperty('--size-lyrics', '1');
|
||||
root.style.setProperty('--offset-lyrics', '0');
|
||||
root.style.setProperty('--lyric-width', '100%');
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
export const LyricsRenderer = () => {
|
||||
const [stickyRef, setStickRef] = createSignal<HTMLElement | null>(null);
|
||||
|
||||
// prettier-ignore
|
||||
onMount(() => {
|
||||
const tab = document.querySelector<HTMLElement>(selectors.body.tabRenderer)!;
|
||||
|
||||
const mousemoveListener = (e: MouseEvent) => {
|
||||
const { top } = tab.getBoundingClientRect();
|
||||
const { clientHeight: height } = stickyRef()!;
|
||||
|
||||
const showPicker = (e.clientY - top - 5) <= height;
|
||||
if (showPicker) {
|
||||
// picker visible
|
||||
stickyRef()!.style.setProperty('--top', '0');
|
||||
} else {
|
||||
// picker hidden
|
||||
stickyRef()!.style.setProperty('--top', '-50%');
|
||||
}
|
||||
};
|
||||
|
||||
tab.addEventListener('mousemove', mousemoveListener);
|
||||
return () => tab.removeEventListener('mousemove', mousemoveListener);
|
||||
});
|
||||
|
||||
return (
|
||||
<Show when={isVisible()}>
|
||||
<LyricsContainer />
|
||||
<div class="lyrics-renderer">
|
||||
<div class="lyrics-renderer-sticky" ref={setStickRef}>
|
||||
<LyricsPicker />
|
||||
<div
|
||||
id="divider"
|
||||
class="style-scope ytmusic-guide-section-renderer"
|
||||
style={{ width: '100%', margin: '0' }}
|
||||
></div>
|
||||
</div>
|
||||
<LyricsContainer />
|
||||
</div>
|
||||
</Show>
|
||||
);
|
||||
};
|
||||
|
||||
@ -1,10 +1,7 @@
|
||||
import { render } from 'solid-js/web';
|
||||
|
||||
import { waitForElement } from '@/utils/wait-for-element';
|
||||
|
||||
import { LyricsRenderer, setIsVisible, setPlayerState } from './renderer';
|
||||
|
||||
import type { VideoDetails } from '@/types/video-details';
|
||||
import { LyricsRenderer, setIsVisible } from './renderer';
|
||||
|
||||
export const selectors = {
|
||||
head: '#tabsContent > .tab-header:nth-of-type(2)',
|
||||
@ -14,10 +11,9 @@ export const selectors = {
|
||||
},
|
||||
};
|
||||
|
||||
export const tabStates = {
|
||||
true: async (data?: VideoDetails) => {
|
||||
export const tabStates: Record<string, () => void> = {
|
||||
true: async () => {
|
||||
setIsVisible(true);
|
||||
setPlayerState(data ?? null);
|
||||
|
||||
let container = document.querySelector('#synced-lyrics-container');
|
||||
if (container) return;
|
||||
|
||||
Reference in New Issue
Block a user