Add lyric search selection and override

This commit is contained in:
jeffvli 2023-06-09 02:38:04 -07:00 committed by Jeff
parent f8ecb3fc53
commit 2f0634dc03
6 changed files with 140 additions and 35 deletions

View file

@ -1,4 +1,5 @@
import { QueryFunctionContext } from '@tanstack/react-query'; import { QueryFunctionContext } from '@tanstack/react-query';
import { LyricSource } from './types';
import type { import type {
AlbumListQuery, AlbumListQuery,
SongListQuery, SongListQuery,
@ -108,6 +109,9 @@ export const queryKeys: Record<
if (query) return [serverId, 'song', 'lyrics', query] as const; if (query) return [serverId, 'song', 'lyrics', query] as const;
return [serverId, 'song', 'lyrics'] as const; return [serverId, 'song', 'lyrics'] as const;
}, },
lyricsByRemoteId: (searchQuery: { remoteSongId: string; remoteSource: LyricSource }) => {
return ['song', 'lyrics', 'remote', searchQuery] as const;
},
lyricsSearch: (query?: LyricSearchQuery) => { lyricsSearch: (query?: LyricSearchQuery) => {
if (query) return ['lyrics', 'search', query] as const; if (query) return ['lyrics', 'search', query] as const;
return ['lyrics', 'search'] as const; return ['lyrics', 'search'] as const;

View file

@ -1,32 +1,40 @@
import { useMemo } from 'react'; import { useMemo } from 'react';
import { Divider, Group, Stack, UnstyledButton } from '@mantine/core'; import { Divider, Group, Stack } from '@mantine/core';
import { useForm } from '@mantine/form'; import { useForm } from '@mantine/form';
import { useDebouncedValue } from '@mantine/hooks'; import { useDebouncedValue } from '@mantine/hooks';
import { openModal } from '@mantine/modals'; import { openModal } from '@mantine/modals';
import styled from 'styled-components'; import styled from 'styled-components';
import { InternetProviderLyricSearchResponse } from '../../../api/types'; import {
InternetProviderLyricSearchResponse,
LyricSource,
LyricsOverride,
} from '../../../api/types';
import { useLyricSearch } from '../queries/lyric-search-query'; import { useLyricSearch } from '../queries/lyric-search-query';
import { Badge, ScrollArea, Spinner, Text, TextInput } from '/@/renderer/components'; import { Badge, ScrollArea, Spinner, Text, TextInput } from '/@/renderer/components';
const SearchItem = styled(UnstyledButton)` const SearchItem = styled.button`
all: unset;
box-sizing: border-box !important;
padding: 0.5rem;
border-radius: 5px;
cursor: pointer;
&:hover, &:hover,
&:focus-visible { &:focus-visible {
color: var(--btn-default-fg-hover); color: var(--btn-default-fg-hover);
background: var(--btn-default-bg-hover); background: var(--btn-default-bg-hover);
} }
padding: 0.5rem;
border-radius: 5px;
`; `;
interface SearchResultProps { interface SearchResultProps {
artist?: string; artist?: string;
name?: string; name?: string;
onClick?: () => void;
source?: string; source?: string;
} }
const SearchResult = ({ name, artist, source }: SearchResultProps) => { const SearchResult = ({ name, artist, source, onClick }: SearchResultProps) => {
return ( return (
<SearchItem> <SearchItem onClick={onClick}>
<Group <Group
noWrap noWrap
position="apart" position="apart"
@ -35,7 +43,12 @@ const SearchResult = ({ name, artist, source }: SearchResultProps) => {
maw="65%" maw="65%"
spacing={0} spacing={0}
> >
<Text size="md">{name}</Text> <Text
size="md"
weight={600}
>
{name}
</Text>
<Text $secondary>{artist}</Text> <Text $secondary>{artist}</Text>
</Stack> </Stack>
<Badge size="lg">{source}</Badge> <Badge size="lg">{source}</Badge>
@ -47,10 +60,10 @@ const SearchResult = ({ name, artist, source }: SearchResultProps) => {
interface LyricSearchFormProps { interface LyricSearchFormProps {
artist?: string; artist?: string;
name?: string; name?: string;
onSelect?: (lyrics: InternetProviderLyricSearchResponse) => void; onSearchOverride?: (params: LyricsOverride) => void;
} }
export const LyricsSearchForm = ({ artist, name }: LyricSearchFormProps) => { export const LyricsSearchForm = ({ artist, name, onSearchOverride }: LyricSearchFormProps) => {
const form = useForm({ const form = useForm({
initialValues: { initialValues: {
artist: artist || '', artist: artist || '',
@ -69,8 +82,6 @@ export const LyricsSearchForm = ({ artist, name }: LyricSearchFormProps) => {
const searchResults = useMemo(() => { const searchResults = useMemo(() => {
if (!data) return []; if (!data) return [];
console.log('data', data);
const results: InternetProviderLyricSearchResponse[] = []; const results: InternetProviderLyricSearchResponse[] = [];
Object.keys(data).forEach((key) => { Object.keys(data).forEach((key) => {
(data[key as keyof typeof data] || []).forEach((result) => results.push(result)); (data[key as keyof typeof data] || []).forEach((result) => results.push(result));
@ -102,7 +113,7 @@ export const LyricsSearchForm = ({ artist, name }: LyricSearchFormProps) => {
) : ( ) : (
<ScrollArea <ScrollArea
offsetScrollbars offsetScrollbars
h={500} h={350}
pr="1rem" pr="1rem"
> >
<Stack spacing="md"> <Stack spacing="md">
@ -112,6 +123,15 @@ export const LyricsSearchForm = ({ artist, name }: LyricSearchFormProps) => {
artist={result.artist} artist={result.artist}
name={result.name} name={result.name}
source={result.source} source={result.source}
onClick={() => {
onSearchOverride?.({
artist: result.artist,
id: result.id,
name: result.name,
remote: true,
source: result.source as LyricSource,
});
}}
/> />
))} ))}
</Stack> </Stack>
@ -121,12 +141,13 @@ export const LyricsSearchForm = ({ artist, name }: LyricSearchFormProps) => {
); );
}; };
export const openLyricSearchModal = ({ artist, name }: LyricSearchFormProps) => { export const openLyricSearchModal = ({ artist, name, onSearchOverride }: LyricSearchFormProps) => {
openModal({ openModal({
children: ( children: (
<LyricsSearchForm <LyricsSearchForm
artist={artist} artist={artist}
name={name} name={name}
onSearchOverride={onSearchOverride}
/> />
), ),
size: 'lg', size: 'lg',

View file

@ -1,19 +1,26 @@
import { RiAddFill, RiSubtractFill } from 'react-icons/ri'; import { RiAddFill, RiSubtractFill } from 'react-icons/ri';
import { LyricsOverride } from '/@/renderer/api/types';
import { Button, NumberInput } from '/@/renderer/components'; import { Button, NumberInput } from '/@/renderer/components';
import { openLyricSearchModal } from '/@/renderer/features/lyrics/components/lyrics-search-form'; import { openLyricSearchModal } from '/@/renderer/features/lyrics/components/lyrics-search-form';
import { useCurrentSong } from '/@/renderer/store'; import { useCurrentSong } from '/@/renderer/store';
export const LyricsActions = () => { interface LyricsActionsProps {
onSearchOverride?: (params: LyricsOverride) => void;
}
export const LyricsActions = ({ onSearchOverride }: LyricsActionsProps) => {
const currentSong = useCurrentSong(); const currentSong = useCurrentSong();
return ( return (
<> <>
<Button <Button
variant="default" uppercase
variant="subtle"
onClick={() => onClick={() =>
openLyricSearchModal({ openLyricSearchModal({
artist: currentSong?.artistName, artist: currentSong?.artistName,
name: currentSong?.name, name: currentSong?.name,
onSearchOverride,
}) })
} }
> >
@ -21,7 +28,7 @@ export const LyricsActions = () => {
</Button> </Button>
<Button <Button
tooltip={{ label: 'Decrease offset', openDelay: 500 }} tooltip={{ label: 'Decrease offset', openDelay: 500 }}
variant="default" variant="subtle"
> >
<RiSubtractFill /> <RiSubtractFill />
</Button> </Button>
@ -31,12 +38,13 @@ export const LyricsActions = () => {
/> />
<Button <Button
tooltip={{ label: 'Increase offset', openDelay: 500 }} tooltip={{ label: 'Increase offset', openDelay: 500 }}
variant="default" variant="subtle"
> >
<RiAddFill /> <RiAddFill />
</Button> </Button>
<Button <Button
variant="default" uppercase
variant="subtle"
onClick={() => onClick={() =>
openLyricSearchModal({ openLyricSearchModal({
artist: currentSong?.artistName, artist: currentSong?.artistName,

View file

@ -1,16 +1,21 @@
import { useEffect, useState } from 'react'; import { useCallback, useEffect, useState } from 'react';
import { Center, Group } from '@mantine/core'; import { Center, Group } from '@mantine/core';
import { AnimatePresence, motion } from 'framer-motion'; import { AnimatePresence, motion } from 'framer-motion';
import { ErrorBoundary } from 'react-error-boundary'; import { ErrorBoundary } from 'react-error-boundary';
import { RiInformationFill } from 'react-icons/ri'; import { RiInformationFill } from 'react-icons/ri';
import styled from 'styled-components'; import styled from 'styled-components';
import { useSongLyrics } from './queries/lyric-query'; import { useSongLyricsByRemoteId, useSongLyricsBySong } from './queries/lyric-query';
import { SynchronizedLyrics } from './synchronized-lyrics'; import { SynchronizedLyrics } from './synchronized-lyrics';
import { ScrollArea, Spinner, TextTitle } from '/@/renderer/components'; import { ScrollArea, Spinner, TextTitle } from '/@/renderer/components';
import { ErrorFallback } from '/@/renderer/features/action-required'; import { ErrorFallback } from '/@/renderer/features/action-required';
import { UnsynchronizedLyrics } from '/@/renderer/features/lyrics/unsynchronized-lyrics'; import { UnsynchronizedLyrics } from '/@/renderer/features/lyrics/unsynchronized-lyrics';
import { getServerById, useCurrentSong } from '/@/renderer/store'; import { getServerById, useCurrentSong } from '/@/renderer/store';
import { FullLyricsMetadata, SynchronizedLyricMetadata } from '/@/renderer/api/types'; import {
FullLyricsMetadata,
LyricsOverride,
SynchronizedLyricMetadata,
UnsynchronizedLyricMetadata,
} from '/@/renderer/api/types';
import { LyricsActions } from '/@/renderer/features/lyrics/lyrics-actions'; import { LyricsActions } from '/@/renderer/features/lyrics/lyrics-actions';
const ActionsContainer = styled.div` const ActionsContainer = styled.div`
@ -70,9 +75,12 @@ const ScrollContainer = styled(motion(ScrollArea))`
} }
`; `;
function isSynchronized(data: FullLyricsMetadata): data is SynchronizedLyricMetadata { function isSynchronized(
data: Partial<FullLyricsMetadata> | undefined,
): data is SynchronizedLyricMetadata {
// Type magic. The only difference between Synchronized and Unsynchhronized is // Type magic. The only difference between Synchronized and Unsynchhronized is
// the datatype of lyrics. This makes Typescript happier later... // the datatype of lyrics. This makes Typescript happier later...
if (!data) return false;
return Array.isArray(data.lyrics); return Array.isArray(data.lyrics);
} }
@ -82,7 +90,7 @@ export const Lyrics = () => {
const [clear, setClear] = useState(false); const [clear, setClear] = useState(false);
const { data, isInitialLoading } = useSongLyrics( const { data, isInitialLoading } = useSongLyricsBySong(
{ {
query: { songId: currentSong?.id || '' }, query: { songId: currentSong?.id || '' },
serverId: currentServer?.id, serverId: currentServer?.id,
@ -90,14 +98,48 @@ export const Lyrics = () => {
currentSong, currentSong,
); );
const [override, setOverride] = useState<LyricsOverride | undefined>(undefined);
const handleOnSearchOverride = useCallback((params: LyricsOverride) => {
setOverride(params);
}, []);
const { data: overrideLyrics, isInitialLoading: isOverrideLoading } = useSongLyricsByRemoteId({
options: {
enabled: !!override,
},
query: {
remoteSongId: override?.id,
remoteSource: override?.source,
},
serverId: currentServer?.id,
});
useEffect(() => { useEffect(() => {
// We want to reset the clear flag whenever a song changes // We want to reset the clear flag whenever a song changes
setClear(false); setClear(false);
}, [currentSong]); }, [currentSong]);
const isLoadingLyrics = isInitialLoading || isOverrideLoading;
const lyricsMetadata:
| Partial<SynchronizedLyricMetadata>
| Partial<UnsynchronizedLyricMetadata>
| undefined = overrideLyrics
? {
artist: override?.artist,
lyrics: overrideLyrics,
name: override?.name,
remote: true,
source: override?.source,
}
: data;
const isSynchronizedLyrics = isSynchronized(lyricsMetadata);
return ( return (
<ErrorBoundary FallbackComponent={ErrorFallback}> <ErrorBoundary FallbackComponent={ErrorFallback}>
{isInitialLoading ? ( {isLoadingLyrics ? (
<Spinner <Spinner
container container
size={25} size={25}
@ -124,14 +166,14 @@ export const Lyrics = () => {
scrollHideDelay={0} scrollHideDelay={0}
transition={{ duration: 0.5 }} transition={{ duration: 0.5 }}
> >
{isSynchronized(data) ? ( {isSynchronizedLyrics ? (
<SynchronizedLyrics <SynchronizedLyrics
{...data} {...lyricsMetadata}
onRemoveLyric={() => setClear(true)} onRemoveLyric={() => setClear(true)}
/> />
) : ( ) : (
<UnsynchronizedLyrics <UnsynchronizedLyrics
{...data} {...(lyricsMetadata as UnsynchronizedLyricMetadata)}
onRemoveLyric={() => setClear(true)} onRemoveLyric={() => setClear(true)}
/> />
)} )}
@ -139,7 +181,7 @@ export const Lyrics = () => {
)} )}
<ActionsContainer> <ActionsContainer>
<LyricsActions /> <LyricsActions onSearchOverride={handleOnSearchOverride} />
</ActionsContainer> </ActionsContainer>
</LyricsContainer> </LyricsContainer>
</AnimatePresence> </AnimatePresence>

View file

@ -5,6 +5,7 @@ import {
SynchronizedLyricsArray, SynchronizedLyricsArray,
InternetProviderLyricResponse, InternetProviderLyricResponse,
FullLyricsMetadata, FullLyricsMetadata,
LyricGetQuery,
} from '/@/renderer/api/types'; } from '/@/renderer/api/types';
import { QueryHookArgs } from '/@/renderer/lib/react-query'; import { QueryHookArgs } from '/@/renderer/lib/react-query';
import { getServerById, useLyricsSettings } from '/@/renderer/store'; import { getServerById, useLyricsSettings } from '/@/renderer/store';
@ -43,7 +44,10 @@ const formatLyrics = (lyrics: string) => {
const alternateSynchronizedLines = lyrics.matchAll(alternateTimeExp); const alternateSynchronizedLines = lyrics.matchAll(alternateTimeExp);
for (const line of alternateSynchronizedLines) { for (const line of alternateSynchronizedLines) {
const [, timeInMilis, , text] = line; const [, timeInMilis, , text] = line;
const cleanText = text.replaceAll(/\(\d+,\d+\)/g, ''); const cleanText = text
.replaceAll(/\(\d+,\d+\)/g, '')
.replaceAll(/\s,/g, ',')
.replaceAll(/\s\./g, '.');
formattedLyrics.push([Number(timeInMilis), cleanText]); formattedLyrics.push([Number(timeInMilis), cleanText]);
} }
@ -73,7 +77,7 @@ export const useServerLyrics = (
}); });
}; };
export const useSongLyrics = ( export const useSongLyricsBySong = (
args: QueryHookArgs<LyricsQuery>, args: QueryHookArgs<LyricsQuery>,
song: QueueSong | undefined, song: QueueSong | undefined,
): UseQueryResult<FullLyricsMetadata> => { ): UseQueryResult<FullLyricsMetadata> => {
@ -120,7 +124,7 @@ export const useSongLyrics = (
if (fetch) { if (fetch) {
const remoteLyricsResult: InternetProviderLyricResponse | null = const remoteLyricsResult: InternetProviderLyricResponse | null =
await lyricsIpc?.fetchRemoteLyrics(song); await lyricsIpc?.getRemoteLyricsBySong(song);
if (remoteLyricsResult) { if (remoteLyricsResult) {
return { return {
@ -137,3 +141,26 @@ export const useSongLyrics = (
staleTime: 1000 * 60 * 2, staleTime: 1000 * 60 * 2,
}); });
}; };
export const useSongLyricsByRemoteId = (
args: QueryHookArgs<Partial<LyricGetQuery>>,
): UseQueryResult<string | null> => {
const { query } = args;
return useQuery({
cacheTime: 1000 * 60 * 10,
enabled: !!query.remoteSongId && !!query.remoteSource,
onError: () => {},
queryFn: async () => {
const remoteLyricsResult: string | null = await lyricsIpc?.getRemoteLyricsByRemoteId(query);
if (remoteLyricsResult) {
return formatLyrics(remoteLyricsResult);
}
return null;
},
queryKey: queryKeys.songs.lyricsByRemoteId(query),
staleTime: 1000 * 60 * 5,
});
};

View file

@ -1,9 +1,12 @@
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import isElectron from 'is-electron'; import isElectron from 'is-electron';
import { queryKeys } from '/@/renderer/api/query-keys'; import { queryKeys } from '/@/renderer/api/query-keys';
import { InternetProviderLyricSearchResponse, LyricSearchQuery } from '/@/renderer/api/types'; import {
InternetProviderLyricSearchResponse,
LyricSearchQuery,
LyricSource,
} from '/@/renderer/api/types';
import { QueryHookArgs } from '/@/renderer/lib/react-query'; import { QueryHookArgs } from '/@/renderer/lib/react-query';
import { LyricSource } from '/@/renderer/types';
const lyricsIpc = isElectron() ? window.electron.lyrics : null; const lyricsIpc = isElectron() ? window.electron.lyrics : null;