Files
otunes/apps/mobile/contexts/add-to-playlist.tsx
T
joshuafhiggins 9da758b196 perf: optimize app rendering and data loading (#18)
- Virtualize mobile lists and defer queue loading
- Split playback state from actions to reduce rerenders
- Skip invalid or unnecessary Convex queries

Reviewed-on: #18
2026-09-05 16:35:37 -04:00

381 lines
10 KiB
TypeScript

import { useConvex, useMutation, useQuery } from "convex/react"
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react"
import {
FlatList,
Modal,
Pressable,
StyleSheet,
Text,
View,
} from "react-native"
import { Button, Input } from "@/components/ui/primitives"
import { api } from "@otunes/convex/_generated/api"
import type { OwnedPlaylistForAdd } from "@otunes/convex/types"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { showError, showSuccess } from "@/lib/toast"
import { useAppNavigation } from "@/lib/app-navigation"
import { useThemeColors } from "@/lib/theme"
type AddToPlaylistContextValue = {
openAddToPlaylist: (songIds: Id<"songs">[]) => void
openAddAlbumToPlaylist: (albumId: Id<"albums">) => Promise<void>
openAddPlaylistToPlaylist: (playlistId: Id<"playlists">) => Promise<void>
openAddArtistToPlaylist: (artistId: Id<"artists">) => Promise<void>
openCreatePlaylist: () => void
}
const AddToPlaylistContext = createContext<AddToPlaylistContextValue | null>(
null
)
export function useAddToPlaylist() {
const context = useContext(AddToPlaylistContext)
if (!context) {
throw new Error(
"useAddToPlaylist must be used within AddToPlaylistProvider"
)
}
return context
}
export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
const convex = useConvex()
const { push } = useAppNavigation()
const colors = useThemeColors()
const addSongs = useMutation(api.playlists.addSongsToPlaylist)
const createPlaylist = useMutation(api.playlists.createPlaylist)
const [open, setOpen] = useState(false)
const [createOpen, setCreateOpen] = useState(false)
const [pendingSongIds, setPendingSongIds] = useState<Id<"songs">[]>([])
const [newPlaylistName, setNewPlaylistName] = useState("")
const [submitting, setSubmitting] = useState(false)
const [addingToPlaylistId, setAddingToPlaylistId] =
useState<Id<"playlists"> | null>(null)
const selectionRequestIdRef = useRef(0)
const ownedPlaylists = useQuery(
api.playlists.listOwnedPlaylists,
open ? {} : "skip"
)
useEffect(
() => () => {
selectionRequestIdRef.current += 1
},
[]
)
const openAddToPlaylist = useCallback((songIds: Id<"songs">[]) => {
selectionRequestIdRef.current += 1
setPendingSongIds(songIds)
setOpen(true)
}, [])
const closeAddToPlaylist = useCallback(() => {
selectionRequestIdRef.current += 1
setOpen(false)
setAddingToPlaylistId(null)
setPendingSongIds([])
}, [])
const openAddAlbumToPlaylist = useCallback(
async (albumId: Id<"albums">) => {
const requestId = ++selectionRequestIdRef.current
try {
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
albumId,
})
if (selectionRequestIdRef.current !== requestId) return
setPendingSongIds(songIds)
setOpen(true)
} catch (error) {
if (selectionRequestIdRef.current !== requestId) return
showError(
error instanceof Error ? error.message : "Failed to load album"
)
}
},
[convex]
)
const openAddPlaylistToPlaylist = useCallback(
async (playlistId: Id<"playlists">) => {
const requestId = ++selectionRequestIdRef.current
try {
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
playlistId,
})
if (selectionRequestIdRef.current !== requestId) return
setPendingSongIds(songIds)
setOpen(true)
} catch (error) {
if (selectionRequestIdRef.current !== requestId) return
showError(
error instanceof Error ? error.message : "Failed to load playlist"
)
}
},
[convex]
)
const openAddArtistToPlaylist = useCallback(
async (artistId: Id<"artists">) => {
const requestId = ++selectionRequestIdRef.current
try {
const songIds = await convex.query(
api.playlists.getOrderedArtistSongIds,
{ artistId }
)
if (selectionRequestIdRef.current !== requestId) return
setPendingSongIds(songIds)
setOpen(true)
} catch (error) {
if (selectionRequestIdRef.current !== requestId) return
showError(
error instanceof Error ? error.message : "Failed to load artist"
)
}
},
[convex]
)
const openCreatePlaylist = useCallback(() => {
selectionRequestIdRef.current += 1
setPendingSongIds([])
setNewPlaylistName("")
setCreateOpen(true)
}, [])
const handleAddToPlaylist = useCallback(
async (
playlistId: Id<"playlists">,
title: string,
existing: Id<"songs">[]
) => {
if (addingToPlaylistId) return
const existingSet = new Set(existing)
const toAdd = pendingSongIds.filter((id) => !existingSet.has(id))
if (toAdd.length === 0) {
showSuccess(`All selected songs are already in ${title}`)
closeAddToPlaylist()
return
}
setAddingToPlaylistId(playlistId)
try {
await addSongs({ playlistId, songIds: toAdd })
showSuccess(
toAdd.length > 1
? `Added ${toAdd.length} songs to ${title}`
: `Added to ${title}`
)
closeAddToPlaylist()
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to add to playlist"
)
} finally {
setAddingToPlaylistId(null)
}
},
[addSongs, addingToPlaylistId, closeAddToPlaylist, pendingSongIds]
)
const handleCreatePlaylist = useCallback(async () => {
const name = newPlaylistName.trim()
if (!name) return
setSubmitting(true)
try {
const playlistId = await createPlaylist({
name,
songIds: pendingSongIds,
})
showSuccess("Playlist created")
setCreateOpen(false)
closeAddToPlaylist()
push(`/playlist/${playlistId}`)
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to create playlist"
)
} finally {
setSubmitting(false)
}
}, [
closeAddToPlaylist,
createPlaylist,
newPlaylistName,
pendingSongIds,
push,
])
const value = useMemo(
() => ({
openAddToPlaylist,
openAddAlbumToPlaylist,
openAddPlaylistToPlaylist,
openAddArtistToPlaylist,
openCreatePlaylist,
}),
[
openAddToPlaylist,
openAddAlbumToPlaylist,
openAddPlaylistToPlaylist,
openAddArtistToPlaylist,
openCreatePlaylist,
]
)
return (
<AddToPlaylistContext.Provider value={value}>
{children}
<Modal
visible={open}
animationType="slide"
transparent
onRequestClose={closeAddToPlaylist}
>
<Pressable style={styles.overlay} onPress={closeAddToPlaylist}>
<Pressable
style={[
styles.sheet,
{ backgroundColor: colors.card, borderColor: colors.border },
]}
onPress={(event) => event.stopPropagation()}
>
<Text style={[styles.title, { color: colors.foreground }]}>
Add to Playlist
</Text>
<FlatList
style={styles.list}
data={ownedPlaylists ?? []}
keyExtractor={(playlist) => playlist.id}
renderItem={({
item: playlist,
}: {
item: OwnedPlaylistForAdd
}) => (
<Pressable
style={styles.row}
disabled={addingToPlaylistId !== null}
onPress={() =>
void handleAddToPlaylist(
playlist.id,
playlist.title,
playlist.songIds
)
}
>
<Text style={{ color: colors.foreground }}>
{playlist.title}
</Text>
</Pressable>
)}
/>
<Button
title="New Playlist"
variant="secondary"
onPress={() => {
selectionRequestIdRef.current += 1
setOpen(false)
setNewPlaylistName("")
setCreateOpen(true)
}}
/>
</Pressable>
</Pressable>
</Modal>
<Modal
visible={createOpen}
animationType="fade"
transparent
onRequestClose={() => setCreateOpen(false)}
>
<Pressable style={styles.overlay} onPress={() => setCreateOpen(false)}>
<Pressable
style={[
styles.createSheet,
{ backgroundColor: colors.card, borderColor: colors.border },
]}
onPress={(event) => event.stopPropagation()}
>
<Text style={[styles.title, { color: colors.foreground }]}>
New Playlist
</Text>
<Input
value={newPlaylistName}
onChangeText={setNewPlaylistName}
placeholder="Playlist name"
autoFocus
/>
<View style={styles.createActions}>
<Button
title="Cancel"
variant="ghost"
onPress={() => setCreateOpen(false)}
/>
<Button
title="Create"
loading={submitting}
disabled={!newPlaylistName.trim()}
onPress={() => void handleCreatePlaylist()}
/>
</View>
</Pressable>
</Pressable>
</Modal>
</AddToPlaylistContext.Provider>
)
}
const styles = StyleSheet.create({
overlay: {
flex: 1,
backgroundColor: "rgba(0,0,0,0.45)",
justifyContent: "flex-end",
},
sheet: {
maxHeight: "60%",
borderTopLeftRadius: 16,
borderTopRightRadius: 16,
borderWidth: 1,
padding: 16,
gap: 12,
},
createSheet: {
margin: 24,
borderRadius: 16,
borderWidth: 1,
padding: 16,
gap: 12,
},
title: {
fontSize: 18,
fontWeight: "700",
},
list: {
maxHeight: 280,
},
row: {
paddingVertical: 14,
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: "#e4e4e7",
},
createActions: {
flexDirection: "row",
justifyContent: "flex-end",
gap: 8,
},
})