1import { useState, type CSSProperties } from "react";2import { useTranslation } from "react-i18next";3import { Loader2, X } from "lucide-react";4import { CoverArtThumbnail } from "@/components/Shared/CoverArtThumbnail";5import { useBootstrapStore } from
"@/stores/bootstrap-store"
;
6import { useLibraryStore } from "@/stores/library-store";
7import { usePlayerStore } from "@/stores/player-store";
8import { useLyricsStore } from "@/stores/lyrics-store";
9import { useSettingsStore } from "@/stores/settings-store";
10import { useQueueStore } from "@/stores/queue-store";
11import { usePlaylistStore } from "@/stores/playlist-store";
12import { formatDuration } from "@/lib/format";
13import { TaskProgressBar } from "@/components/Layout/GlobalProgressBar";
14import { songCanBeSeparated } from "@/lib/song-media";
15import * as api from "@/lib/tauri";
16import { notifyError, notifySuccess } from "@/lib/errors";
17import { showNativeContextMenu } from "@/lib/native-context-menu";
18import { ConfirmationDialog } from "../Settings/ConfirmationDialog";
19import { InputDialog } from "../Settings/InputDialog";
20import { SongEditDialog } from "./SongEditDialog";
21import { SongPropertiesDialog } from "./SongPropertiesDialog";
22import {
23 buildSongListContextMenuForSong,
24 getSongListContextSongIds,
25} from "./song-list-item-context-menu-build";
26import { songDisplayTitle } from "@/lib/song-display";
27import type { Song } from "@/types/ipc";
28
29interface SongListItemProps {
30 song: Song;
31 orderedHashes: string[];
32}
33
34export function SongListItem({ song, orderedHashes }: SongListItemProps) {
35 const { t } = useTranslation();
36 const isSelected = useLibraryStore((s) => s.selectedSongIds.has(song.hash));
37 const selectSong = useLibraryStore((s) => s.selectSong);
38 const separationStatus = useLibraryStore(
39 (s) => s.separationStatuses[song.hash],
40 );
41 const uploadStatus = useLibraryStore((s) => s.uploadStatuses[song.hash]);
42 const batchActive = useLibraryStore((s) => {
43 const batch = s.batchSeparation;
44 if (batch == null) return false;
45 return batch.completed + batch.failed < batch.total;
46 });
47 const createPlaylist = usePlaylistStore((s) => s.createPlaylist);
48 const addSongsToPlaylist = usePlaylistStore((s) => s.addSongsToPlaylist);
49 const playSong = usePlayerStore((s) => s.playSong);
50 const closeSettings = useSettingsStore((s) => s.close);
51
52 const [editDialogOpen, setEditDialogOpen] = useState(false);
53 const [propertiesDialogOpen, setPropertiesDialogOpen] = useState(false);
54 const [deleteSongIds, setDeleteSongIds] = useState<string[] | null>(null);
55 const [isDeleting, setIsDeleting] = useState(false);
56 const [playlistDialogOpen, setPlaylistDialogOpen] = useState(false);
57
58 const isCurrentPlaying = usePlayerStore(
59 (s) => s.snapshot?.song_id === song.hash && !!s.snapshot?.is_playing,
60 );
61 const isCurrentLoading = usePlayerStore(
62 (s) => s.snapshot?.song_id === song.hash && s.snapshot?.state === "loading",
63 );
64 const sepState = separationStatus?.state ?? "idle";
65 const uploadRunning = uploadStatus?.state === "running";
66 const showBatchSongProgress = batchActive && sepState === "running";
67 const isMediaG = song.media_g_container != null;
68 const canSeparateSong = songCanBeSeparated(song);
69 const modelPreparing = useBootstrapStore(
70 (s) => s.status?.state === "pending" || s.status?.state === "downloading",
71 );
72 const mediaGBadgeLabel =
73 song.media_g_container === "paired"
74 ? "CDG"
75 : song.media_g_container === "zip"
76 ? "ZIP+G"
77 : null;
78
79 const handlePlay = () => {
80 const current = usePlayerStore.getState().snapshot;
81 if (current?.song_id && current.song_id !== song.hash) {
82 useQueueStore.getState().addToQueue(song.hash);
83 } else {
84 playSong(song.hash);
85 }
86 closeSettings();
87 };
88
89 const selectSongFromEvent = (event: React.MouseEvent<HTMLButtonElement>) => {
90 selectSong(
91 song.hash,
92 {
93 shiftKey: event.shiftKey,
94 metaKey: event.metaKey,
95 ctrlKey: event.ctrlKey,
96 },
97 orderedHashes,
98 );
99 };
100
101 const handleSeparate = (e: React.MouseEvent) => {
102 e.stopPropagation();
103 api.separate(song.hash).catch((err) => notifyError(err));
104 };
105
106 const handleCancelSeparation = (e: React.MouseEvent) => {
107 e.stopPropagation();
108 api.cancelSeparation(song.hash).catch((err) => notifyError(err));
109 };
110
111 const handleDeleteSongs = async (songIds: string[]) => {
112 setIsDeleting(true);
113 try {
114 const result = await api.deleteSongs(songIds);
115 for (const failure of result.failed) {
116 notifyError(failure.error);
117 }
118
119 if (result.deleted_song_ids.length > 0) {
120 useQueueStore.getState().removeSongIds(result.deleted_song_ids);
121 useLibraryStore.setState((state) => ({
122 selectedSongIds: new Set(
123 [...state.selectedSongIds].filter(
124 (id) => !result.deleted_song_ids.includes(id),
125 ),
126 ),
127 lastClickedSongId: result.deleted_song_ids.includes(
128 state.lastClickedSongId ?? "",
129 )
130 ? null
131 : state.lastClickedSongId,
132 separationStatuses: Object.fromEntries(
133 Object.entries(state.separationStatuses).filter(
134 ([id]) => !result.deleted_song_ids.includes(id),
135 ),
136 ),
137 uploadStatuses: Object.fromEntries(
138 Object.entries(state.uploadStatuses).filter(
139 ([id]) => !result.deleted_song_ids.includes(id),
140 ),
141 ),
142 }));
143 await useLibraryStore.getState().loadLibrary();
144 await usePlayerStore.getState().loadState();
145 const lyricsStore = useLyricsStore.getState();
146 if (
147 lyricsStore.songId &&
148 result.deleted_song_ids.includes(lyricsStore.songId)
149 ) {
150 lyricsStore.clear();
151 }
152 }
153 } catch (error) {
154 notifyError(error);
155 } finally {
156 setIsDeleting(false);
157 setDeleteSongIds(null);
158 }
159 };
160
161 const openContextMenu = (clientX: number, clientY: number) => {
162 if (!isSelected) {
163 selectSong(
164 song.hash,
165 { shiftKey: false, metaKey: false, ctrlKey: false },
166 orderedHashes,
167 );
168 }
169 const items = buildSongListContextMenuForSong(
170 song,
171 (key, options) => String(t(key as never, options as never)),
172 {
173 setEditDialogOpen,
174 setPropertiesDialogOpen,
175 setDeleteSongIds,
176 setPlaylistDialogOpen,
177 },
178 );
179 void showNativeContextMenu(items, clientX, clientY);
180 };
181
182 const handleContextMenu = (event: React.MouseEvent<HTMLButtonElement>) => {
183 event.preventDefault();
184 openContextMenu(event.clientX, event.clientY);
185 };
186
187 const handleSelectionKeyDown = (
188 event: React.KeyboardEvent<HTMLButtonElement>,
189 ) => {
190 if (event.key === "Enter") {
191 event.preventDefault();
192 handlePlay();
193 return;
194 }
195
196 if (
197 event.key === "ContextMenu" ||
198 (event.shiftKey && event.key === "F10")
199 ) {
200 event.preventDefault();
201 const rect = event.currentTarget.getBoundingClientRect();
202 openContextMenu(rect.left + rect.width / 2, rect.top + rect.height / 2);
203 }
204 };
205
206 return (
207 <div
208 className={`group relative flex select-none items-center gap-2.5 rounded-[14px] border px-3 py-2.5 transition-colors duration-150 ${
209 isSelected
210 ? "border-[var(--sidebar-row-selected-border)] bg-[var(--sidebar-row-selected-bg)] text-[var(--color-text)]"
211 : "border-transparent text-[var(--color-text)] hover:bg-[var(--sidebar-row-overlay-bg)]"
212 }`}
213 data-native-overlay-surface="song-row"
214 data-song-list-item-variant="unified"
215 data-song-hash={song.hash}
216 data-selected={isSelected ? "true" : "false"}
217 style={
218 showBatchSongProgress
219 ? undefined
220 : ({
221 contentVisibility: "auto",
222 containIntrinsicSize: "64px",
223 } satisfies CSSProperties)
224 }
225 >
226 <button
227 type="button"
228 onClick={selectSongFromEvent}
229 onDoubleClick={handlePlay}
230 onContextMenu={handleContextMenu}
231 onKeyDown={handleSelectionKeyDown}
232 aria-label={songDisplayTitle(song)}
233 aria-pressed={isSelected}
234 className="absolute inset-0 z-0 cursor-pointer rounded-[14px] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-focus-ring)]"
235 data-song-action="select"
236 />
237
238 <CoverArtThumbnail
239 songHash={song.hash}
240 coverArt={song.cover_art}
241 thumbnailPath={song.artwork_thumb_path}
242 alt={`${songDisplayTitle(song)} cover art`}
243 className="pointer-events-none h-11 w-11 shrink-0"
244 />
245
246 <div className="relative z-10 pointer-events-none flex min-w-0 flex-1 flex-col justify-center">
247 <div className="flex items-center justify-between gap-3">
248 <div className="flex min-w-0 items-center gap-2 overflow-hidden">
249 {isCurrentPlaying ? (
250 <div className="flex w-3 shrink-0 justify-center">
251 <span className="inline-flex h-2 w-2 rounded-full bg-[var(--color-accent)]" />
252 </div>
253 ) : isCurrentLoading ? (
254 <div className="flex w-3 shrink-0 justify-center">
255 <Loader2 size={10} className="animate-spin" />
256 </div>
257 ) : (
258 <div className="w-3 shrink-0" />
259 )}
260 <span className="truncate text-[15px] font-semibold">
261 {songDisplayTitle(song)}
262 </span>
263 </div>
264
265 <div className="flex shrink-0 items-center gap-2">
266 {mediaGBadgeLabel && (
267 <span className="inline-flex h-[14px] items-center justify-center rounded bg-[var(--sidebar-row-overlay-bg)] px-1.5 text-[9px] font-semibold leading-none tracking-[0.08em] text-[var(--color-text-dim)]">
268 {mediaGBadgeLabel}
269 </span>
270 )}
271 {sepState === "idle" && canSeparateSong && (
272 <button
273 type="button"
274 onClick={handleSeparate}
275 disabled={modelPreparing}
276 title={modelPreparing ? t("library.modelPreparing") : undefined}
277 className={`pointer-events-auto min-h-[24px] min-w-[24px] rounded border px-1.5 py-0.5 text-[10px] disabled:cursor-default disabled:opacity-50 ${
278 isSelected
279 ? "border-[var(--sidebar-control-border)] bg-[var(--sidebar-control-bg)] text-[var(--color-text)] hover:bg-[var(--sidebar-row-overlay-bg)]"
280 : "border-[var(--sidebar-control-border)] bg-[var(--sidebar-control-bg)] text-[var(--color-text-dim)] hover:bg-[var(--sidebar-row-overlay-bg)]"
281 }`}
282 data-native-overlay-surface="song-action"
283 >
284 {t("library.separate")}
285 </button>
286 )}
287 {sepState === "running" && (
288 <div className="flex items-center gap-1 text-[11px] text-[var(--color-text-dim)]">
289 <Loader2 size={10} className="animate-spin" />
290 <span>{separationStatus?.percent ?? 0}%</span>
291 {!batchActive && (
292 <button
293 type="button"
294 onClick={handleCancelSeparation}
295 title={t("library.cancelSeparation")}
296 aria-label={t("library.cancelSeparation")}
297 className="pointer-events-auto inline-flex min-h-[24px] min-w-[24px] items-center justify-center motion-icon-button rounded p-0.5 text-[var(--color-text-dim)] hover:bg-[var(--sidebar-row-overlay-bg)] hover:text-[var(--color-text)]"
298 data-native-overlay-surface="song-action"
299 >
300 <X size={12} />
301 </button>
302 )}
303 </div>
304 )}
305 {uploadRunning && sepState !== "running" && (
306 <div className="flex items-center gap-1 text-[11px] text-[var(--color-text-dim)]">
307 <Loader2 size={10} className="animate-spin" />
308 <span>{uploadStatus?.percent ?? 0}%</span>
309 </div>
310 )}
311 {sepState === "completed" && (
312 <span className="flex items-center gap-1.5 text-[11px] text-[var(--color-text-dim)]">
313 <span
314 className={`inline-flex h-[14px] min-w-[14px] items-center justify-center rounded text-[9px] font-semibold leading-none ${
315 separationStatus?.drums_path
316 ? "bg-[var(--sidebar-row-overlay-bg)] text-[var(--color-accent)]"
317 : "bg-[var(--sidebar-row-overlay-bg)] text-[var(--color-text-dim)]"
318 }`}
319 >
320 {separationStatus?.drums_path ? "4" : "2"}
321 </span>
322 {formatDuration(song.duration_ms)}
323 </span>
324 )}
325 {sepState === "failed" && canSeparateSong && (
326 <button
327 type="button"
328 onClick={handleSeparate}
329 className="pointer-events-auto min-h-[24px] min-w-[24px] text-[10px] text-[var(--color-destructive)]"
330 >
331 {t("common.retry")}
332 </button>
333 )}
334 {(isMediaG ||
335 !canSeparateSong ||
336 (sepState !== "idle" &&
337 sepState !== "running" &&
338 sepState !== "completed" &&
339 sepState !== "failed")) && (
340 <span className="text-[11px] text-[var(--color-text-dim)]">
341 {formatDuration(song.duration_ms)}
342 </span>
343 )}
344 </div>
345 </div>
346
347 {showBatchSongProgress && (
348 <div className="mt-1.5 pl-5">
349 <TaskProgressBar
350 compact
351 label=""
352 percent={separationStatus?.percent ?? 0}
353 ariaLabel={t("progress.separating", {
354 title: songDisplayTitle(song),
355 defaultValue: `Separating: ${songDisplayTitle(song)}`,
356 })}
357 />
358 </div>
359 )}
360
361 <div className="flex pl-5">
362 <span className="truncate text-[12px] text-[var(--color-text-dim)]">
363 {song.artist || t("common.unknownArtist")}
364 </span>
365 </div>
366 </div>
367
368 {editDialogOpen && (
369 <SongEditDialog song={song} onClose={() => setEditDialogOpen(false)} />
370 )}
371
372 {propertiesDialogOpen && (
373 <SongPropertiesDialog
374 song={song}
375 onClose={() => setPropertiesDialogOpen(false)}
376 />
377 )}
378
379 {playlistDialogOpen && (
380 <InputDialog
381 title={t("playlist.create")}
382 placeholder={t("playlist.name")}
383 confirmLabel={t("common.save")}
384 onConfirm={async (name) => {
385 setPlaylistDialogOpen(false);
386 const contextSongIds = getSongListContextSongIds(song);
387 try {
388 const playlist = await createPlaylist(name.trim());
389 await addSongsToPlaylist(playlist.id, contextSongIds);
390 notifySuccess(
391 t("playlist.createdAndAddedToast", {
392 count: contextSongIds.length,
393 }),
394 );
395 } catch (error) {
396 notifyError(error);
397 }
398 }}
399 onCancel={() => setPlaylistDialogOpen(false)}
400 />
401 )}
402
403 {deleteSongIds && (
404 <ConfirmationDialog
405 title={t("library.confirmDeleteTitle", {
406 count: deleteSongIds.length,
407 })}
408 message={t("library.confirmDeleteMessage", {
409 count: deleteSongIds.length,
410 })}
411 confirmLabel={
412 isDeleting ? t("common.deleting") : t("library.deleteConfirm")
413 }
414 onCancel={() => {
415 if (!isDeleting) {
416 setDeleteSongIds(null);
417 }
418 }}
419 onConfirm={() => {
420 if (!isDeleting) {
421 void handleDeleteSongs(deleteSongIds);
422 }
423 }}
424 />
425 )}
426 </div>
427 );
428}
429