-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathArtistMetadataEditorModal.tsx
More file actions
494 lines (468 loc) Β· 19.3 KB
/
Copy pathArtistMetadataEditorModal.tsx
File metadata and controls
494 lines (468 loc) Β· 19.3 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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Loader2, Search, User, X, Split } from "lucide-react";
import { useModalA11y } from "../../hooks/useModalA11y";
import { AnimatedModalContent, AnimatedModalShell } from "./AnimatedModalShell";
import {
getArtistOverrides,
setArtistMetadataOverrides,
splitArtist,
type ArtistOverrideSimilar,
} from "../../lib/tauri/artistOverrides";
import { searchArtists, type ArtistRow } from "../../lib/tauri/browse";
import { resolveRemoteImage } from "../../lib/tauri/artwork";
/** Mirror of the backend `MAX_SIMILAR` cap so the UI blocks before the
* server would silently truncate. */
const MAX_SIMILAR = 50;
interface ArtistMetadataEditorModalProps {
artistId: number;
artistName: string;
isOpen: boolean;
onClose: () => void;
/** Fired after a successful save so the detail view re-reads the
* (now overridden) bio + similar list. */
onSuccess: () => void;
/** Fired after a successful comma-split (issue #396). The phantom
* artist page this modal was opened from no longer exists, so the
* caller should navigate to the new primary artist (or away).
* `primaryArtistId` is `null` only in the degenerate case where the
* split resolved no distinct artist. */
onSplit?: (primaryArtistId: number | null) => void;
}
/**
* Per-artist override editor (issue #323). Two offline-first controls:
* - a free-text bio that replaces the fetched Last.fm/TheAudioDB one
* - a library-scoped, user-curated similar-artist list
*
* Both persist per-profile and survive enrichment passes. Clearing the
* bio field or removing every chip drops the respective override so the
* online value takes back over.
*/
export function ArtistMetadataEditorModal({
artistId,
artistName,
isOpen,
onClose,
onSuccess,
onSplit,
}: ArtistMetadataEditorModalProps) {
const { t } = useTranslation();
const [bio, setBio] = useState("");
const [selected, setSelected] = useState<ArtistOverrideSimilar[]>([]);
const [query, setQuery] = useState("");
const [results, setResults] = useState<ArtistRow[]>([]);
const [isSearching, setIsSearching] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [isSplitting, setIsSplitting] = useState(false);
const [error, setError] = useState<string | null>(null);
// Ignore user-initiated close (Escape / backdrop / Cancel) while a split
// is running so the relink + navigation can't be interrupted halfway.
// handleSplit calls onClose() directly once it's done.
const guardedClose = () => {
if (isSplitting) return;
onClose();
};
const dialogRef = useModalA11y<HTMLDivElement>(isOpen, guardedClose);
// A comma in the name flags a likely phantom artist (issue #396): a
// comma-joined `ARTIST` tag the scanner didn't split. The preview
// fragments let the user confirm this really is several artists and not
// one name that contains a comma ("Tyler, The Creator") before acting.
const splitFragments = useMemo(
() =>
artistName
.split(",")
.map((s) => s.trim())
.filter((s) => s.length > 0),
[artistName],
);
const isSplittable = splitFragments.length >= 2;
const debounceRef = useRef<number | null>(null);
// Monotonic counter so a slow earlier response can't overwrite a
// newer query's results.
const requestIdRef = useRef(0);
// Prefill from the current override state every time the modal opens.
useEffect(() => {
if (!isOpen) return;
let cancelled = false;
// Clear EVERYTHING up-front β including bio + chips β so a different
// artist never flashes the previous one's data while the async read
// is in flight.
/* eslint-disable react-hooks/set-state-in-effect */
setIsLoading(true);
setError(null);
setQuery("");
setResults([]);
setBio("");
setSelected([]);
/* eslint-enable react-hooks/set-state-in-effect */
getArtistOverrides(artistId)
.then((ov) => {
if (cancelled) return;
setBio(ov.custom_bio ?? "");
setSelected(ov.similar);
})
.catch((err) => {
if (cancelled) return;
console.error("[ArtistMetadataEditorModal] load failed", err);
setError(String(err));
})
.finally(() => {
if (!cancelled) setIsLoading(false);
});
return () => {
cancelled = true;
};
}, [isOpen, artistId]);
const selectedIds = useMemo(
() => new Set(selected.map((s) => s.artist_id)),
[selected],
);
// Single source of truth for "don't touch state right now": the
// initial read is in flight (would clobber local edits), or a save /
// split is running (would submit stale state / race the relink).
const isBusy = isLoading || isSaving || isSplitting;
// Debounced library search for the similar-artist autocomplete.
useEffect(() => {
if (!isOpen || isBusy) return;
if (debounceRef.current != null) window.clearTimeout(debounceRef.current);
// Invalidate any in-flight request the instant the query changes β
// bumping here (not inside the timeout) means a response that lands
// during the debounce window fails the `requestId` check and can't
// apply stale hits.
const requestId = ++requestIdRef.current;
const trimmed = query.trim();
if (trimmed.length < 2) {
/* eslint-disable react-hooks/set-state-in-effect */
setResults([]);
setIsSearching(false);
/* eslint-enable react-hooks/set-state-in-effect */
return;
}
debounceRef.current = window.setTimeout(() => {
setIsSearching(true);
// Drop the previous query's hits immediately so stale entries
// aren't shown (or clickable) while the new request is in flight.
setResults([]);
searchArtists(trimmed, null, 8)
.then((res) => {
if (requestId !== requestIdRef.current) return;
// Drop the artist itself + anyone already picked.
setResults(
res.filter((r) => r.id !== artistId && !selectedIds.has(r.id)),
);
})
.catch((err) => {
if (requestId !== requestIdRef.current) return;
console.error("[ArtistMetadataEditorModal] search failed", err);
setResults([]);
})
.finally(() => {
if (requestId !== requestIdRef.current) return;
setIsSearching(false);
});
}, 250);
return () => {
if (debounceRef.current != null) window.clearTimeout(debounceRef.current);
};
}, [query, isOpen, isBusy, artistId, selectedIds]);
const atLimit = selected.length >= MAX_SIMILAR;
const addArtist = (row: ArtistRow) => {
if (isBusy) return;
// Enforce the cap + dedup inside the updater so rapid clicks
// validate against the latest `prev`, not a render-stale snapshot.
setSelected((prev) => {
if (
prev.length >= MAX_SIMILAR ||
prev.some((s) => s.artist_id === row.id)
) {
return prev;
}
return [
...prev,
{
artist_id: row.id,
name: row.name,
picture_url: row.picture_url,
picture_path: row.picture_path,
},
];
});
setQuery("");
setResults([]);
};
const removeArtist = (id: number) => {
if (isBusy) return;
setSelected((prev) => prev.filter((s) => s.artist_id !== id));
};
const handleSplit = async () => {
if (isBusy) return;
setIsSplitting(true);
setError(null);
try {
const res = await splitArtist(artistId);
// The phantom page is gone; hand the caller the new primary so it
// can navigate there instead of rendering a dead artist id.
onSplit?.(res.artists[0]?.id ?? null);
onClose();
} catch (err) {
console.error("[ArtistMetadataEditorModal] split failed", err);
setError(String(err));
} finally {
setIsSplitting(false);
}
};
const handleSave = async () => {
// Block while loading / saving / splitting β a save mid-split would
// race the relink transaction and submit against stale state.
if (isBusy) return;
setIsSaving(true);
setError(null);
try {
const trimmedBio = bio.trim();
// One transactional write so bio + similar can't half-apply.
await setArtistMetadataOverrides(
artistId,
trimmedBio.length ? trimmedBio : null,
selected.length ? selected.map((s) => s.artist_id) : null,
);
onSuccess();
onClose();
} catch (err) {
console.error("[ArtistMetadataEditorModal] save failed", err);
setError(String(err));
} finally {
setIsSaving(false);
}
};
return (
<AnimatedModalShell isOpen={isOpen} onBackdropClick={guardedClose}>
<AnimatedModalContent
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-labelledby="artist-metadata-editor-title"
className="relative w-full max-w-2xl rounded-3xl border border-zinc-200 bg-white p-6 shadow-2xl dark:border-zinc-800 dark:bg-surface-dark-elevated max-h-[90vh] overflow-hidden flex flex-col"
>
<h2
id="artist-metadata-editor-title"
className="text-lg font-bold text-zinc-900 dark:text-white mb-1"
>
{t("artistMetadataEditor.title")}
</h2>
<p className="text-xs text-zinc-500 dark:text-zinc-400 mb-4">
{t("artistMetadataEditor.subtitle", { name: artistName })}
</p>
{error && <div className="mb-3 text-xs text-red-500 px-1">{error}</div>}
<div className="flex-1 overflow-y-auto space-y-6 pr-1">
{/* Split phantom artist (issue #396) β only when the name looks
comma-joined. User confirms via the fragment preview. */}
{isSplittable && (
<section className="space-y-2 rounded-xl border border-amber-200 bg-amber-50/60 p-3 dark:border-amber-900/40 dark:bg-amber-900/10">
<div className="flex items-center gap-2 text-sm font-semibold text-amber-800 dark:text-amber-300">
<Split size={15} />
{t("artistMetadataEditor.split.label")}
</div>
<p className="text-xs text-amber-700/90 dark:text-amber-200/70">
{t("artistMetadataEditor.split.help")}
</p>
<ul className="flex flex-wrap gap-1.5">
{splitFragments.map((frag, i) => (
<li
key={`${frag}-${i}`}
className="rounded-full bg-white px-2.5 py-1 text-xs font-medium text-zinc-700 shadow-sm dark:bg-zinc-800 dark:text-zinc-200"
>
{frag}
</li>
))}
</ul>
<button
type="button"
onClick={handleSplit}
disabled={isBusy}
className="mt-1 inline-flex items-center gap-2 rounded-lg bg-amber-500 px-3 py-1.5 text-xs font-semibold text-white shadow-sm transition-colors hover:bg-amber-600 disabled:cursor-not-allowed disabled:opacity-50"
>
{isSplitting ? (
<Loader2 size={13} className="animate-spin" />
) : (
<Split size={13} />
)}
<span>{t("artistMetadataEditor.split.action")}</span>
</button>
</section>
)}
{/* Bio override */}
<section className="space-y-2">
<div className="flex items-center justify-between">
<label
htmlFor="artist-bio-override"
className="text-sm font-semibold text-zinc-800 dark:text-zinc-200"
>
{t("artistMetadataEditor.bio.label")}
</label>
{bio.trim().length > 0 && !isBusy && (
<button
type="button"
onClick={() => setBio("")}
className="text-xs font-medium text-emerald-600 dark:text-emerald-400 hover:underline"
>
{t("artistMetadataEditor.bio.reset")}
</button>
)}
</div>
<textarea
id="artist-bio-override"
value={bio}
onChange={(e) => setBio(e.target.value)}
rows={5}
disabled={isBusy}
placeholder={t("artistMetadataEditor.bio.placeholder")}
className="w-full px-3 py-2.5 rounded-xl bg-zinc-50 dark:bg-zinc-800/50 border border-zinc-200 dark:border-zinc-700 text-sm text-zinc-900 dark:text-white placeholder:text-zinc-400 dark:placeholder:text-zinc-500 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-transparent resize-y disabled:opacity-50"
/>
<p className="text-xs text-zinc-400">
{t("artistMetadataEditor.bio.help")}
</p>
</section>
{/* Similar override */}
<section className="space-y-2">
<label
htmlFor="artist-similar-search"
className="text-sm font-semibold text-zinc-800 dark:text-zinc-200"
>
{t("artistMetadataEditor.similar.label")}
</label>
{/* Selected chips */}
{selected.length > 0 && (
<ul className="flex flex-wrap gap-2">
{selected.map((s) => {
const img = resolveRemoteImage(s.picture_path, s.picture_url);
return (
<li key={s.artist_id}>
<span className="inline-flex items-center gap-2 pl-1 pr-2 py-1 rounded-full bg-zinc-100 dark:bg-zinc-800 text-sm text-zinc-800 dark:text-zinc-200">
{img ? (
<img
src={img}
alt=""
className="w-6 h-6 rounded-full object-cover"
/>
) : (
<span className="w-6 h-6 rounded-full bg-zinc-200 dark:bg-zinc-700 flex items-center justify-center text-zinc-400">
<User size={12} />
</span>
)}
<span className="truncate max-w-48">{s.name}</span>
<button
type="button"
onClick={() => removeArtist(s.artist_id)}
disabled={isBusy}
aria-label={t("artistMetadataEditor.similar.remove", {
name: s.name,
})}
className="text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200 disabled:opacity-50"
>
<X size={14} />
</button>
</span>
</li>
);
})}
</ul>
)}
{/* Autocomplete input */}
<div className="relative">
<Search
size={16}
className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-400"
/>
<input
id="artist-similar-search"
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
disabled={isBusy || atLimit}
placeholder={t("artistMetadataEditor.similar.placeholder")}
className="w-full pl-9 pr-9 py-2.5 rounded-xl bg-zinc-50 dark:bg-zinc-800/50 border border-zinc-200 dark:border-zinc-700 text-sm text-zinc-900 dark:text-white placeholder:text-zinc-400 dark:placeholder:text-zinc-500 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-transparent disabled:opacity-50"
/>
{isSearching && (
<Loader2
size={16}
className="absolute right-3 top-1/2 -translate-y-1/2 text-zinc-400 animate-spin"
/>
)}
</div>
{atLimit && (
<p className="text-xs text-amber-600 dark:text-amber-400">
{t("artistMetadataEditor.similar.limitReached", {
max: MAX_SIMILAR,
})}
</p>
)}
{/* Results β plain list of action buttons (not a listbox: no
roving focus / active-option semantics implemented). */}
{!isBusy && !atLimit && results.length > 0 && (
<ul className="max-h-56 overflow-y-auto rounded-xl border border-zinc-200 dark:border-zinc-700 divide-y divide-zinc-100 dark:divide-zinc-800">
{results.map((r) => {
const img = resolveRemoteImage(r.picture_path, r.picture_url);
return (
<li key={r.id}>
<button
type="button"
onClick={() => addArtist(r)}
className="flex w-full items-center gap-3 px-3 py-2 text-left hover:bg-zinc-50 dark:hover:bg-zinc-800/40 transition-colors"
>
{img ? (
<img
src={img}
alt=""
className="w-8 h-8 rounded-full object-cover shrink-0"
/>
) : (
<span className="w-8 h-8 rounded-full bg-zinc-100 dark:bg-zinc-800 flex items-center justify-center text-zinc-400 shrink-0">
<User size={14} />
</span>
)}
<span className="min-w-0">
<span className="block text-sm text-zinc-800 dark:text-zinc-200 truncate">
{r.name}
</span>
<span className="block text-xs text-zinc-400">
{t("artistDetail.trackCount", {
count: r.track_count,
})}
</span>
</span>
</button>
</li>
);
})}
</ul>
)}
<p className="text-xs text-zinc-400">
{t("artistMetadataEditor.similar.help")}
</p>
</section>
</div>
{/* Footer */}
<div className="mt-4 flex items-center justify-end gap-2 pt-3 border-t border-zinc-100 dark:border-zinc-800">
<button
type="button"
onClick={guardedClose}
disabled={isSplitting}
className="px-4 py-2 rounded-xl text-sm font-medium text-zinc-500 hover:text-zinc-800 dark:text-zinc-400 dark:hover:text-zinc-200 transition-colors disabled:opacity-50"
>
{t("common.cancel")}
</button>
<button
type="button"
onClick={handleSave}
disabled={isBusy}
className="bg-emerald-500 hover:bg-emerald-600 text-white px-5 py-2 rounded-xl text-sm font-semibold flex items-center gap-2 transition-colors shadow-sm disabled:opacity-50 disabled:cursor-not-allowed"
>
{isSaving && <Loader2 size={14} className="animate-spin" />}
<span>{t("common.save")}</span>
</button>
</div>
</AnimatedModalContent>
</AnimatedModalShell>
);
}