Repository navigation
Expand file tree
/
Copy pathLibraryView.tsx
More file actions
4945 lines (4808 loc) Β· 192 KB
/
Copy pathLibraryView.tsx
File metadata and controls
4945 lines (4808 loc) Β· 192 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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { PlaylistGrid } from "./library/PlaylistGrid";
import { InventoryCategories } from "./library/InventoryCategories";
import { PhantomArtistList } from "./library/PhantomArtistList";
import { TrackTableHeader } from "./library/TrackTableHeader";
import { ColumnPicker } from "./library/ColumnPicker";
import { useTrackColumns } from "../../hooks/useTrackColumns";
import {
listTrackTagKeys,
listTrackTagValues,
} from "../../lib/tauri/trackTags";
import {
cellText,
MAX_COLUMN_WIDTH,
specFor,
tagKeyOf,
fitLayoutToWidth,
trackMinWidthFor,
trackSizeFor,
type ColumnId,
type ColumnLayout,
} from "../../lib/trackColumns";
import { formatMusicalKey } from "../../lib/musicalKey";
import { fitWidth, styleOf } from "../../lib/measureText";
import {
inventorySummary,
inventoryTracks,
type InventoryCategory,
} from "../../lib/tauri/inventory";
import { useLibraryPlaylists } from "../../hooks/useLibraryPlaylists";
import { useVirtualizer } from "@tanstack/react-virtual";
import {
Music2,
Disc,
Mic2,
Tags,
CalendarDays,
Folder,
AlertTriangle,
RefreshCcw,
FileSearch,
ListMusic,
LayoutList,
AlignJustify,
Plus,
Heart,
Eye,
EyeOff,
Trash2,
ImageIcon,
ArrowUpDown,
ArrowDown,
ArrowUp,
Check,
Download,
FolderDown,
Pencil,
ChevronRight,
CornerLeftUp,
LayoutGrid,
Play,
ListEnd,
TagsIcon,
Loader2,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import type { LibraryTab } from "../../types";
import { Tab } from "../common/Tab";
import { RemoteArtwork } from "../common/RemoteArtwork";
import { remotePlayTracks } from "../../lib/tauri/remoteServer";
import { useRemoteArtworkSrc } from "../../hooks/useRemoteArtworkSrc";
import { useRemoteSource } from "../../hooks/useRemoteSource";
import {
useLibrarySource,
type LibrarySourceFilter,
} from "../../hooks/useLibrarySource";
import { EmptyState } from "../common/EmptyState";
import { Artwork } from "../common/Artwork";
import { AlbumLink } from "../common/AlbumLink";
import { ArtistLink } from "../common/ArtistLink";
import { HiResBadge } from "../common/HiResBadge";
import { PlayingIndicator } from "../common/PlayingIndicator";
import { Tooltip } from "../common/Tooltip";
import { CreatePlaylistModal } from "../common/CreatePlaylistModal";
import { CoverPickerModal } from "../common/CoverPickerModal";
import {
remoteDownloadTrack,
remoteListDownloads,
} from "../../lib/tauri/remoteServer";
import { ImportToLibraryModal } from "../common/ImportToLibraryModal";
import { RemoteTrackTagsModal } from "../common/RemoteTrackTagsModal";
import { StarRating } from "../common/StarRating";
import { SelectionActionBar } from "../common/SelectionActionBar";
import { AlphabetIndex } from "../common/AlphabetIndex";
import { useSortIgnoreArticles } from "../../hooks/useSortIgnoreArticles";
import { useSortMemory } from "../../hooks/useSortMemory";
import { usePageScroll } from "../../hooks/usePageScroll";
import {
isPlayClick,
useSingleClickPlay,
} from "../../hooks/useSingleClickPlay";
import { useLibrary } from "../../hooks/useLibrary";
import { usePlayer } from "../../hooks/usePlayer";
import { usePlaylist } from "../../hooks/usePlaylist";
import { useTrackContextMenu } from "../../hooks/useTrackContextMenu";
import { useRemoteTrackContextMenu } from "../../hooks/useRemoteTrackContextMenu";
import { useTrackUpdated } from "../../hooks/useTrackUpdated";
import { useArtistUpdated } from "../../hooks/useArtistUpdated";
import { useMultiSelect } from "../../hooks/useMultiSelect";
import { useSelectAllShortcut } from "../../hooks/useSelectAllShortcut";
import { RowSelectCheckbox } from "../common/RowSelectCheckbox";
import { resolvePlaylistColor } from "../../lib/playlistVisuals";
import { resolveArtwork } from "../../lib/tauri/artwork";
import { FadeInImage } from "../common/FadeInImage";
import { PlaylistIcon } from "../../lib/PlaylistIcon";
import {
listPlaylistsContainingTrack,
type Playlist,
} from "../../lib/tauri/playlist";
import { pickFolder } from "../../lib/tauri/dialog";
import {
removeFolderFromLibrary,
countFolderPlayEvents,
setFolderWatched,
scanFolder,
} from "../../lib/tauri/library";
import {
formatDuration,
listLikedTrackIds,
setTrackRating,
toggleLikeTrack,
type Track,
} from "../../lib/tauri/track";
import {
browseFolders,
listFolderTracks,
folderTrackIds,
type FolderListing,
type FolderNode,
listGenres,
listYears,
type YearRow,
listFolders,
type LibraryAlbumRow,
type LibraryArtistRow,
type LibraryTrackRow,
listLibraryAlbums,
listLibraryArtists,
listLibraryTracks,
type GenreRow,
type FolderRow,
} from "../../lib/tauri/browse";
import { useCreatePlaylistFromModal } from "../../hooks/useCreatePlaylistFromModal";
import { BatchTagEditModal } from "../common/BatchTagEditModal";
import { MenuActionItem } from "../common/MenuActionItem";
import { playerAddToQueue, playerPlayNext } from "../../lib/tauri/player";
import { formatBytes } from "../../lib/format";
/** View density for the tracks list: `list` shows cover art, `compact` doesn't. */
type TracksView = "list" | "compact";
interface LibraryViewProps {
activeTab: LibraryTab;
setActiveTab: (tab: LibraryTab) => void;
onNavigateToAlbum: (albumId: number) => void;
/** A server album opens the remote detail view; the two catalogues are
* never merged, so they are never the same page. */
onNavigateToRemoteAlbum: (remoteAlbumId: string) => void;
onNavigateToRemoteArtist: (remoteArtistId: string) => void;
onNavigateToRemotePlaylist: (remotePlaylistId: string) => void;
onNavigateToArtist: (artistId: number) => void;
onNavigateToGenre: (genreId: number) => void;
/** `null` opens the tracks with no usable year. */
onNavigateToYear: (year: number | null) => void;
onNavigateToPlaylist: (playlistId: number) => void;
}
type Translator = (key: string, options?: Record<string, unknown>) => string;
const tabConfig: { id: LibraryTab; icon: typeof Music2 }[] = [
{ id: "tracks", icon: Music2 },
{ id: "albums", icon: Disc },
{ id: "artists", icon: Mic2 },
{ id: "genres", icon: Tags },
{ id: "years", icon: CalendarDays },
{ id: "playlists", icon: ListMusic },
{ id: "folders", icon: Folder },
{ id: "needs-attention", icon: AlertTriangle },
];
const emptyStateIcons: Record<LibraryTab, typeof Music2> = {
tracks: Music2,
albums: Disc,
artists: Mic2,
genres: Tags,
years: CalendarDays,
playlists: ListMusic,
folders: Folder,
"needs-attention": AlertTriangle,
};
const headerIcons: Record<LibraryTab, typeof Music2> = {
tracks: Music2,
albums: Disc,
artists: Mic2,
genres: Tags,
years: CalendarDays,
playlists: ListMusic,
folders: Folder,
"needs-attention": AlertTriangle,
};
export function LibraryView({
activeTab,
setActiveTab,
onNavigateToAlbum,
onNavigateToRemoteAlbum,
onNavigateToArtist,
onNavigateToRemoteArtist,
onNavigateToRemotePlaylist,
onNavigateToGenre,
onNavigateToYear,
onNavigateToPlaylist,
}: LibraryViewProps) {
const { t, i18n } = useTranslation();
const createFromModal = useCreatePlaylistFromModal();
const {
libraries,
selectedLibraryId,
selectLibrary,
createLibrary,
importFolder,
rescanLibrary,
refresh: refreshLibraries,
} = useLibrary();
const { playTracks, currentTrack, isPlaying } = usePlayer();
const {
playlists,
addTracksToPlaylist,
removeTrackFromPlaylist,
addSourceToPlaylist,
} = usePlaylist();
const [isImporting, setIsImporting] = useState(false);
const [isRescanning, setIsRescanning] = useState(false);
// Separate from `isRescanning` so the two buttons disable each other
// without either claiming the other's spinner.
const [isDeepRescanning, setIsDeepRescanning] = useState(false);
// Which folder a deep rescan (issue #366) is currently running against,
// if any β drives the spinner on that row's action only, since it's a
// per-folder action rather than the global "Rescan" button above.
const [deepRescanFolderId, setDeepRescanFolderId] = useState<number | null>(
null,
);
// Any scan in flight, whichever control started it. `scan_folder_inner`
// is a writer and SQLite takes one writer at a time, so a folder-level
// deep pass and a library-wide one must not overlap β before this, the
// global buttons only guarded against each other and left the
// per-folder button free to start a second concurrent scan.
const isAnyRescanActive =
isRescanning || isDeepRescanning || deepRescanFolderId != null;
// Server tracks queued for an import, and what to call them in the modal's
// heading. `null` closes it.
const [importTargets, setImportTargets] = useState<{
ids: string[];
label: string;
} | null>(null);
// Server track whose tag editor is open, by its server identifier.
const [remoteTagsTrackId, setRemoteTagsTrackId] = useState<string | null>(
null,
);
const [downloadingRemote, setDownloadingRemote] = useState<Set<string>>(
() => new Set(),
);
const [downloadedRemote, setDownloadedRemote] = useState<Set<string>>(
() => new Set(),
);
const [isCreatePlaylistModalOpen, setIsCreatePlaylistModalOpen] =
useState(false);
// When the create-playlist modal is opened from a popover's "+ New
// playlist" entry, remember which source triggered it so we can add
// its tracks to the freshly created playlist in one step instead of
// forcing the user to reopen the popover.
const [pendingSourceForCreate, setPendingSourceForCreate] = useState<
| { kind: "tracks"; ids: number[] }
| { kind: "folder" | "album" | "artist"; id: number }
| null
>(null);
const [coverPickerAlbumId, setCoverPickerAlbumId] = useState<number | null>(
null,
);
const [coverReloadKey, setCoverReloadKey] = useState(0);
const [tracks, setTracks] = useState<LibraryTrackRow[]>([]);
const [albums, setAlbums] = useState<LibraryAlbumRow[]>([]);
const librarySource = useLibrarySource();
const [artists, setArtists] = useState<LibraryArtistRow[]>([]);
const [genres, setGenres] = useState<GenreRow[]>([]);
const [years, setYears] = useState<YearRow[]>([]);
const [folders, setFolders] = useState<FolderRow[]>([]);
// Folder browsing (#578). `null` is the list of configured roots β
// the tab's original content, which stays reachable because it is
// also where a root is unwatched or removed.
const [folderPath, setFolderPath] = useState<string | null>(null);
const [folderListing, setFolderListing] = useState<FolderListing | null>(
null,
);
const [folderTracks, setFolderTracks] = useState<LibraryTrackRow[]>([]);
const [folderBusy, setFolderBusy] = useState(false);
/** Folders as covers, or as rows with names and sizes. */
const [folderDensity, setFolderDensity] = useState<"grid" | "list">("grid");
/** Batch tag editor, opened with a whole folder as its scope. */
const [batchTagIds, setBatchTagIds] = useState<number[] | null>(null);
/** Drops a response for a folder the user has already left. Same rule
* as every other keyed fetch here: a stale answer counts as absent,
* not as approximate. */
const folderRequest = useRef(0);
// Per-tab loading state β drives both the in-place dim and the
// first-load skeleton. Independent flags let the 5 fetches run in
// parallel without one tab's dim leaking onto another. Initial value
// is `true` everywhere so the skeleton paints on first render instead
// of a one-frame EmptyState flash before the effects schedule.
const [loading, setLoading] = useState<Record<LibraryTab, boolean>>({
tracks: true,
albums: true,
artists: true,
genres: true,
years: true,
// Playlists come from PlaylistContext, already loaded β there is no
// fetch of our own to wait on, so this tab never shows a skeleton.
playlists: false,
folders: true,
// The only tab that does NOT prefetch. Its counts are album-level
// aggregates plus a walk over every track to chain probable
// duplicates, so paying for them on every mount of the library --
// which is what the six other tabs with a query of their own do --
// would tax people who never open it. That is about the *fetch*,
// not about this flag: `true`, because an inventory nobody has
// asked for yet is an empty list, and an empty list is what
// "nothing to fix" looks like. The first paint would congratulate
// the user before a single count existed.
"needs-attention": true,
});
// Which columns the track table shows, in what order and how wide
// (#588). One preference for every list that renders the shared
// table, so the library, the folder browser and the inventory agree.
const trackColumns = useTrackColumns();
// The width of the column currently being dragged, before it is
// persisted. `useProfileSetting` serializes one database write per
// call, so writing on every pointer move would queue hundreds of
// round trips for a single gesture β this is what the table renders
// from meanwhile, and the commit on release is the only write.
const [columnPreview, setColumnPreview] = useState<{
id: ColumnId;
width: number;
} | null>(null);
// The same value again, in a ref, and both spellings are needed.
//
// The state is what the table renders from. The ref is what the
// commit reads, because neither of the other two ways of reading it
// works: a functional updater would put a database write inside an
// updater React is free to replay, and the render closure would be a
// tick behind for the keyboard, which previews and commits back to
// back with no render in between -- an arrow key would persist the
// width before the one it just asked for.
const columnPreviewRef = useRef<{ id: ColumnId; width: number } | null>(null);
// The layout as it looks right now, preview included. Everything that
// lays the table out reads this, so the header, the rows and the
// resize handle cannot disagree mid-drag.
const liveColumnLayout = useMemo(
() =>
columnPreview
? {
...trackColumns.layout,
widths: {
...trackColumns.layout.widths,
[columnPreview.id]: columnPreview.width,
},
}
: trackColumns.layout,
[trackColumns.layout, columnPreview],
);
// Tag keys the library actually holds, offered in the picker with a
// count each. Read once per library change: it is a GROUP BY over a
// side table, and it only moves when a scan has run.
const [tagKeys, setTagKeys] = useState<{ key: string; count: number }[]>([]);
// Values for the chosen `tag:` columns only. Empty -- and never
// fetched -- while no such column is shown, which is the common case.
const [tagValues, setTagValues] = useState<
Map<string, Record<string, string>>
>(new Map());
// Inventory tab (#589). Three pieces of state rather than one: the
// categories survive a category being opened and closed, so reopening
// one does not re-run the expensive summary.
const [inventory, setInventory] = useState<InventoryCategory[]>([]);
const [inventoryCategory, setInventoryCategory] = useState<string | null>(
null,
);
const [inventoryRows, setInventoryRows] = useState<LibraryTrackRow[]>([]);
const [inventoryBusy, setInventoryBusy] = useState(false);
const [tracksView, setTracksView] = useState<TracksView>("list");
const [likedIds, setLikedIds] = useState<Set<number>>(new Set());
const selection = useMultiSelect<Track>();
const EmptyIcon = emptyStateIcons[activeTab];
const HeaderIcon = headerIcons[activeTab];
// Sort memory per tab β restored from `profile_setting['sort.<ctx>']`
// and persisted on every change. The lists wait for `isLoaded` before
// their first fetch so we don't query twice on mount.
const tracksSort = useSortMemory("tracks", {
orderBy: "title",
direction: "asc",
});
// Smart playlists (Daily Mix, On Repeat) live in Home's "Made for
// you" carousel; this tab is the user's own playlists, which is what
// issue #461 asked for ("the ones we make").
const userPlaylists = useMemo(
() => playlists.filter((p) => p.is_smart === 0),
[playlists],
);
// Persisted like every other tab's sort. Default `custom` = the
// sidebar's manual order, so the grid opens in the arrangement the
// user already curated there.
const playlistsSort = useSortMemory("playlists", {
orderBy: "custom",
direction: "asc",
});
const albumsSort = useSortMemory("albums", {
orderBy: "title",
direction: "asc",
});
const artistsSort = useSortMemory("artists", {
orderBy: "name",
direction: "asc",
});
// Single-click play. Coexists with multi-select: ctrl/shift always
// takes precedence (selection), single-click triggers play only on a
// bare click and only when the toggle is on.
const { value: singleClickPlay } = useSingleClickPlay();
// Scroll target for the AlphabetIndex (artists tab uses it).
// Callback ref populated by the virtualized ArtistList so the
// alphabet jump index can scroll a specific artist into view without
// relying on a `querySelector` that can't reach off-screen rows.
const artistScrollToIndexRef = useRef<((idx: number) => void) | null>(null);
const trackContextMenu = useTrackContextMenu({
likedIds,
onLikedChanged: (trackId, nowLiked) =>
setLikedIds((prev) => {
const next = new Set(prev);
if (nowLiked) next.add(trackId);
else next.delete(trackId);
return next;
}),
onCreatePlaylist: () => setIsCreatePlaylistModalOpen(true),
onNavigateToAlbum,
onNavigateToArtist,
selectedTrackIds: [...selection.selectedIds],
});
// Re-fetch when any library's updated_at changes (e.g. after a scan),
// and when the sort sets articles aside or stops: the backend sorts
// artists and albums with it, so every listing comes back reordered.
const { ignoreArticles } = useSortIgnoreArticles();
const librariesSignature = `${libraries
.map((l) => `${l.id}:${l.updated_at}`)
.join(",")}|${ignoreArticles ? "articles" : "literal"}`;
// Bumped when a tag edit elsewhere fires `track:updated` so the
// active tab re-fetches and shows the new metadata.
const [editRefetch, setEditRefetch] = useState(0);
// `setEditRefetch` is listed even though a state setter is stable:
// the React Compiler infers it as a dependency, and a manual list
// that does not match makes it skip optimizing the whole component.
useTrackUpdated(
useCallback(() => setEditRefetch((k) => k + 1), [setEditRefetch]),
);
// And when an artist's picture changes: the artists grid reads that
// image, and a picture set from the artist page used to leave the
// grid showing the old one until a scan or a tag edit (#692). Its own
// counter rather than `editRefetch`, which every tab's effect depends
// on β a new artist photo says nothing about tracks, albums, genres,
// tags or folders.
const [artistRefetch, setArtistRefetch] = useState(0);
useArtistUpdated(
useCallback(() => setArtistRefetch((k) => k + 1), [setArtistRefetch]),
);
const clearSelection = selection.clear;
// The track table on screen, if any: the tracks tab, an opened folder,
// or an inventory category. Ctrl+A and the selection bar follow it, so
// a selection built in any of the three has its actions.
const listedTracks: LibraryTrackRow[] | null =
activeTab === "tracks"
? tracks
: // The listing must be the open folder's: right after walking
// into another one, the previous rows are still in state.
activeTab === "folders" &&
folderPath != null &&
folderListing?.path === folderPath
? folderTracks
: activeTab === "needs-attention" &&
inventoryCategory != null &&
inventoryCategory !== "phantom_artist"
? inventoryRows
: null;
// Local rows only: selection is keyed on local rowids.
useSelectAllShortcut(
listedTracks?.some((row) => row.source === "local") ?? false,
() =>
selection.selectAll(
(listedTracks ?? [])
.filter((row) => row.source === "local")
.map(toLocalTrack),
),
);
// Also on `folderPath`: a selection is a set of track ids, and the
// action bar it feeds would otherwise act on tracks the user can no
// longer see after walking into another folder (#578).
useEffect(() => {
clearSelection();
// And on the inventory category: switching one shows other rows.
}, [activeTab, folderPath, inventoryCategory, clearSelection]);
const { available: remoteAvailable } = useRemoteSource();
// Which server tracks are already kept offline, so the row's tick is right
// on first paint rather than only after the user downloads one this session.
// Silent on failure: a stock build has no such command, and a signed-out one
// has nothing to report β neither is worth a console error every mount.
useEffect(() => {
if (!remoteAvailable) return;
let cancelled = false;
void remoteListDownloads()
.then((kept) => {
if (!cancelled) {
setDownloadedRemote(
new Set(kept.map((entry) => entry.remote_track_id)),
);
}
})
.catch(() => {});
return () => {
cancelled = true;
};
}, [remoteAvailable]);
// Which custom tag keys the library holds. Only moves when a scan
// has run, so it follows the library signature rather than any
// render.
useEffect(() => {
let cancelled = false;
listTrackTagKeys()
.then((keys) => {
if (!cancelled) setTagKeys(keys);
})
.catch((err) => {
if (!cancelled)
console.error("[LibraryView] listTrackTagKeys failed", err);
});
return () => {
cancelled = true;
};
}, [librariesSignature, editRefetch]);
// Values for the chosen `tag:` columns. Nothing is fetched while none
// is shown, which is the common case -- and the dependency is the
// sorted key list rather than the layout, so reordering or resizing a
// column does not re-query the whole library.
// The chosen tag keys, as a value that only changes when the SET
// changes -- reordering or resizing a column must not re-query the
// whole library. `JSON.stringify` of a sorted array rather than a
// joined string, because a tag key can contain any character a tagger
// chose to write and there is no separator that is safe by
// construction.
const chosenTagKeys = useMemo(
() =>
JSON.stringify(
trackColumns.layout.order
.map((id) => (id.startsWith("tag:") ? id.slice(4) : null))
.filter((key): key is string => key !== null)
.sort(),
),
[trackColumns.layout.order],
);
// Every track's values for the chosen tag columns, in one read.
//
// Deliberately not scoped to the rows on screen, which looks like the
// obvious saving and is not one here: `tracks` already holds every
// row in the library: the virtualizer windows the *render*, not the
// data. These values are a few short strings per track against some
// twenty fields per row, so bounding them alone would make the tag
// columns the one part of the table fetched per scroll, against a
// design where the rows arrive once. If the memory matters, it is the
// row list that has to give first, and then this follows it.
useEffect(() => {
const keys = JSON.parse(chosenTagKeys) as string[];
if (keys.length === 0) {
// eslint-disable-next-line react-hooks/set-state-in-effect
setTagValues(new Map());
return;
}
let cancelled = false;
listTrackTagValues(keys)
.then((byTrack) => {
if (!cancelled) setTagValues(new Map(Object.entries(byTrack)));
})
.catch((err) => {
if (!cancelled)
console.error("[LibraryView] listTrackTagValues failed", err);
});
return () => {
cancelled = true;
};
}, [chosenTagKeys, librariesSignature, editRefetch]);
// The inventory is the one tab that fetches on activation rather than
// in parallel with the others: its counts are album-level aggregates
// plus a walk over every track, so prefetching them would tax everyone
// who never opens it. Re-runs when the library changes underneath, and
// after a tag edit, because fixing something is the whole point and a
// count that does not move reads as the fix not having worked.
useEffect(() => {
if (activeTab !== "needs-attention") return;
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect
setLoading((p) => ({ ...p, "needs-attention": true }));
inventorySummary()
.then((list) => {
if (!cancelled) setInventory(list);
})
.catch((err) => {
if (!cancelled)
console.error("[LibraryView] inventorySummary failed", err);
})
.finally(() => {
if (!cancelled) setLoading((p) => ({ ...p, "needs-attention": false }));
});
return () => {
cancelled = true;
};
}, [activeTab, librariesSignature, editRefetch]);
// Fixing the last track in a category is the success case, and it is
// the one that leaves the view wrong: the counts come back with that
// category at zero, `InventoryCategories` greys its button out, and
// the table underneath stays mounted on an empty list under a chip
// that can no longer be clicked to close it. So an emptied category
// closes itself, which puts the user back on the overview -- where
// the count they just drove to zero is the thing worth seeing.
useEffect(() => {
if (inventoryCategory == null) return;
const open = inventory.find((c) => c.key === inventoryCategory);
if (open && open.count > 0) return;
// eslint-disable-next-line react-hooks/set-state-in-effect
setInventoryCategory(null);
setInventoryRows([]);
}, [inventory, inventoryCategory]);
// Opening a category. Guarded on the key rather than on a request
// token: a second click on the same category is a no-op, and a click
// on another one replaces the rows wholesale, so a slow answer for a
// category the user has left must not paint.
useEffect(() => {
if (activeTab !== "needs-attention" || inventoryCategory == null) return;
// The one category made of artists lists itself (#719).
if (inventoryCategory === "phantom_artist") return;
// Same gate the other lists use: firing before the stored sort has
// been read loads the whole category once in the default order and
// again in the right one.
if (!tracksSort.isLoaded) return;
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect
setInventoryBusy(true);
inventoryTracks(inventoryCategory, tracksSort.sort)
.then((rows) => {
if (!cancelled) setInventoryRows(rows);
})
.catch((err) => {
if (!cancelled)
console.error("[LibraryView] inventoryTracks failed", err);
})
.finally(() => {
if (!cancelled) setInventoryBusy(false);
});
return () => {
cancelled = true;
};
}, [
activeTab,
inventoryCategory,
tracksSort.sort,
tracksSort.isLoaded,
// A rescan changes what a category holds, and the open category is
// the one the user is looking at while it runs.
librariesSignature,
editRefetch,
]);
// Per-tab parallel fetchers β each runs independently of `activeTab`,
// so navigating into LibraryView fires all 5 SQL queries at once and
// every subsequent tab switch hits cached state instantly. The 500 ms
// "EmptyState flash" disappears because the data lands during the
// very first paint instead of after the user picks a tab.
useEffect(() => {
// Both preferences gate the fetch, for the reason on the albums effect.
if (!tracksSort.isLoaded || !librarySource.ready) return;
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect
setLoading((p) => ({ ...p, tracks: true }));
listLibraryTracks(
null,
librarySource.source === "all" ? null : librarySource.source,
tracksSort.sort,
)
.then((list) => {
if (!cancelled) setTracks(list);
})
.catch((err) => {
if (!cancelled)
console.error("[LibraryView] listLibraryTracks failed", err);
})
.finally(() => {
if (!cancelled) setLoading((p) => ({ ...p, tracks: false }));
});
return () => {
cancelled = true;
};
}, [
librariesSignature,
tracksSort.isLoaded,
tracksSort.sort,
librarySource.ready,
librarySource.source,
editRefetch,
]);
useEffect(() => {
// Both preferences gate the fetch: loading with either default and again
// with the stored value would paint the wrong list first, and the source
// filter is the more visible of the two to get wrong.
if (!albumsSort.isLoaded || !librarySource.ready) return;
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect
setLoading((p) => ({ ...p, albums: true }));
listLibraryAlbums(
null,
librarySource.source === "all" ? null : librarySource.source,
{
orderBy: albumsSort.sort.orderBy,
direction: albumsSort.sort.direction,
},
)
.then((list) => {
if (!cancelled) setAlbums(list);
})
.catch((err) => {
if (!cancelled)
console.error("[LibraryView] listLibraryAlbums failed", err);
})
.finally(() => {
if (!cancelled) setLoading((p) => ({ ...p, albums: false }));
});
return () => {
cancelled = true;
};
}, [
librariesSignature,
albumsSort.isLoaded,
albumsSort.sort,
librarySource.ready,
librarySource.source,
coverReloadKey,
editRefetch,
]);
useEffect(() => {
// Both preferences gate the fetch, for the reason on the albums effect.
if (!artistsSort.isLoaded || !librarySource.ready) return;
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect
setLoading((p) => ({ ...p, artists: true }));
listLibraryArtists(
null,
librarySource.source === "all" ? null : librarySource.source,
artistsSort.sort,
)
.then((list) => {
if (!cancelled) setArtists(list);
})
.catch((err) => {
if (!cancelled)
console.error("[LibraryView] listLibraryArtists failed", err);
})
.finally(() => {
if (!cancelled) setLoading((p) => ({ ...p, artists: false }));
});
return () => {
cancelled = true;
};
}, [
librariesSignature,
artistsSort.isLoaded,
artistsSort.sort,
librarySource.ready,
librarySource.source,
editRefetch,
artistRefetch,
]);
useEffect(() => {
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect
setLoading((p) => ({ ...p, genres: true }));
listGenres(null)
.then((list) => {
if (!cancelled) setGenres(list);
})
.catch((err) => {
if (!cancelled) console.error("[LibraryView] listGenres failed", err);
})
.finally(() => {
if (!cancelled) setLoading((p) => ({ ...p, genres: false }));
});
return () => {
cancelled = true;
};
}, [librariesSignature, editRefetch]);
useEffect(() => {
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect
setLoading((p) => ({ ...p, years: true }));
listYears(null)
.then((list) => {
if (!cancelled) setYears(list);
})
.catch((err) => {
if (!cancelled) console.error("[LibraryView] listYears failed", err);
})
.finally(() => {
if (!cancelled) setLoading((p) => ({ ...p, years: false }));
});
return () => {
cancelled = true;
};
}, [librariesSignature, editRefetch]);
useEffect(() => {
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect
setLoading((p) => ({ ...p, folders: true }));
listFolders(null)
.then((list) => {
if (!cancelled) setFolders(list);
})
.catch((err) => {
if (!cancelled) console.error("[LibraryView] listFolders failed", err);
})
.finally(() => {
if (!cancelled) setLoading((p) => ({ ...p, folders: false }));
});
return () => {
cancelled = true;
};
}, [librariesSignature]);
// Load liked track IDs once on mount so the TrackTable can show
// filled hearts. Re-fetches when the libraries change (scan might
// add new tracks whose liked state we need to know).
useEffect(() => {
listLikedTrackIds()
.then((ids) => setLikedIds(new Set(ids)))
.catch((err) => console.error("[LibraryView] liked ids failed", err));
}, [librariesSignature]);
// Merged where they are read: both playlist surfaces already sorted in the
// browser, so there is nothing for a compound select to unify.
const libraryPlaylists = useLibraryPlaylists(
userPlaylists,
librarySource.source,
);
// Browse one folder: its child directories, and the files directly
// inside it. Two calls rather than one because the files come back in
// the Tracks tab's own row shape, which is what lets the folder view
// render the same table with the same sort.
useEffect(() => {
// Nothing is cleared here on the way out: the folder branch does
// not read these states while `folderPath` is null, and clearing
// them would be a setState cascade for a value nobody looks at.
// What protects the render instead is the stamp -- `listing.path`
// has to match the folder being shown, so a previous folder's
// contents count as absent rather than as approximate.
if (folderPath == null) return;
if (!tracksSort.isLoaded) return;
const mine = folderRequest.current + 1;
folderRequest.current = mine;
// eslint-disable-next-line react-hooks/set-state-in-effect
setFolderBusy(true);
void Promise.all([
browseFolders(null, folderPath),
listFolderTracks(null, folderPath, {
recursive: false,
...tracksSort.sort,
}),
])
.then(([listing, rows]) => {
if (folderRequest.current !== mine) return;
setFolderListing(listing);
setFolderTracks(rows);
})
.catch((err: unknown) => {
if (folderRequest.current !== mine) return;
console.error("[LibraryView] browseFolders failed", err);
setFolderListing(null);
setFolderTracks([]);
})
.finally(() => {
if (folderRequest.current === mine) setFolderBusy(false);
});
// `librariesSignature` and `editRefetch` for the same reason every
// other tab watches them: a rescan or a tag edit changes what is in
// the folder, and a view that only reloads on navigation would show
// the user their own edit as missing.
}, [
folderPath,
tracksSort.isLoaded,
tracksSort.sort,
librariesSignature,
editRefetch,
]);
/** Everything under a folder, for the actions that take ids. */
const idsUnderFolder = useCallback(
(path: string) =>
folderTrackIds(null, path).catch((err: unknown) => {
console.error("[LibraryView] folderTrackIds failed", err);
return [] as number[];
}),
[],
);
/** Play a folder whole, in path order. Goes through the same
* `playTracks` the Tracks tab uses, with the recursive listing as its
* queue β ids alone would not carry what the player needs. */
const playFolder = useCallback(
async (path: string) => {
try {
const rows = await listFolderTracks(null, path, { recursive: true });
if (rows.length === 0) return;
await playTracks(rows.map(toLocalTrack), 0, {
type: "library",
id: null,
});
} catch (err) {
console.error("[LibraryView] playFolder failed", err);
}
},
[playTracks],
);
// Per-tab header subtext uses the fetched data lengths since we
// aggregate across all libraries (no single Library to read counts from).
const countForTab = (tab: LibraryTab): number => {
switch (tab) {
case "tracks":
return tracks.length;
case "albums":
return albums.length;
case "artists":
return artists.length;
case "genres":
return genres.length;
case "years":
return years.length;
case "playlists":
// The merged list, not the local one: the header would otherwise
// count a different set from the grid right below it.
return libraryPlaylists.length;
case "folders":
return folders.length;
case "needs-attention":
// The number the header should carry is "how many tracks need
// attention", which is the sum of the categories β and a
// category can list a track that another one lists too, so this
// is a count of findings rather than of distinct tracks. The
// subtext key says so.
return inventory.reduce((sum, category) => sum + category.count, 0);