-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLibraryContext.tsx
More file actions
231 lines (218 loc) Β· 7.09 KB
/
LibraryContext.tsx
File metadata and controls
231 lines (218 loc) Β· 7.09 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
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
import { listen } from "@tauri-apps/api/event";
import { LibraryContext } from "../hooks/useLibrary";
import { useProfile } from "../hooks/useProfile";
import {
addFolderToLibrary,
createLibrary as apiCreateLibrary,
deleteLibrary as apiDeleteLibrary,
listLibraries,
rescanLibrary as apiRescanLibrary,
scanFolder,
updateLibrary as apiUpdateLibrary,
type CreateLibraryInput,
type Library,
type UpdateLibraryInput,
} from "../lib/tauri/library";
export function LibraryProvider({ children }: { children: ReactNode }) {
const { activeProfile } = useProfile();
// Tracks the currently-active profile id so `refresh()` can detect when
// its in-flight `listLibraries` response belongs to a profile the user
// has since switched away from, and drop the stale write.
const activeProfileIdRef = useRef<number | null>(null);
useEffect(() => {
activeProfileIdRef.current = activeProfile?.id ?? null;
}, [activeProfile?.id]);
const [libraries, setLibraries] = useState<Library[]>([]);
const [loadedProfileId, setLoadedProfileId] = useState<number | null>(null);
const [selectedLibraryId, setSelectedLibraryId] = useState<number | null>(
null,
);
// Start in the loading state so consumers waiting on a "first
// fetch settled" signal don't see the empty initial value as if
// the fetch had completed. The mount-time `useEffect` below
// resolves it to `false` once `listLibraries` returns. Without
// this, the first-run onboarding modal flashes on every launch:
// before the effect runs, `libraries.length === 0` is true even
// for users with a populated library, and `AppLayout` opens the
// modal for one frame before the fetch lands.
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const refresh = useCallback(async () => {
if (!activeProfile) {
setLibraries([]);
setLoadedProfileId(null);
setSelectedLibraryId(null);
return;
}
const profileIdAtStart = activeProfile.id;
try {
const list = await listLibraries();
// Drop the response if the user switched profile mid-flight β writing
// it would clobber the new profile's libraries with the old one's data
// and re-block the onboarding gate (see fix/onboarding-on-new-profile).
if (activeProfileIdRef.current !== profileIdAtStart) return;
setLibraries(list);
setLoadedProfileId(profileIdAtStart);
setError(null);
// Keep the current selection if it still exists, otherwise fall back to
// the most-recently-updated library (which is the first one because of
// the ORDER BY in `list_libraries`).
setSelectedLibraryId((prev) => {
if (prev != null && list.some((l) => l.id === prev)) return prev;
return list[0]?.id ?? null;
});
} catch (err) {
if (activeProfileIdRef.current !== profileIdAtStart) return;
const message = err instanceof Error ? err.message : String(err);
setError(message);
console.error("[LibraryContext] refresh failed", err);
}
}, [activeProfile]);
// Re-fetch whenever the active profile changes β libraries are scoped to
// `data.db` which is swapped on profile switch.
useEffect(() => {
let cancelled = false;
(async () => {
setIsLoading(true);
try {
if (!activeProfile) {
if (!cancelled) {
setLibraries([]);
setLoadedProfileId(null);
setSelectedLibraryId(null);
}
return;
}
const list = await listLibraries();
if (cancelled) return;
setLibraries(list);
setLoadedProfileId(activeProfile.id);
setSelectedLibraryId((prev) => {
if (prev != null && list.some((l) => l.id === prev)) return prev;
return list[0]?.id ?? null;
});
setError(null);
} catch (err) {
if (cancelled) return;
const message = err instanceof Error ? err.message : String(err);
setError(message);
console.error("[LibraryContext] initial load failed", err);
} finally {
if (!cancelled) setIsLoading(false);
}
})();
return () => {
cancelled = true;
};
}, [activeProfile]);
// The filesystem watcher emits `library:rescanned` after each
// debounced rescan completes. Refreshing here bumps each library's
// `updated_at`, which propagates through the `librariesSignature`
// memo in views and re-fetches their visible track / album lists
// without manual reloads.
useEffect(() => {
if (!activeProfile) return;
let unlisten: (() => void) | undefined;
let cancelled = false;
(async () => {
try {
const off = await listen("library:rescanned", () => {
refresh().catch(() => {});
});
if (cancelled) {
off();
} else {
unlisten = off;
}
} catch (err) {
console.error("[LibraryContext] listen library:rescanned failed", err);
}
})();
return () => {
cancelled = true;
unlisten?.();
};
}, [activeProfile, refresh]);
const selectLibrary = useCallback((libraryId: number | null) => {
setSelectedLibraryId(libraryId);
}, []);
const createLibrary = useCallback(
async (input: CreateLibraryInput) => {
const created = await apiCreateLibrary(input);
await refresh();
setSelectedLibraryId(created.id);
return created;
},
[refresh],
);
const importFolder = useCallback(
async (libraryId: number, path: string) => {
const folderId = await addFolderToLibrary(libraryId, path);
const summary = await scanFolder(folderId);
await refresh();
return summary;
},
[refresh],
);
const updateLibrary = useCallback(
async (libraryId: number, input: UpdateLibraryInput) => {
await apiUpdateLibrary(libraryId, input);
await refresh();
},
[refresh],
);
const deleteLibrary = useCallback(
async (libraryId: number) => {
await apiDeleteLibrary(libraryId);
// `refresh` will pick a new selection from the remaining libraries
// (most recently updated first) because the previous id no longer
// matches anything in the list.
await refresh();
},
[refresh],
);
const rescanLibrary = useCallback(
async (libraryId: number) => {
const summary = await apiRescanLibrary(libraryId);
await refresh();
return summary;
},
[refresh],
);
const selectedLibrary = useMemo(
() =>
selectedLibraryId == null
? null
: (libraries.find((l) => l.id === selectedLibraryId) ?? null),
[libraries, selectedLibraryId],
);
return (
<LibraryContext.Provider
value={{
libraries,
loadedProfileId,
selectedLibraryId,
selectedLibrary,
isLoading,
error,
refresh,
selectLibrary,
createLibrary,
updateLibrary,
deleteLibrary,
rescanLibrary,
importFolder,
}}
>
{children}
</LibraryContext.Provider>
);
}