Skip to content

feat(synced-lyrics): lyrics offset #3240

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 7 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/i18n/resources/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -792,6 +792,14 @@
},
"tooltip": "Choose the effect to apply to the current line"
},
"offset": {
"label": "Lyrics offset",
"tooltip": "Set the offset for the lyrics (useful when using bluetooth speakers)",
"prompt": {
"title": "Lyrics offset",
"label": "Set the lyrics offset in ms"
}
},
"precise-timing": {
"label": "Make the lyrics perfectly synced",
"tooltip": "Calculate to the milisecond the display of the next line (can have a small impact on performance)"
Expand All @@ -810,6 +818,11 @@
}
},
"name": "Synced Lyrics",
"advanced-options": {
"offset": {
"title": "Lyrics Offset (ms):"
}
},
"refetch-btn": {
"fetching": "Fetching...",
"normal": "Refetch lyrics"
Expand Down
1 change: 1 addition & 0 deletions src/plugins/synced-lyrics/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export default createPlugin({
config: {
enabled: false,
preciseTiming: true,
lyricsOffset: 0,
showLyricsEvenIfInexact: true,
showTimeCodes: false,
defaultTextString: '♪',
Expand Down
30 changes: 30 additions & 0 deletions src/plugins/synced-lyrics/menu.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import prompt from 'custom-electron-prompt';

import { t } from '@/i18n';
import promptOptions from '@/providers/prompt-options';

import type { MenuItemConstructorOptions } from 'electron';
import type { MenuContext } from '@/types/contexts';
Expand All @@ -10,6 +13,33 @@ export const menu = async (
const config = await ctx.getConfig();

return [
{
label: t('plugins.synced-lyrics.menu.offset.label'),
toolTip: t('plugins.synced-lyrics.menu.offset.tooltip'),
type: 'normal',
async click() {
const config = await ctx.getConfig();
const newOffset = await prompt(
{
title: t('plugins.synced-lyrics.menu.offset.prompt.title'),
label: t('plugins.synced-lyrics.menu.offset.prompt.label'),
value: config.lyricsOffset || 0,
type: 'input',
inputAttrs: {
type: 'number',
style: 'text-align: center; width: unset;' as unknown as CSSStyleDeclaration,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also if anyone's got a better solution than this please lmk

},
width: 380,
...promptOptions(),
},
ctx.window,
);

ctx.setConfig({
lyricsOffset: Number(newOffset) ?? config.lyricsOffset,
});
},
},
{
label: t('plugins.synced-lyrics.menu.precise-timing.label'),
toolTip: t('plugins.synced-lyrics.menu.precise-timing.tooltip'),
Expand Down
17 changes: 12 additions & 5 deletions src/plugins/synced-lyrics/renderer/components/LyricsPicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import {

import { _ytAPI } from '../index';

import type { YtIcons } from '@/types/icons';
import type { Icons, YtIcons } from '@/types/icons';

export const providerIdx = createMemo(() =>
providerNames.indexOf(lyricsStore.provider),
Expand Down Expand Up @@ -53,11 +53,13 @@ const pickBestProvider = () => {
return providers[0];
};

const [hasManuallySwitchedProvider, setHasManuallySwitchedProvider] =
createSignal(false);
export const [pickerAdvancedOpen, setPickerAdvancedOpen] = createSignal(false);

// prettier-ignore
export const LyricsPicker = (props: { setStickRef: Setter<HTMLElement | null> }) => {
const [hasManuallySwitchedProvider, setHasManuallySwitchedProvider] = createSignal(false);

// prettier-ignore
export const LyricsPicker = () => {
createEffect(() => {
// fallback to the next source, if the current one has an error
if (!hasManuallySwitchedProvider()
Expand Down Expand Up @@ -105,9 +107,10 @@ export const LyricsPicker = (props: { setStickRef: Setter<HTMLElement | null> })
const successIcon: YtIcons = 'yt-icons:check-circle';
const errorIcon: YtIcons = 'yt-icons:error';
const notFoundIcon: YtIcons = 'yt-icons:warning';
const toggleAdvancedIcon: Icons = 'icons:more-vert';

return (
<div class="lyrics-picker" ref={props.setStickRef}>
<div class="lyrics-picker">
<div class="lyrics-picker-left">
<tp-yt-paper-icon-button icon={chevronLeft} onClick={previous} />
</div>
Expand Down Expand Up @@ -173,6 +176,10 @@ export const LyricsPicker = (props: { setStickRef: Setter<HTMLElement | null> })
class="description ytmusic-description-shelf-renderer"
text={{ runs: [{ text: provider() }] }}
/>
<tp-yt-paper-icon-button
icon={toggleAdvancedIcon}
onClick={() => setPickerAdvancedOpen(prev => !prev)}
/>
</div>
)}
</Index>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { t } from '@/i18n';
import { createSignal } from 'solid-js';

export const [lyricsOffset, setLyricsOffset] = createSignal(0);

export const LyricsPickerAdvanced = () => {
const [typing, setTyping] = createSignal(false)
return (
<div
style={{
width: '100%',
height: '100%',
display: 'flex',
'flex-direction': 'row',
'align-items': 'center',
'justify-content': 'center',
}}
>
<yt-formatted-string
class="description ytmusic-description-shelf-renderer"
text={{ runs: [{ text: t('plugins.synced-lyrics.advanced-options.offset.title') }] }}
/>
<div style={{ display: 'flex', 'flex-direction': 'row' }}>
<input
class="lrcpkradv-offset"
type="number"
step={50}
value={lyricsOffset()}
onFocus={() => setTyping(true)}
onBlur={(e) => {
let value = e.target.valueAsNumber;
if (isNaN(value)) value = 0;

setLyricsOffset(value);
setTyping(false)
}}
onInput={() => setTyping(true)}
/>
<span>
<button
class="lrcpkradv-offset-btn"
disabled={typing()}
onclick={() => setLyricsOffset((old) => old - 50)}
>
-
</button>
/
<button
class="lrcpkradv-offset-btn"
disabled={typing()}
onclick={() => setLyricsOffset((old) => old + 50)}
>
+
</button>
</span>
</div>
</div>
);
};
29 changes: 26 additions & 3 deletions src/plugins/synced-lyrics/renderer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,24 @@ import { createRenderer } from '@/utils';
import { waitForElement } from '@/utils/wait-for-element';

import { selectors, tabStates } from './utils';
import { setConfig, setCurrentTime } from './renderer';
import { config, setConfig, setCurrentTime } from './renderer';

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';
import { createEffect } from 'solid-js';
import {
lyricsOffset,
setLyricsOffset,
} from './components/LyricsPickerAdvanced';

export let _ytAPI: YoutubePlayer | null = null;
export let netFetch: (
url: string,
init?: RequestInit
init?: RequestInit,
) => Promise<[number, string, Record<string, string>]>;

export const renderer = createRenderer<
Expand All @@ -28,6 +33,7 @@ export const renderer = createRenderer<
>({
onConfigChange(newConfig) {
setConfig(newConfig);
setLyricsOffset(newConfig.lyricsOffset);
},

observerCallback(mutations: MutationRecord[]) {
Expand Down Expand Up @@ -56,7 +62,7 @@ export const renderer = createRenderer<
if (!this.updateTimestampInterval) {
this.updateTimestampInterval = setInterval(
() => setCurrentTime((_ytAPI?.getCurrentTime() ?? 0) * 1000),
100
100,
);
}

Expand All @@ -80,6 +86,23 @@ export const renderer = createRenderer<

setConfig(await ctx.getConfig());

let hasInit = false;
createEffect(() => {
const offset = lyricsOffset();
if (offset !== 0) return;

if (hasInit) return;
hasInit = true;

setLyricsOffset(config()?.lyricsOffset ?? 0);
});

createEffect(() => {
if (!hasInit) return;
const offset = lyricsOffset();
ctx.setConfig({ lyricsOffset: offset });
});

ctx.ipc.on('ytmd:update-song-info', (info: SongInfo) => {
fetchLyrics(info);
});
Expand Down
57 changes: 48 additions & 9 deletions src/plugins/synced-lyrics/renderer/renderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
} from 'solid-js';
import { type VirtualizerHandle, VList } from 'virtua/solid';

import { LyricsPicker } from './components/LyricsPicker';
import { LyricsPicker, pickerAdvancedOpen } from './components/LyricsPicker';

import { selectors } from './utils';

Expand All @@ -23,6 +23,7 @@ import {
import { currentLyrics } from '../providers';

import type { LineLyrics, SyncedLyricsPluginConfig } from '../types';
import { LyricsPickerAdvanced } from './components/LyricsPickerAdvanced';

export const [isVisible, setIsVisible] = createSignal<boolean>(false);
export const [config, setConfig] =
Expand Down Expand Up @@ -155,21 +156,43 @@ export const LyricsRenderer = () => {
mouseCoord = (e as MouseEvent).clientY;
}

const ref = stickyRef()!;
const [
[realPicker, pickerHeight],
[_, divHeight],
[realAdvanced, advancedHeight],
] = Array.from(ref.children).map((c) => {
const style = getComputedStyle(c);
return [
parseFloat(style.height) -
(parseFloat(style.paddingTop) + parseFloat(style.paddingBottom)),
c.clientHeight,
];
});

const contentHeight = pickerAdvancedOpen()
? pickerHeight + advancedHeight
: pickerHeight;
ref.style.height = `${
pickerAdvancedOpen() ? realPicker + divHeight + realAdvanced : realPicker
}px`;

const { top } = tab.getBoundingClientRect();
const { clientHeight: height } = stickyRef()!;
const scrollOffset = scroller()?.scrollOffset ?? -1;

const isInView = scrollOffset <= height;
const isMouseOver = mouseCoord - top - 5 <= height;
const isMouseOver = mouseCoord - top - 5 <= contentHeight;

const showPicker = isInView || isMouseOver;
console.log({ relative: mouseCoord - top - 5, showPicker });

if (showPicker) {
// picker visible
stickyRef()!.style.setProperty('--lyrics-picker-top', '0');
ref.style.setProperty('--lyrics-picker-top', '0');
} else {
// picker hidden
stickyRef()!.style.setProperty('--lyrics-picker-top', `-${height}px`);
ref.style.setProperty('--lyrics-picker-top', `-${contentHeight}px`);
}
};

Expand Down Expand Up @@ -228,11 +251,11 @@ export const LyricsRenderer = () => {
});
});

const [statuses, setStatuses] = createSignal<
('previous' | 'current' | 'upcoming')[]
>([]);
// prettier-ignore
const [statuses, setStatuses] = createSignal<('previous' | 'current' | 'upcoming')[]>([]);

createEffect(() => {
const time = currentTime();
const time = Math.max(0, currentTime() + (config()?.lyricsOffset ?? 0));
const data = currentLyrics()?.data;

if (!data || !data.lines) return setStatuses([]);
Expand Down Expand Up @@ -290,7 +313,23 @@ export const LyricsRenderer = () => {
if (typeof props === 'undefined') return null;
switch (props.kind) {
case 'LyricsPicker':
return <LyricsPicker setStickRef={setStickRef} />;
return (
<div class="lyrics-picker-container" ref={setStickRef}>
<LyricsPicker />
<div
id="divider"
class="style-scope ytmusic-guide-section-renderer"
style={{ width: '100%', margin: '0' }}
></div>
<div
class={`lyrics-picker-advanced ${
pickerAdvancedOpen() ? 'open' : ''
}`}
>
<LyricsPickerAdvanced />
</div>
</div>
);
case 'Error':
return <ErrorDisplay {...props} />;
case 'LoadingKaomoji':
Expand Down
Loading