-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathstore.ts
More file actions
238 lines (203 loc) Β· 6.08 KB
/
store.ts
File metadata and controls
238 lines (203 loc) Β· 6.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import { createStore } from 'solid-js/store';
import { createMemo } from 'solid-js';
import { detect } from 'tinyld';
import { getSongInfo } from '@/providers/song-info-front';
import {
type ProviderName,
providerNames,
type ProviderState,
} from '../providers';
import { providers } from '../providers/renderer';
import type { LyricProvider, LyricResult } from '../types';
import type { SongInfo } from '@/providers/song-info';
type LyricsStore = {
provider: ProviderName;
current: ProviderState;
lyrics: Record<ProviderName, ProviderState>;
};
const initialData = () =>
providerNames.reduce(
(acc, name) => {
acc[name] = { state: 'fetching', data: null, error: null };
return acc;
},
{} as LyricsStore['lyrics'],
);
export const [lyricsStore, setLyricsStore] = createStore<LyricsStore>({
provider: providerNames[0],
lyrics: initialData(),
get current(): ProviderState {
return this.lyrics[this.provider];
},
});
export const currentLyrics = createMemo(() => {
const provider = lyricsStore.provider;
return lyricsStore.lyrics[provider];
});
/**
* Returns the best available provider result that has a detected language,
* without requiring lyricsStore.provider to have been set by LyricsPicker.
* Prefers the currently selected provider, then falls back to any done provider
* with a language so that auto-skip works even when the lyrics panel is hidden.
*/
export const bestLanguageResult = createMemo(() => {
const current = lyricsStore.lyrics[lyricsStore.provider];
if (current.state === 'done' && current.data?.language) return current;
for (const name of providerNames) {
const state = lyricsStore.lyrics[name];
if (state.state === 'done' && state.data?.language) return state;
}
return null;
});
type VideoId = string;
type SearchCacheData = Record<ProviderName, ProviderState>;
interface SearchCache {
state: 'loading' | 'done';
data: SearchCacheData;
}
// TODO: Maybe use localStorage for the cache.
const searchCache = new Map<VideoId, SearchCache>();
/**
* Detects the language of lyrics and adds it to the result.
* Handles edge cases: no lyrics, empty text, detection failure.
*/
const detectLyricsLanguage = (
result: LyricResult | null,
): LyricResult | null => {
if (!result) return null;
try {
// Extract text from either plain lyrics or synced lines
let textToAnalyze = '';
if (result.lyrics) {
textToAnalyze = result.lyrics.trim();
} else if (result.lines && result.lines.length > 0) {
textToAnalyze = result.lines
.map((line) => line.text)
.join('\n')
.trim();
}
// Only attempt detection if we have meaningful text
if (textToAnalyze.length > 0) {
const detectedLang = detect(textToAnalyze);
// Only set language if detection was successful (not empty string)
if (detectedLang) {
return { ...result, language: detectedLang };
}
}
} catch (error) {
// Detection failed - log but don't throw, just leave language undefined
console.warn('Language detection failed:', error);
}
return result;
};
export const fetchLyrics = (info: SongInfo) => {
if (searchCache.has(info.videoId)) {
const cache = searchCache.get(info.videoId)!;
if (cache.state === 'loading') {
setTimeout(() => {
fetchLyrics(info);
});
return;
}
if (getSongInfo().videoId === info.videoId) {
setLyricsStore('lyrics', () => {
// weird bug with solid-js
return JSON.parse(JSON.stringify(cache.data)) as typeof cache.data;
});
}
return;
}
const cache: SearchCache = {
state: 'loading',
data: initialData(),
};
searchCache.set(info.videoId, cache);
if (getSongInfo().videoId === info.videoId) {
setLyricsStore('lyrics', () => {
// weird bug with solid-js
return JSON.parse(JSON.stringify(cache.data)) as typeof cache.data;
});
}
const tasks: Promise<void>[] = [];
// prettier-ignore
for (
const [providerName, provider] of Object.entries(providers) as [
ProviderName,
LyricProvider,
][]
) {
const pCache = cache.data[providerName];
tasks.push(
provider
.search(info)
.then((res) => {
// Detect language from the lyrics result
const resultWithLanguage = detectLyricsLanguage(res);
pCache.state = 'done';
pCache.data = resultWithLanguage;
if (getSongInfo().videoId === info.videoId) {
setLyricsStore('lyrics', (old) => {
return {
...old,
[providerName]: {
state: 'done',
data: resultWithLanguage ? { ...resultWithLanguage } : null,
error: null,
},
};
});
}
})
.catch((error: Error) => {
pCache.state = 'error';
pCache.error = error;
console.error(error);
if (getSongInfo().videoId === info.videoId) {
setLyricsStore('lyrics', (old) => {
return {
...old,
[providerName]: { state: 'error', error, data: null },
};
});
}
}),
);
}
Promise.allSettled(tasks).then(() => {
cache.state = 'done';
searchCache.set(info.videoId, cache);
});
};
export const retrySearch = (provider: ProviderName, info: SongInfo) => {
setLyricsStore('lyrics', (old) => {
const pCache = {
state: 'fetching',
data: null,
error: null,
};
return {
...old,
[provider]: pCache,
};
});
providers[provider]
.search(info)
.then((res) => {
// Detect language from the lyrics result
const resultWithLanguage = detectLyricsLanguage(res);
setLyricsStore('lyrics', (old) => {
return {
...old,
[provider]: { state: 'done', data: resultWithLanguage, error: null },
};
});
})
.catch((error) => {
setLyricsStore('lyrics', (old) => {
return {
...old,
[provider]: { state: 'error', data: null, error },
};
});
});
};