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

View file

@ -1,32 +1,40 @@
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 { useDebouncedValue } from '@mantine/hooks';
import { openModal } from '@mantine/modals';
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 { 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,
&:focus-visible {
color: var(--btn-default-fg-hover);
background: var(--btn-default-bg-hover);
}
padding: 0.5rem;
border-radius: 5px;
`;
interface SearchResultProps {
artist?: string;
name?: string;
onClick?: () => void;
source?: string;
}
const SearchResult = ({ name, artist, source }: SearchResultProps) => {
const SearchResult = ({ name, artist, source, onClick }: SearchResultProps) => {
return (
<SearchItem>
<SearchItem onClick={onClick}>
<Group
noWrap
position="apart"
@ -35,7 +43,12 @@ const SearchResult = ({ name, artist, source }: SearchResultProps) => {
maw="65%"
spacing={0}
>
<Text size="md">{name}</Text>
<Text
size="md"
weight={600}
>
{name}
</Text>
<Text $secondary>{artist}</Text>
</Stack>
<Badge size="lg">{source}</Badge>
@ -47,10 +60,10 @@ const SearchResult = ({ name, artist, source }: SearchResultProps) => {
interface LyricSearchFormProps {
artist?: 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({
initialValues: {
artist: artist || '',
@ -69,8 +82,6 @@ export const LyricsSearchForm = ({ artist, name }: LyricSearchFormProps) => {
const searchResults = useMemo(() => {
if (!data) return [];
console.log('data', data);
const results: InternetProviderLyricSearchResponse[] = [];
Object.keys(data).forEach((key) => {
(data[key as keyof typeof data] || []).forEach((result) => results.push(result));
@ -102,7 +113,7 @@ export const LyricsSearchForm = ({ artist, name }: LyricSearchFormProps) => {
) : (
<ScrollArea
offsetScrollbars
h={500}
h={350}
pr="1rem"
>
<Stack spacing="md">
@ -112,6 +123,15 @@ export const LyricsSearchForm = ({ artist, name }: LyricSearchFormProps) => {
artist={result.artist}
name={result.name}
source={result.source}
onClick={() => {
onSearchOverride?.({
artist: result.artist,
id: result.id,
name: result.name,
remote: true,
source: result.source as LyricSource,
});
}}
/>
))}
</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({
children: (
<LyricsSearchForm
artist={artist}
name={name}
onSearchOverride={onSearchOverride}
/>
),
size: 'lg',

View file

@ -1,19 +1,26 @@
import { RiAddFill, RiSubtractFill } from 'react-icons/ri';
import { LyricsOverride } from '/@/renderer/api/types';
import { Button, NumberInput } from '/@/renderer/components';
import { openLyricSearchModal } from '/@/renderer/features/lyrics/components/lyrics-search-form';
import { useCurrentSong } from '/@/renderer/store';
export const LyricsActions = () => {
interface LyricsActionsProps {
onSearchOverride?: (params: LyricsOverride) => void;
}
export const LyricsActions = ({ onSearchOverride }: LyricsActionsProps) => {
const currentSong = useCurrentSong();
return (
<>
<Button
variant="default"
uppercase
variant="subtle"
onClick={() =>
openLyricSearchModal({
artist: currentSong?.artistName,
name: currentSong?.name,
onSearchOverride,
})
}
>
@ -21,7 +28,7 @@ export const LyricsActions = () => {
</Button>
<Button
tooltip={{ label: 'Decrease offset', openDelay: 500 }}
variant="default"
variant="subtle"
>
<RiSubtractFill />
</Button>
@ -31,12 +38,13 @@ export const LyricsActions = () => {
/>
<Button
tooltip={{ label: 'Increase offset', openDelay: 500 }}
variant="default"
variant="subtle"
>
<RiAddFill />
</Button>
<Button
variant="default"
uppercase
variant="subtle"
onClick={() =>
openLyricSearchModal({
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 { AnimatePresence, motion } from 'framer-motion';
import { ErrorBoundary } from 'react-error-boundary';
import { RiInformationFill } from 'react-icons/ri';
import styled from 'styled-components';
import { useSongLyrics } from './queries/lyric-query';
import { useSongLyricsByRemoteId, useSongLyricsBySong } from './queries/lyric-query';
import { SynchronizedLyrics } from './synchronized-lyrics';
import { ScrollArea, Spinner, TextTitle } from '/@/renderer/components';
import { ErrorFallback } from '/@/renderer/features/action-required';
import { UnsynchronizedLyrics } from '/@/renderer/features/lyrics/unsynchronized-lyrics';
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';
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
// the datatype of lyrics. This makes Typescript happier later...
if (!data) return false;
return Array.isArray(data.lyrics);
}
@ -82,7 +90,7 @@ export const Lyrics = () => {
const [clear, setClear] = useState(false);
const { data, isInitialLoading } = useSongLyrics(
const { data, isInitialLoading } = useSongLyricsBySong(
{
query: { songId: currentSong?.id || '' },
serverId: currentServer?.id,
@ -90,14 +98,48 @@ export const Lyrics = () => {
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(() => {
// We want to reset the clear flag whenever a song changes
setClear(false);
}, [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 (
<ErrorBoundary FallbackComponent={ErrorFallback}>
{isInitialLoading ? (
{isLoadingLyrics ? (
<Spinner
container
size={25}
@ -124,14 +166,14 @@ export const Lyrics = () => {
scrollHideDelay={0}
transition={{ duration: 0.5 }}
>
{isSynchronized(data) ? (
{isSynchronizedLyrics ? (
<SynchronizedLyrics
{...data}
{...lyricsMetadata}
onRemoveLyric={() => setClear(true)}
/>
) : (
<UnsynchronizedLyrics
{...data}
{...(lyricsMetadata as UnsynchronizedLyricMetadata)}
onRemoveLyric={() => setClear(true)}
/>
)}
@ -139,7 +181,7 @@ export const Lyrics = () => {
)}
<ActionsContainer>
<LyricsActions />
<LyricsActions onSearchOverride={handleOnSearchOverride} />
</ActionsContainer>
</LyricsContainer>
</AnimatePresence>

View file

@ -5,6 +5,7 @@ import {
SynchronizedLyricsArray,
InternetProviderLyricResponse,
FullLyricsMetadata,
LyricGetQuery,
} from '/@/renderer/api/types';
import { QueryHookArgs } from '/@/renderer/lib/react-query';
import { getServerById, useLyricsSettings } from '/@/renderer/store';
@ -43,7 +44,10 @@ const formatLyrics = (lyrics: string) => {
const alternateSynchronizedLines = lyrics.matchAll(alternateTimeExp);
for (const line of alternateSynchronizedLines) {
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]);
}
@ -73,7 +77,7 @@ export const useServerLyrics = (
});
};
export const useSongLyrics = (
export const useSongLyricsBySong = (
args: QueryHookArgs<LyricsQuery>,
song: QueueSong | undefined,
): UseQueryResult<FullLyricsMetadata> => {
@ -120,7 +124,7 @@ export const useSongLyrics = (
if (fetch) {
const remoteLyricsResult: InternetProviderLyricResponse | null =
await lyricsIpc?.fetchRemoteLyrics(song);
await lyricsIpc?.getRemoteLyricsBySong(song);
if (remoteLyricsResult) {
return {
@ -137,3 +141,26 @@ export const useSongLyrics = (
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 isElectron from 'is-electron';
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 { LyricSource } from '/@/renderer/types';
const lyricsIpc = isElectron() ? window.electron.lyrics : null;