Compare commits

...
71 changed files with 4383 additions and 1945 deletions

No files matched your search

+116 -17
View File
@@ -1,3 +1,5 @@
# syntax=docker/dockerfile:1
# ============================================ # ============================================
# Stage 1: Dependencies Installation Stage # Stage 1: Dependencies Installation Stage
# ============================================ # ============================================
@@ -11,6 +13,11 @@ ARG NODE_VERSION=24.13.0-slim
# https://github.com/get-convex/convex-backend/pkgs/container/convex-backend # https://github.com/get-convex/convex-backend/pkgs/container/convex-backend
ARG CONVEX_BACKEND_IMAGE=ghcr.io/get-convex/convex-backend:5c7cb5bc7db457290f1769f95f1d1340912f7fd7 ARG CONVEX_BACKEND_IMAGE=ghcr.io/get-convex/convex-backend:5c7cb5bc7db457290f1769f95f1d1340912f7fd7
# Audio-only static ffmpeg. The distro package links video filters that pull
# in LLVM and Mesa (~420MB) for codecs this app never uses.
ARG FFMPEG_VERSION=7.1.5
ARG FFMPEG_SHA256=de668509caf9e35e3cd162473441fdb29538c6d96ed080292b3cf9e6fc5d558f
FROM node:${NODE_VERSION} AS node FROM node:${NODE_VERSION} AS node
FROM node:${NODE_VERSION} AS dependencies FROM node:${NODE_VERSION} AS dependencies
@@ -28,7 +35,12 @@ RUN printf '%s\n' \
'packages:' \ 'packages:' \
' - "apps/web"' \ ' - "apps/web"' \
' - "packages/convex"' \ ' - "packages/convex"' \
> pnpm-workspace.yaml >> pnpm-workspace.yaml \
&& printf '\n%s\n' \
'supportedArchitectures.os=current' \
'supportedArchitectures.cpu=current' \
'supportedArchitectures.libc=current' \
>> .npmrc
RUN --mount=type=cache,target=/root/.local/share/pnpm/store \ RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
corepack enable pnpm && \ corepack enable pnpm && \
@@ -38,21 +50,20 @@ RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
# Stage 2: Build Next.js application in standalone mode # Stage 2: Build Next.js application in standalone mode
# ============================================ # ============================================
# Reuse the installed workspace — no need to re-copy node_modules from a blank image. # Reuse the installed workspace. Copying node_modules into a new layer retars
# hundreds of thousands of files on every source change.
FROM dependencies AS builder FROM dependencies AS builder
WORKDIR /app WORKDIR /app
# Overlay sources; nested node_modules must be dockerignored so they do not COPY apps/web /tmp/src/apps/web
# replace the install from the dependencies stage with host pnpm symlinks. COPY packages/convex /tmp/src/packages/convex
COPY apps/web ./apps/web
COPY packages/convex ./packages/convex
# Re-apply the install tree after source COPY so module resolution cannot be # Merge sources onto the install. cp does not remove the existing
# clobbered even if a nested node_modules slips into the build context. # node_modules tree, and the build context already dockerignores it.
COPY --from=dependencies /app/node_modules ./node_modules RUN cp -a /tmp/src/apps/web/. ./apps/web/ \
COPY --from=dependencies /app/apps/web/node_modules ./apps/web/node_modules && cp -a /tmp/src/packages/convex/. ./packages/convex/ \
COPY --from=dependencies /app/packages/convex/node_modules ./packages/convex/node_modules && rm -rf /tmp/src
ENV NODE_ENV=production ENV NODE_ENV=production
@@ -75,7 +86,12 @@ COPY packages/convex/package.json ./packages/convex/
RUN printf '%s\n' \ RUN printf '%s\n' \
'packages:' \ 'packages:' \
' - "packages/convex"' \ ' - "packages/convex"' \
> pnpm-workspace.yaml > pnpm-workspace.yaml \
&& printf '\n%s\n' \
'supportedArchitectures.os=current' \
'supportedArchitectures.cpu=current' \
'supportedArchitectures.libc=current' \
>> .npmrc
RUN --mount=type=cache,target=/root/.local/share/pnpm/store \ RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
corepack enable pnpm && \ corepack enable pnpm && \
@@ -83,19 +99,100 @@ RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
COPY packages/convex ./packages/convex COPY packages/convex ./packages/convex
# Source maps and the Convex package's TypeScript sources are not used at runtime.
RUN find /app -type f -name '*.map' -delete \
&& rm -rf /app/node_modules/.pnpm/convex@*/node_modules/convex/src
# ============================================ # ============================================
# Stage 4: Run Convex and Next.js together # Stage 4: Audio-only ffmpeg
# ============================================ # ============================================
FROM ${CONVEX_BACKEND_IMAGE} AS runner FROM ubuntu:24.04 AS ffmpeg
ARG FFMPEG_VERSION
ARG FFMPEG_SHA256
RUN apt-get update && \ RUN apt-get update && \
apt-get install -y --no-install-recommends ffmpeg tini && \ apt-get install -y --no-install-recommends \
build-essential ca-certificates curl nasm pkg-config xz-utils zlib1g-dev && \
rm -rf /var/lib/apt/lists/* rm -rf /var/lib/apt/lists/*
RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes WORKDIR /src
COPY --from=node /usr/local/bin/node /opt/node/bin/node RUN curl -fsSL -o ffmpeg.tar.xz "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz" \
&& echo "${FFMPEG_SHA256} ffmpeg.tar.xz" | sha256sum -c - \
&& tar -xJf ffmpeg.tar.xz --strip-components=1 \
&& rm ffmpeg.tar.xz
# Decoders cover the library formats (FLAC, ALAC/AAC in m4a, MP3, Opus,
# Vorbis, WavPack, WMA, E-AC-3/TrueHD for Atmos). Encoders are only the two
# the app writes: AAC (HLS and ADTS) and FLAC.
RUN ./configure \
--prefix=/opt/ffmpeg \
--disable-shared \
--enable-static \
--disable-debug \
--disable-doc \
--disable-ffplay \
--disable-ffprobe \
--disable-network \
--disable-autodetect \
--disable-everything \
--enable-ffmpeg \
--enable-protocol=file,pipe \
--enable-demuxer=aac,ac3,aiff,ape,asf,au,caf,dsf,flac,matroska,mov,mp3,ogg,wav,wv \
--enable-decoder=aac,aac_latm,ac3,alac,ape,dsd_lsbf,dsd_msbf,eac3,flac,mlp,mp3,opus,pcm_f32le,pcm_s16be,pcm_s16le,pcm_s24be,pcm_s24le,pcm_s32be,pcm_s32le,pcm_u8,truehd,vorbis,wavpack,wmav1,wmav2 \
--enable-encoder=aac,flac \
--enable-muxer=adts,flac,hls,mpegts \
--enable-parser=aac,aac_latm,ac3,flac,mpegaudio,opus,vorbis \
--enable-bsf=aac_adtstoasc \
--enable-filter=aresample,aformat \
--enable-zlib \
--extra-cflags="-Os" \
--extra-ldflags="-static" \
--pkg-config-flags="--static" \
&& make -j"$(nproc)" \
&& make install \
&& strip /opt/ffmpeg/bin/ffmpeg
# ============================================
# Stage 5: Run Convex and Next.js together
# ============================================
FROM ${CONVEX_BACKEND_IMAGE} AS convex-backend
# Fresh Ubuntu instead of the Convex image. That image installs libclang,
# which pulls LLVM (~200MB) even though the backend only links libstdc++.
FROM ubuntu:24.04 AS runner
RUN apt-get update && \
apt-get install -y --no-install-recommends ca-certificates curl openssl tini && \
rm -rf /var/lib/apt/lists/*
WORKDIR /convex
COPY --from=convex-backend --chmod=755 \
/convex/convex-local-backend \
/convex/generate_key \
/convex/run_backend.sh \
/convex/generate_admin_key.sh \
/convex/read_credentials.sh \
./
COPY --from=node --chmod=755 /usr/local/bin/node /usr/local/bin/node
COPY --from=ffmpeg --chmod=755 /opt/ffmpeg/bin/ffmpeg /usr/local/bin/ffmpeg
# Fail the build if a binary is missing a shared library.
RUN node --version \
&& ffmpeg -hide_banner -version \
&& openssl version \
&& command -v tini \
&& command -v curl \
&& ldd /convex/convex-local-backend \
&& ldd /convex/generate_key \
&& ! ldd /convex/convex-local-backend /convex/generate_key | grep -q 'not found'
RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes
COPY --from=convex-functions /app /opt/otunes/convex COPY --from=convex-functions /app /opt/otunes/convex
COPY docker/generate-auth-keys.mjs /opt/otunes/generate-auth-keys.mjs COPY docker/generate-auth-keys.mjs /opt/otunes/generate-auth-keys.mjs
@@ -109,6 +206,8 @@ COPY --from=builder --chown=otunes:otunes /app/apps/web/.next/static ./apps/web/
RUN mkdir -p apps/web/.next /data && chown -R otunes:otunes apps/web/.next RUN mkdir -p apps/web/.next /data && chown -R otunes:otunes apps/web/.next
ENV PATH="/usr/local/bin:${PATH}"
EXPOSE 3000 3210 EXPOSE 3000 3210
HEALTHCHECK --interval=10s --timeout=5s --start-period=60s \ HEALTHCHECK --interval=10s --timeout=5s --start-period=60s \
+3 -1
View File
@@ -65,7 +65,9 @@
} }
], ],
"expo-image", "expo-image",
"expo-status-bar" "expo-status-bar",
"./plugins/with-ios-pod-deployment-target.js",
"./plugins/with-ios-scene-lifecycle.js"
], ],
"experiments": { "experiments": {
"typedRoutes": true "typedRoutes": true
@@ -16,17 +16,18 @@ export default function HomeLayout() {
screenOptions={({ route }) => ({ screenOptions={({ route }) => ({
...baseOptions, ...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Home", title: tabStackScreenTitles[route.name] ?? "Home",
headerRight: route.name === "settings" ? undefined : () => <ProfileHeaderButton />, headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems: unstable_headerRightItems:
route.name === "settings" route.name === "index"
? undefined ? () => [
: () => [
{ {
type: "custom", type: "custom",
element: <ProfileHeaderButton />, element: <ProfileHeaderButton />,
hidesSharedBackground: true, hidesSharedBackground: true,
}, },
], ]
: undefined,
})} })}
/> />
) )
+264 -115
View File
@@ -1,26 +1,38 @@
import { useQuery } from "convex/react" import { Stack, useIsFocused, useLocalSearchParams } from "expo-router"
import { Stack, useLocalSearchParams } from "expo-router" import { StatusBar } from "expo-status-bar"
import { memo, useCallback, useEffect, useMemo } from "react"
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native" import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
import { Ionicons } from "@expo/vector-icons" import { Ionicons } from "@expo/vector-icons"
import {
CollectionDivider,
collectionInset,
DiscHeader,
} from "@/components/collection-list"
import { CoverImage } from "@/components/cover-image" import { CoverImage } from "@/components/cover-image"
import { import {
MediaActionMenu, MediaActionMenu,
MediaContextMenu, MediaContextMenu,
type MediaAction,
} from "@/components/media-actions-sheet" } from "@/components/media-actions-sheet"
import { Button, LoadingView } from "@/components/ui/primitives" import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player" import { contentBottomInset } from "@/components/player"
import { useFavorites } from "@/contexts/favorites" import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback" import { usePlaybackActions } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config" import { useServerConfig } from "@/contexts/server-config"
import { useCoverBackgroundColor } from "@/hooks/use-cover-background-color" import { useCachedQuery } from "@/hooks/use-cached-query"
import { useCoverPalette } from "@/hooks/use-cover-palette"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseAlbumTrack } from "@otunes/convex/types" import type { BrowseAlbumDetail, BrowseAlbumTrack } from "@otunes/convex/types"
import type { CoverPalette } from "@/lib/cover-palette"
import { formatDuration, formatMetadata } from "@/lib/format" import { formatDuration, formatMetadata } from "@/lib/format"
import { useAppNavigation } from "@/lib/app-navigation" import { useAppNavigation } from "@/lib/app-navigation"
import { longListProps } from "@/lib/list"
import { albumDetailSongs, rememberSongs } from "@/lib/song-cache"
import { albumCoverUrl } from "@/lib/urls" import { albumCoverUrl } from "@/lib/urls"
import { radius, spacing, useThemeColors } from "@/lib/theme" import { radius, spacing, useThemeColors } from "@/lib/theme"
@@ -29,7 +41,7 @@ export default function AlbumScreen() {
const { push } = useAppNavigation() const { push } = useAppNavigation()
const colors = useThemeColors() const colors = useThemeColors()
const { config } = useServerConfig() const { config } = useServerConfig()
const album = useQuery( const album = useCachedQuery(
api.library.browseAlbumDetail, api.library.browseAlbumDetail,
typeof id === "string" ? { id: id as Id<"albums"> } : "skip" typeof id === "string" ? { id: id as Id<"albums"> } : "skip"
) )
@@ -41,15 +53,55 @@ export default function AlbumScreen() {
handleAlbumTrackAction, handleAlbumTrackAction,
isAlbumFavorite: isAlbumFav, isAlbumFavorite: isAlbumFav,
} = useMediaMenuActions() } = useMediaMenuActions()
const isFocused = useIsFocused()
const coverUri = const coverUri =
config && album ? albumCoverUrl(config.serverUrl, album.id) : "" config && typeof id === "string" ? albumCoverUrl(config.serverUrl, id) : ""
const backgroundColor = useCoverBackgroundColor( const { palette, settled } = useCoverPalette(
coverUri, coverUri,
album?.cover != null, album ? album.cover != null : album === null ? false : undefined
colors.background )
const songIds = useMemo(
() => album?.tracks.map((track) => track.id as Id<"songs">) ?? [],
[album]
) )
if (album === undefined || !config) { useEffect(() => {
if (album) {
rememberSongs(albumDetailSongs(album))
}
}, [album])
const listItems = useMemo(() => albumListItems(album?.tracks ?? []), [album])
const renderItem = useCallback(
({ item }: { item: AlbumListItem }) => {
if (item.type === "disc") {
return <DiscHeader label={item.label} color={palette.foreground} />
}
return album ? (
<AlbumTrackRow
track={item.track}
number={item.number}
album={album}
songIds={songIds}
palette={palette}
favorited={isSongFavorite(item.track.id)}
onPlay={playFromSong}
onAction={handleAlbumTrackAction}
/>
) : null
},
[
album,
handleAlbumTrackAction,
isSongFavorite,
palette,
playFromSong,
songIds,
]
)
if (album === undefined || !config || !settled) {
return ( return (
<> <>
<Stack.Screen <Stack.Screen
@@ -58,7 +110,7 @@ export default function AlbumScreen() {
headerLargeTitle: false, headerLargeTitle: false,
}} }}
/> />
<LoadingView /> <CollectionDetailSkeleton />
</> </>
) )
} }
@@ -81,17 +133,19 @@ export default function AlbumScreen() {
) )
} }
const songIds = album.tracks.map(
(track: BrowseAlbumTrack) => track.id as Id<"songs">
)
const metadata = formatMetadata(album.genre, album.year) const metadata = formatMetadata(album.genre, album.year)
const favorited = isAlbumFavorite(album.id)
return ( return (
<> <>
{isFocused ? (
<StatusBar style={palette.isDark ? "light" : "dark"} />
) : null}
<Stack.Screen <Stack.Screen
options={{ options={{
title: "", title: "",
headerLargeTitle: false, headerLargeTitle: false,
headerTintColor: palette.foreground,
headerRight: () => ( headerRight: () => (
<MediaActionMenu <MediaActionMenu
selectedCount={album.tracks.length} selectedCount={album.tracks.length}
@@ -109,7 +163,7 @@ export default function AlbumScreen() {
<Ionicons <Ionicons
name="ellipsis-horizontal" name="ellipsis-horizontal"
size={22} size={22}
color={colors.foreground} color={palette.foreground}
/> />
</Pressable> </Pressable>
</MediaActionMenu> </MediaActionMenu>
@@ -117,115 +171,201 @@ export default function AlbumScreen() {
}} }}
/> />
<FlatList <FlatList
data={album.tracks} {...longListProps}
keyExtractor={(track) => track.id} data={listItems}
style={{ flex: 1, backgroundColor }} keyExtractor={albumListItemKey}
style={{ flex: 1, backgroundColor: palette.background }}
contentContainerStyle={{ paddingBottom: contentBottomInset }} contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic" contentInsetAdjustmentBehavior="automatic"
indicatorStyle={palette.isDark ? "white" : "black"}
ListHeaderComponent={ ListHeaderComponent={
<View style={styles.hero}> <View>
<CoverImage <View style={styles.hero}>
uri={coverUri} <CoverImage
hasCover={album.cover != null} uri={coverUri}
style={styles.cover} hasCover={album.cover != null}
/> style={styles.cover}
<Text style={[styles.title, { color: colors.foreground }]}>
{album.title}
</Text>
<Pressable onPress={() => push(`/artist/${album.artist.id}`)}>
<Text style={[styles.artist, { color: colors.mutedForeground }]}>
{album.artist.name}
</Text>
</Pressable>
{metadata ? (
<Text style={{ color: colors.mutedForeground }}>{metadata}</Text>
) : null}
<View style={styles.actions}>
<Pressable
onPress={() => void toggleAlbumFavorite(album.id)}
hitSlop={8}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
>
<Ionicons
name={isAlbumFavorite(album.id) ? "star" : "star-outline"}
size={24}
color={
isAlbumFavorite(album.id)
? colors.primary
: colors.foreground
}
/>
</Pressable>
<Button
title="Play"
icon="play"
onPress={() => void playAlbum(album.id)}
style={styles.playButton}
/> />
<Pressable <Text style={[styles.title, { color: palette.foreground }]}>
accessibilityRole="button" {album.title}
accessibilityLabel="Shuffle" </Text>
hitSlop={8} <Pressable onPress={() => push(`/artist/${album.artist.id}`)}>
onPress={() => void playAlbumShuffled(album.id)} <Text style={[styles.artist, { color: palette.accentText }]}>
style={[styles.iconAction, { backgroundColor: colors.muted }]} {album.artist.name}
> </Text>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable> </Pressable>
{metadata ? (
<Text style={{ color: palette.secondaryForeground }}>
{metadata}
</Text>
) : null}
<View style={styles.actions}>
<Pressable
onPress={() => void toggleAlbumFavorite(album.id)}
hitSlop={8}
style={[
styles.iconAction,
{ backgroundColor: palette.surface },
]}
>
<Ionicons
name={favorited ? "star" : "star-outline"}
size={24}
color={favorited ? palette.accent : palette.foreground}
/>
</Pressable>
<Button
title="Play"
icon="play"
onPress={() => void playAlbum(album.id, songIds)}
style={styles.playButton}
tint={{
background: palette.accent,
foreground: palette.accentForeground,
}}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() => void playAlbumShuffled(album.id, songIds)}
style={[
styles.iconAction,
{ backgroundColor: palette.surface },
]}
>
<Ionicons
name="shuffle"
size={24}
color={palette.foreground}
/>
</Pressable>
</View>
</View> </View>
<CollectionDivider color={palette.divider} />
</View> </View>
} }
renderItem={({ item: track, index }) => ( renderItem={renderItem}
<MediaContextMenu
favorited={isSongFavorite(track.id)}
navigation={{
artist: { id: album.artist.id },
album: { id: album.id },
}}
share={{
type: "song",
albumId: album.id,
songId: track.id,
}}
onAction={(action) =>
void handleAlbumTrackAction(track, album, action)
}
>
<Pressable
style={[styles.trackRow, { borderBottomColor: colors.border }]}
onPress={() => void playFromSong(track.id, songIds)}
>
<Text
style={[styles.trackNumber, { color: colors.mutedForeground }]}
>
{track.track || index + 1}
</Text>
<View style={styles.trackMeta}>
<Text
style={[styles.trackTitle, { color: colors.foreground }]}
numberOfLines={1}
>
{track.title}
</Text>
{track.artists ? (
<Text
style={{ color: colors.mutedForeground }}
numberOfLines={1}
>
{track.artists.join(", ")}
</Text>
) : null}
</View>
<Text style={{ color: colors.mutedForeground }}>
{formatDuration(track.durationSeconds)}
</Text>
</Pressable>
</MediaContextMenu>
)}
/> />
</> </>
) )
} }
type AlbumListItem =
| { type: "disc"; key: string; label: string }
| { type: "track"; track: BrowseAlbumTrack; number: number }
/**
* Tracks arrive sorted by disc then track number. Disc headers are only
* inserted when the album spans more than one disc.
*/
function albumListItems(tracks: BrowseAlbumTrack[]): AlbumListItem[] {
const multiDisc = new Set(tracks.map((track) => track.diskNumber)).size > 1
const items: AlbumListItem[] = []
let currentDisc: number | null | undefined
let positionInDisc = 0
for (const track of tracks) {
if (track.diskNumber !== currentDisc) {
currentDisc = track.diskNumber
positionInDisc = 0
if (multiDisc) {
items.push({
type: "disc",
key: `disc-${currentDisc ?? "unknown"}`,
label: currentDisc == null ? "Other" : `Disc ${currentDisc}`,
})
}
}
positionInDisc += 1
items.push({
type: "track",
track,
number: track.track || positionInDisc,
})
}
return items
}
function albumListItemKey(item: AlbumListItem) {
return item.type === "disc" ? item.key : item.track.id
}
const AlbumTrackRow = memo(function AlbumTrackRow({
track,
number,
album,
songIds,
palette,
favorited,
onPlay,
onAction,
}: {
track: BrowseAlbumTrack
number: number
album: BrowseAlbumDetail
songIds: Id<"songs">[]
palette: CoverPalette
favorited: boolean
onPlay: (songId: Id<"songs">, songIds: Id<"songs">[]) => Promise<void>
onAction: (
track: BrowseAlbumTrack,
album: BrowseAlbumDetail,
action: MediaAction
) => Promise<void>
}) {
return (
<MediaContextMenu
favorited={favorited}
navigation={{
artist: { id: album.artist.id },
album: { id: album.id },
}}
share={{
type: "song",
albumId: album.id,
songId: track.id,
}}
onAction={(action) => void onAction(track, album, action)}
>
<Pressable
style={styles.trackRow}
onPress={() => void onPlay(track.id as Id<"songs">, songIds)}
>
<Text
style={[styles.trackNumber, { color: palette.secondaryForeground }]}
>
{number}
</Text>
<View
style={[styles.trackContent, { borderBottomColor: palette.divider }]}
>
<View style={styles.trackMeta}>
<Text
style={[styles.trackTitle, { color: palette.foreground }]}
numberOfLines={1}
>
{track.title}
</Text>
{track.artists ? (
<Text
style={{ color: palette.secondaryForeground }}
numberOfLines={1}
>
{track.artists.join(", ")}
</Text>
) : null}
</View>
<Text style={{ color: palette.secondaryForeground }}>
{formatDuration(track.durationSeconds)}
</Text>
</View>
</Pressable>
</MediaContextMenu>
)
})
const styles = StyleSheet.create({ const styles = StyleSheet.create({
empty: { flex: 1, alignItems: "center", justifyContent: "center" }, empty: { flex: 1, alignItems: "center", justifyContent: "center" },
hero: { hero: {
@@ -258,13 +398,22 @@ const styles = StyleSheet.create({
trackRow: { trackRow: {
flexDirection: "row", flexDirection: "row",
alignItems: "center", alignItems: "center",
gap: spacing.sm,
paddingLeft: collectionInset,
},
trackNumber: { width: 24, fontSize: 16, textAlign: "center" },
trackContent: {
flex: 1,
minWidth: 0,
flexDirection: "row",
alignItems: "center",
alignSelf: "stretch",
gap: spacing.md, gap: spacing.md,
minHeight: 60, minHeight: 52,
paddingHorizontal: spacing.lg,
paddingVertical: 12, paddingVertical: 12,
marginRight: collectionInset,
borderBottomWidth: StyleSheet.hairlineWidth, borderBottomWidth: StyleSheet.hairlineWidth,
}, },
trackNumber: { width: 24, textAlign: "center" },
trackMeta: { flex: 1, minWidth: 0 }, trackMeta: { flex: 1, minWidth: 0 },
trackTitle: { fontSize: 16, fontWeight: "500" }, trackTitle: { fontSize: 16, fontWeight: "500" },
}) })
@@ -1,4 +1,3 @@
import { useQuery } from "convex/react"
import { Stack, useLocalSearchParams } from "expo-router" import { Stack, useLocalSearchParams } from "expo-router"
import { Pressable, StyleSheet, Text, View } from "react-native" import { Pressable, StyleSheet, Text, View } from "react-native"
import { Ionicons } from "@expo/vector-icons" import { Ionicons } from "@expo/vector-icons"
@@ -7,11 +6,13 @@ import { CoverImage } from "@/components/cover-image"
import { MediaGridList } from "@/components/media-cards" import { MediaGridList } from "@/components/media-cards"
import { MediaActionMenu } from "@/components/media-actions-sheet" import { MediaActionMenu } from "@/components/media-actions-sheet"
import { Button, LoadingView } from "@/components/ui/primitives" import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player" import { contentBottomInset } from "@/components/player"
import { useFavorites } from "@/contexts/favorites" import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback" import { usePlaybackActions } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config" import { useServerConfig } from "@/contexts/server-config"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
@@ -22,7 +23,7 @@ export default function ArtistScreen() {
const { id } = useLocalSearchParams<{ id: string }>() const { id } = useLocalSearchParams<{ id: string }>()
const colors = useThemeColors() const colors = useThemeColors()
const { config } = useServerConfig() const { config } = useServerConfig()
const data = useQuery( const data = useCachedQuery(
api.library.browseArtistDetail, api.library.browseArtistDetail,
typeof id === "string" ? { id: id as Id<"artists"> } : "skip" typeof id === "string" ? { id: id as Id<"artists"> } : "skip"
) )
@@ -40,7 +41,7 @@ export default function ArtistScreen() {
headerLargeTitle: false, headerLargeTitle: false,
}} }}
/> />
<LoadingView /> <CollectionDetailSkeleton round />
</> </>
) )
} }
@@ -1,10 +1,13 @@
import { usePaginatedQuery, useQuery } from "convex/react"
import { Stack } from "expo-router" import { Stack } from "expo-router"
import { useCallback } from "react" import { useCallback } from "react"
import { MediaGridList } from "@/components/media-cards" import { MediaGridList } from "@/components/media-cards"
import { LoadingView } from "@/components/ui/primitives" import { MediaGridSkeleton } from "@/components/skeletons"
import { contentBottomInset } from "@/components/player" import { contentBottomInset } from "@/components/player"
import {
useCachedPaginatedQuery,
useCachedQuery,
} from "@/hooks/use-cached-query"
import { useDebouncedSearch } from "@/hooks/use-debounced-search" import { useDebouncedSearch } from "@/hooks/use-debounced-search"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
@@ -12,16 +15,20 @@ const PAGE_SIZE = 50
export default function AlbumsScreen() { export default function AlbumsScreen() {
const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch() const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch()
const { results, status, loadMore } = usePaginatedQuery( const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
api.library.browseAlbumsPaginated, api.library.browseAlbumsPaginated,
{}, {},
{ initialNumItems: PAGE_SIZE } { initialNumItems: PAGE_SIZE }
) )
const searchResults = useQuery( const searchResults = useCachedQuery(
api.library.searchLibrary, api.library.searchLibrary,
searchQuery ? { query: searchQuery } : "skip" searchQuery ? { query: searchQuery } : "skip"
) )
const albums = searchQuery ? searchResults?.albums : results const albums = searchQuery
? searchResults?.albums
: status === "LoadingFirstPage" && !isCached
? undefined
: results
const handleChangeText = useCallback( const handleChangeText = useCallback(
(event: { nativeEvent: { text: string } }) => { (event: { nativeEvent: { text: string } }) => {
@@ -46,7 +53,7 @@ export default function AlbumsScreen() {
return ( return (
<> <>
{searchBar} {searchBar}
<LoadingView /> <MediaGridSkeleton />
</> </>
) )
} }
@@ -1,19 +1,32 @@
import { Ionicons } from "@expo/vector-icons" import { Ionicons } from "@expo/vector-icons"
import { usePaginatedQuery, useQuery } from "convex/react"
import { Stack } from "expo-router" import { Stack } from "expo-router"
import { useCallback } from "react" import { memo, useCallback } from "react"
import { FlatList, Pressable, StyleSheet, Text } from "react-native" import {
FlatList,
Pressable,
StyleSheet,
Text,
type ListRenderItemInfo,
} from "react-native"
import { MediaContextMenu } from "@/components/media-context-menu" import {
MediaContextMenu,
type MediaAction,
} from "@/components/media-context-menu"
import { CoverImage } from "@/components/cover-image" import { CoverImage } from "@/components/cover-image"
import { LoadingView } from "@/components/ui/primitives" import { ArtistListSkeleton } from "@/components/skeletons"
import { contentBottomInset } from "@/components/player" import { contentBottomInset } from "@/components/player"
import { useServerConfig } from "@/contexts/server-config" import { useServerConfig } from "@/contexts/server-config"
import {
useCachedPaginatedQuery,
useCachedQuery,
} from "@/hooks/use-cached-query"
import { useDebouncedSearch } from "@/hooks/use-debounced-search" import { useDebouncedSearch } from "@/hooks/use-debounced-search"
import { useAppNavigation } from "@/lib/app-navigation" import { useAppNavigation } from "@/lib/app-navigation"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import type { BrowseArtist } from "@otunes/convex/types" import type { BrowseArtist } from "@otunes/convex/types"
import { longListProps } from "@/lib/list"
import { artistCoverUrl } from "@/lib/urls" import { artistCoverUrl } from "@/lib/urls"
import { spacing, useThemeColors } from "@/lib/theme" import { spacing, useThemeColors } from "@/lib/theme"
@@ -24,17 +37,39 @@ export default function ArtistsScreen() {
const colors = useThemeColors() const colors = useThemeColors()
const { config } = useServerConfig() const { config } = useServerConfig()
const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch() const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch()
const { results, status, loadMore } = usePaginatedQuery( const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
api.library.browseArtistsPaginated, api.library.browseArtistsPaginated,
{}, {},
{ initialNumItems: PAGE_SIZE } { initialNumItems: PAGE_SIZE }
) )
const searchResults = useQuery( const searchResults = useCachedQuery(
api.library.searchLibrary, api.library.searchLibrary,
searchQuery ? { query: searchQuery } : "skip" searchQuery ? { query: searchQuery } : "skip"
) )
const { handleArtistAction, isArtistFavorite } = useMediaMenuActions() const { handleArtistAction, isArtistFavorite } = useMediaMenuActions()
const artists = searchQuery ? searchResults?.artists : results const artists = searchQuery
? searchResults?.artists
: status === "LoadingFirstPage" && !isCached
? undefined
: results
const serverUrl = config?.serverUrl ?? ""
const handleOpenArtist = useCallback(
(artistId: string) => push(`/artist/${artistId}`),
[push]
)
const renderItem = useCallback(
({ item: artist }: ListRenderItemInfo<BrowseArtist>) => (
<ArtistRow
artist={artist}
serverUrl={serverUrl}
favorited={isArtistFavorite(artist.id)}
onOpen={handleOpenArtist}
onAction={handleArtistAction}
/>
),
[handleArtistAction, handleOpenArtist, isArtistFavorite, serverUrl]
)
const handleChangeText = useCallback( const handleChangeText = useCallback(
(event: { nativeEvent: { text: string } }) => { (event: { nativeEvent: { text: string } }) => {
@@ -59,7 +94,7 @@ export default function ArtistsScreen() {
return ( return (
<> <>
{searchBar} {searchBar}
<LoadingView /> <ArtistListSkeleton />
</> </>
) )
} }
@@ -69,46 +104,70 @@ export default function ArtistsScreen() {
{searchBar} {searchBar}
<FlatList <FlatList
{...longListProps}
data={artists} data={artists}
keyExtractor={(artist) => artist.id} keyExtractor={artistKey}
renderItem={renderItem}
style={{ flex: 1, backgroundColor: colors.background }} style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{ paddingBottom: contentBottomInset }} contentContainerStyle={styles.listContent}
contentInsetAdjustmentBehavior="automatic" contentInsetAdjustmentBehavior="automatic"
onEndReached={() => { onEndReached={() => {
if (!searchQuery && status === "CanLoadMore") loadMore(PAGE_SIZE) if (!searchQuery && status === "CanLoadMore") loadMore(PAGE_SIZE)
}} }}
onEndReachedThreshold={0.5} onEndReachedThreshold={0.5}
renderItem={({ item: artist }: { item: BrowseArtist }) => (
<MediaContextMenu
favorited={isArtistFavorite(artist.id)}
share={{ type: "artist", artistId: artist.id }}
onAction={(action) => void handleArtistAction(artist, action)}
>
<Pressable
style={[styles.row, { borderBottomColor: colors.border }]}
onPress={() => push(`/artist/${artist.id}`)}
>
<CoverImage
uri={artistCoverUrl(config.serverUrl, artist.id)}
hasCover={artist.photo != null}
style={styles.avatar}
/>
<Text
style={[styles.name, { color: colors.foreground }]}
numberOfLines={1}
>
{artist.name}
</Text>
<Ionicons name="chevron-forward" size={16} color={colors.mutedForeground} />
</Pressable>
</MediaContextMenu>
)}
/> />
</> </>
) )
} }
function artistKey(artist: BrowseArtist) {
return artist.id
}
const ArtistRow = memo(function ArtistRow({
artist,
serverUrl,
favorited,
onOpen,
onAction,
}: {
artist: BrowseArtist
serverUrl: string
favorited: boolean
onOpen: (artistId: string) => void
onAction: (artist: BrowseArtist, action: MediaAction) => Promise<void>
}) {
const colors = useThemeColors()
return (
<MediaContextMenu
favorited={favorited}
share={{ type: "artist", artistId: artist.id }}
onAction={(action) => void onAction(artist, action)}
>
<Pressable
style={[styles.row, { borderBottomColor: colors.border }]}
onPress={() => onOpen(artist.id)}
>
<CoverImage
uri={artistCoverUrl(serverUrl, artist.id)}
hasCover={artist.photo != null}
style={styles.avatar}
/>
<Text
style={[styles.name, { color: colors.foreground }]}
numberOfLines={1}
>
{artist.name}
</Text>
<Ionicons name="chevron-forward" size={16} color={colors.mutedForeground} />
</Pressable>
</MediaContextMenu>
)
})
const styles = StyleSheet.create({ const styles = StyleSheet.create({
listContent: { paddingBottom: contentBottomInset },
row: { row: {
flexDirection: "row", flexDirection: "row",
alignItems: "center", alignItems: "center",
@@ -1,9 +1,9 @@
import { useQuery } from "convex/react"
import { Pressable } from "react-native" import { Pressable } from "react-native"
import { MediaGridList } from "@/components/media-cards" import { MediaGridList } from "@/components/media-cards"
import { LoadingView } from "@/components/ui/primitives" import { MediaGridSkeleton } from "@/components/skeletons"
import { tabContentBottomInset } from "@/components/player" import { tabContentBottomInset } from "@/components/player"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import { useThemeColors } from "@/lib/theme" import { useThemeColors } from "@/lib/theme"
import { Ionicons } from "@expo/vector-icons" import { Ionicons } from "@expo/vector-icons"
@@ -13,7 +13,7 @@ import { useAddToPlaylist } from "@/contexts/add-to-playlist"
export default function PlaylistsTabScreen() { export default function PlaylistsTabScreen() {
const colors = useThemeColors() const colors = useThemeColors()
const playlists = useQuery(api.playlists.listAllPlaylists) const playlists = useCachedQuery(api.playlists.listAllPlaylists)
const { openCreatePlaylist } = useAddToPlaylist() const { openCreatePlaylist } = useAddToPlaylist()
if (playlists === undefined) { if (playlists === undefined) {
@@ -38,7 +38,7 @@ export default function PlaylistsTabScreen() {
), ),
}} }}
/> />
<LoadingView /> <MediaGridSkeleton />
</> </>
) )
} }
@@ -1,17 +1,21 @@
import { usePaginatedQuery, useQuery } from "convex/react"
import { Stack } from "expo-router" import { Stack } from "expo-router"
import { useCallback, useState } from "react" import { useCallback, useState } from "react"
import { FlatList, StyleSheet } from "react-native" import { FlatList, StyleSheet, type ListRenderItemInfo } from "react-native"
import { contentBottomInset, SongRow } from "@/components/player" import type { MediaAction } from "@/components/media-context-menu"
import { LoadingView } from "@/components/ui/primitives" import { contentBottomInset, SongListRow } from "@/components/player"
import { SongListSkeleton } from "@/components/skeletons"
import { useFavorites } from "@/contexts/favorites" import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback" import { usePlaybackActions } from "@/contexts/playback"
import {
useCachedPaginatedQuery,
useCachedQuery,
} from "@/hooks/use-cached-query"
import { useDebouncedSearch } from "@/hooks/use-debounced-search" import { useDebouncedSearch } from "@/hooks/use-debounced-search"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { BrowseSong } from "@otunes/convex/types"
import { spacing } from "@/lib/theme" import { longListProps } from "@/lib/list"
const PAGE_SIZE = 50 const PAGE_SIZE = 50
@@ -23,16 +27,42 @@ export default function SongsScreen() {
const [sortKey, setSortKey] = useState<"title" | "artist" | "album">("title") const [sortKey, setSortKey] = useState<"title" | "artist" | "album">("title")
const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc") const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc")
const { results, status, loadMore } = usePaginatedQuery( const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
api.library.browseSongsPaginated, api.library.browseSongsPaginated,
{ sortKey, sortDirection }, { sortKey, sortDirection },
{ initialNumItems: PAGE_SIZE } { initialNumItems: PAGE_SIZE }
) )
const searchResults = useQuery( const searchResults = useCachedQuery(
api.library.searchLibrary, api.library.searchLibrary,
searchQuery ? { query: searchQuery } : "skip" searchQuery ? { query: searchQuery } : "skip"
) )
const songs = searchQuery ? searchResults?.songs : results const songs = searchQuery
? searchResults?.songs
: status === "LoadingFirstPage" && !isCached
? undefined
: results
const handlePlaySong = useCallback(
(song: BrowseSong) =>
void playFromLibrarySong(song.id, { sortKey, sortDirection }),
[playFromLibrarySong, sortDirection, sortKey]
)
const handleSongMenuAction = useCallback(
(song: BrowseSong, action: MediaAction) =>
void handleSongAction(song, action),
[handleSongAction]
)
const renderItem = useCallback(
({ item }: ListRenderItemInfo<BrowseSong>) => (
<SongListRow
song={item}
favorited={isSongFavorite(item.id)}
onPlay={handlePlaySong}
onAction={handleSongMenuAction}
/>
),
[handlePlaySong, handleSongMenuAction, isSongFavorite]
)
const handleChangeText = useCallback( const handleChangeText = useCallback(
(event: { nativeEvent: { text: string } }) => { (event: { nativeEvent: { text: string } }) => {
@@ -57,7 +87,7 @@ export default function SongsScreen() {
return ( return (
<> <>
{searchBar} {searchBar}
<LoadingView /> <SongListSkeleton />
</> </>
) )
} }
@@ -67,49 +97,25 @@ export default function SongsScreen() {
{searchBar} {searchBar}
<FlatList <FlatList
{...longListProps}
data={songs} data={songs}
keyExtractor={(item) => item.id} keyExtractor={songKey}
contentContainerStyle={{ paddingBottom: contentBottomInset }} renderItem={renderItem}
contentContainerStyle={styles.listContent}
contentInsetAdjustmentBehavior="automatic" contentInsetAdjustmentBehavior="automatic"
onEndReached={() => { onEndReached={() => {
if (!searchQuery && status === "CanLoadMore") loadMore(PAGE_SIZE) if (!searchQuery && status === "CanLoadMore") loadMore(PAGE_SIZE)
}} }}
onEndReachedThreshold={0.5} onEndReachedThreshold={0.5}
renderItem={({ item }) => (
<SongRow
song={item}
onPress={() =>
void playFromLibrarySong(item.id as Id<"songs">, {
sortKey,
sortDirection,
})
}
contextMenu={{
favorited: isSongFavorite(item.id),
navigation: {
artist: { id: item.artist.id },
album: { id: item.album.id },
},
share: {
type: "song",
albumId: item.album.id,
songId: item.id,
},
onAction: (action) => void handleSongAction(item, action),
}}
/>
)}
/> />
</> </>
) )
} }
function songKey(song: BrowseSong) {
return song.id
}
const styles = StyleSheet.create({ const styles = StyleSheet.create({
sortRow: { listContent: { paddingBottom: contentBottomInset },
flexDirection: "row",
justifyContent: "space-around",
paddingVertical: spacing.sm,
borderBottomWidth: StyleSheet.hairlineWidth,
},
sortButton: { padding: spacing.sm },
}) })
+12 -20
View File
@@ -1,10 +1,10 @@
import { usePaginatedQuery } from "convex/react" import { memo } from "react"
import { memo, useRef } from "react"
import { ScrollView, StyleSheet } from "react-native" import { ScrollView, StyleSheet } from "react-native"
import { ContentCarousel } from "@/components/media-cards" import { ContentCarousel } from "@/components/media-cards"
import { LoadingView } from "@/components/ui/primitives" import { HomeSkeleton } from "@/components/skeletons"
import { tabContentBottomInset } from "@/components/player" import { tabContentBottomInset } from "@/components/player"
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import type { BrowseAlbum, PlaylistSummary } from "@otunes/convex/types" import type { BrowseAlbum, PlaylistSummary } from "@otunes/convex/types"
import { spacing, useThemeColors } from "@/lib/theme" import { spacing, useThemeColors } from "@/lib/theme"
@@ -38,34 +38,26 @@ const HomeCarousels = memo(function HomeCarousels({
export default function HomeScreen() { export default function HomeScreen() {
const colors = useThemeColors() const colors = useThemeColors()
const { results: recentlyAdded } = usePaginatedQuery( const recentlyAdded = useCachedPaginatedQuery(
api.library.browseRecentlyAddedPaginated, api.library.browseRecentlyAddedPaginated,
{}, {},
{ initialNumItems: CAROUSEL_ITEM_LIMIT } { initialNumItems: CAROUSEL_ITEM_LIMIT }
) )
const { results: recentlyPlayed } = usePaginatedQuery( const recentlyPlayed = useCachedPaginatedQuery(
api.library.browseRecentlyPlayedPaginated, api.library.browseRecentlyPlayedPaginated,
{}, {},
{ initialNumItems: CAROUSEL_ITEM_LIMIT } { initialNumItems: CAROUSEL_ITEM_LIMIT }
) )
const cachedData = useRef<{
recentlyAdded?: BrowseAlbum[]
recentlyPlayed?: (BrowseAlbum | PlaylistSummary)[]
}>({})
if (recentlyAdded !== undefined) { const isLoading = [recentlyAdded, recentlyPlayed].some(
cachedData.current.recentlyAdded = recentlyAdded (result) => result.status === "LoadingFirstPage" && !result.isCached
} )
if (recentlyPlayed !== undefined) { if (isLoading) {
cachedData.current.recentlyPlayed = recentlyPlayed return <HomeSkeleton />
} }
const added = recentlyAdded ?? cachedData.current.recentlyAdded const added = recentlyAdded.results.slice(0, CAROUSEL_ITEM_LIMIT)
const played = recentlyPlayed ?? cachedData.current.recentlyPlayed const played = recentlyPlayed.results.slice(0, CAROUSEL_ITEM_LIMIT)
if (added === undefined || played === undefined) {
return <LoadingView />
}
return ( return (
<ScrollView <ScrollView
@@ -1,24 +1,12 @@
import { useMutation, usePaginatedQuery, useQuery } from "convex/react" import { useMutation } from "convex/react"
import { memo, useCallback, useEffect, useMemo } from "react"
import { import {
Button as SwiftUIButton, Stack,
ContextMenu, useIsFocused,
Host, useLocalSearchParams,
List, useRouter,
RNHostView, } from "expo-router"
SwipeActions, import { StatusBar } from "expo-status-bar"
} from "@expo/ui/swift-ui"
import {
frame,
listRowBackground,
listRowInsets,
listRowSeparator,
listSectionSpacing,
listRowSpacing,
listStyle,
onAppear,
scrollContentBackground,
} from "@expo/ui/swift-ui/modifiers"
import { Stack, useLocalSearchParams, useRouter } from "expo-router"
import { import {
FlatList, FlatList,
Platform, Platform,
@@ -26,41 +14,63 @@ import {
StyleSheet, StyleSheet,
Text, Text,
View, View,
type ListRenderItemInfo,
} from "react-native" } from "react-native"
import ReanimatedSwipeable from "react-native-gesture-handler/ReanimatedSwipeable" import ReanimatedSwipeable from "react-native-gesture-handler/ReanimatedSwipeable"
import { Ionicons } from "@expo/vector-icons" import { Ionicons } from "@expo/vector-icons"
import { CollectionDivider } from "@/components/collection-list"
import { CoverImage } from "@/components/cover-image" import { CoverImage } from "@/components/cover-image"
import {
SwipeToRemoveRow,
useSwipeRowGroup,
type SwipeRowGroup,
} from "@/components/ios-swipe-to-remove-row"
import { import {
MediaActionMenu, MediaActionMenu,
type MediaAction, type MediaAction,
} from "@/components/media-actions-sheet" } from "@/components/media-actions-sheet"
import { Button, LoadingView } from "@/components/ui/primitives" import { CollectionDetailSkeleton } from "@/components/skeletons"
import { contentBottomInset, SongRow } from "@/components/player" import { Button } from "@/components/ui/primitives"
import { contentBottomInset, SongListRow } from "@/components/player"
import { useFavorites } from "@/contexts/favorites" import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback" import { usePlaybackActions } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config" import { useServerConfig } from "@/contexts/server-config"
import { useCoverBackgroundColor } from "@/hooks/use-cover-background-color" import {
useCachedPaginatedQuery,
useCachedQuery,
} from "@/hooks/use-cached-query"
import { useCoverPalette } from "@/hooks/use-cover-palette"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong } from "@otunes/convex/types" import type { BrowsePlaylistDetail, BrowseSong } from "@otunes/convex/types"
import { shareMediaLink } from "@/lib/share-media-link" import type { CoverPalette } from "@/lib/cover-palette"
import { longListProps } from "@/lib/list"
import { rememberSongs } from "@/lib/song-cache"
import { showError, showSuccess } from "@/lib/toast" import { showError, showSuccess } from "@/lib/toast"
import { playlistCoverUrl } from "@/lib/urls" import { playlistCoverUrl } from "@/lib/urls"
import { radius, spacing, useThemeColors } from "@/lib/theme" import { radius, spacing, useThemeColors } from "@/lib/theme"
const PAGE_SIZE = 50 const PAGE_SIZE = 50
const NATIVE_LOAD_MORE_THRESHOLD = 10 const PLAYLIST_LABEL = "Add to Another Playlist"
const OWNER_MENU_ACTIONS: MediaAction[] = [
"share",
"playlist",
"play-next",
"play-last",
"shuffle",
"favorite",
"delete-playlist",
]
export default function PlaylistScreen() { export default function PlaylistScreen() {
const { id } = useLocalSearchParams<{ id: string }>() const { id } = useLocalSearchParams<{ id: string }>()
const router = useRouter()
const colors = useThemeColors() const colors = useThemeColors()
const { config } = useServerConfig() const { config } = useServerConfig()
const playlistId = typeof id === "string" ? (id as Id<"playlists">) : null const playlistId = typeof id === "string" ? (id as Id<"playlists">) : null
const playlist = useQuery( const playlist = useCachedQuery(
api.playlists.browsePlaylistDetail, api.playlists.browsePlaylistDetail,
playlistId playlistId
? { ? {
@@ -73,38 +83,34 @@ export default function PlaylistScreen() {
results: songs, results: songs,
status, status,
loadMore, loadMore,
} = usePaginatedQuery( isCached,
} = useCachedPaginatedQuery(
api.playlists.browsePlaylistSongsPaginated, api.playlists.browsePlaylistSongsPaginated,
playlistId ? { id: playlistId } : "skip", playlistId ? { id: playlistId } : "skip",
{ initialNumItems: PAGE_SIZE } { initialNumItems: PAGE_SIZE }
) )
const allSongIds = useQuery( const allSongIds = useCachedQuery(
api.playlists.getPlaylistSongIds, api.playlists.getPlaylistSongIds,
playlistId ? { playlistId } : "skip" playlistId ? { playlistId } : "skip"
) )
const { playPlaylist, playPlaylistShuffled, playFromSong } =
usePlaybackActions()
const { isSongFavorite } = useFavorites()
const { handleSongAction, handlePlaylistDetailAction } = useMediaMenuActions()
const subscribe = useMutation(api.playlists.subscribeToPlaylist)
const unsubscribe = useMutation(api.playlists.unsubscribeFromPlaylist)
const deletePlaylist = useMutation(api.playlists.deletePlaylist)
const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist)
const coverUri = const coverUri =
config && playlist config && playlistId
? playlistCoverUrl(config.serverUrl, playlist.id ?? "favorites") ? playlistCoverUrl(config.serverUrl, playlist?.id ?? playlistId)
: "" : ""
const backgroundColor = useCoverBackgroundColor( const { palette, settled } = useCoverPalette(
coverUri, coverUri,
playlist?.cover != null, playlist ? playlist.cover != null : playlist === null ? false : undefined
colors.background
) )
useEffect(() => {
rememberSongs(songs)
}, [songs])
if ( if (
playlist === undefined || playlist === undefined ||
songs === undefined || (status === "LoadingFirstPage" && !isCached) ||
allSongIds === undefined || !config ||
!config !settled
) { ) {
return ( return (
<> <>
@@ -114,7 +120,7 @@ export default function PlaylistScreen() {
headerLargeTitle: false, headerLargeTitle: false,
}} }}
/> />
<LoadingView /> <CollectionDetailSkeleton />
</> </>
) )
} }
@@ -137,21 +143,99 @@ export default function PlaylistScreen() {
) )
} }
const songIds = allSongIds return (
const serverUrl = config.serverUrl <PlaylistContent
playlist={playlist}
songs={songs}
allSongIds={allSongIds}
coverUri={coverUri}
palette={palette}
onEndReached={() => {
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
/>
)
}
function maybeLoadMore() { function PlaylistContent({
if (status === "CanLoadMore") loadMore(PAGE_SIZE) playlist,
} songs,
allSongIds,
coverUri,
palette,
onEndReached,
}: {
playlist: BrowsePlaylistDetail
songs: BrowseSong[]
allSongIds: Id<"songs">[] | undefined
coverUri: string
palette: CoverPalette
onEndReached: () => void
}) {
const router = useRouter()
const isFocused = useIsFocused()
const { playPlaylist, playPlaylistShuffled, playFromSong } =
usePlaybackActions()
const { isSongFavorite } = useFavorites()
const { handleSongAction, handlePlaylistDetailAction } = useMediaMenuActions()
const subscribe = useMutation(api.playlists.subscribeToPlaylist)
const unsubscribe = useMutation(api.playlists.unsubscribeFromPlaylist)
const deletePlaylist = useMutation(api.playlists.deletePlaylist)
const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist)
async function handleSubscribeToggle() { const playlistId = playlist.id
if (!playlist?.id) return const isSubscribed = playlist.isSubscribed
const canEdit = playlist.isOwner && playlistId !== null
const loadedSongIds = useMemo(() => songs.map((song) => song.id), [songs])
const songIds = allSongIds ?? loadedSongIds
const swipeGroup = useSwipeRowGroup()
const handlePlaySong = useCallback(
(song: BrowseSong) => void playFromSong(song.id, songIds),
[playFromSong, songIds]
)
const handleSongMenuAction = useCallback(
(song: BrowseSong, action: MediaAction) =>
void handleSongAction(song, action),
[handleSongAction]
)
const handleRemoveSong = useCallback(
async (songId: Id<"songs">) => {
if (!playlistId) return false
try {
await removeSongs({ playlistId, songIds: [songId] })
showSuccess("Removed from playlist")
return true
} catch (error) {
showError(
error instanceof Error
? error.message
: "Failed to remove from playlist"
)
return false
}
},
[playlistId, removeSongs]
)
const handlePlay = useCallback(() => {
if (playlistId) void playPlaylist(playlistId, allSongIds)
}, [allSongIds, playPlaylist, playlistId])
const handleShuffle = useCallback(() => {
if (playlistId) void playPlaylistShuffled(playlistId, allSongIds)
}, [allSongIds, playPlaylistShuffled, playlistId])
const handleSubscribeToggle = useCallback(async () => {
if (!playlistId) return
try { try {
if (playlist.isSubscribed) { if (isSubscribed) {
await unsubscribe({ playlistId: playlist.id }) await unsubscribe({ playlistId })
showSuccess("Unsubscribed") showSuccess("Unsubscribed")
} else { } else {
await subscribe({ playlistId: playlist.id }) await subscribe({ playlistId })
showSuccess("Subscribed") showSuccess("Subscribed")
} }
} catch (error) { } catch (error) {
@@ -159,318 +243,222 @@ export default function PlaylistScreen() {
error instanceof Error ? error.message : "Failed to update subscription" error instanceof Error ? error.message : "Failed to update subscription"
) )
} }
} }, [isSubscribed, playlistId, subscribe, unsubscribe])
async function handleDelete() { const screenOptions = useMemo(() => {
if (!playlist?.id) return async function handleDelete() {
try { if (!playlistId) return
await deletePlaylist({ playlistId: playlist.id }) try {
showSuccess("Playlist deleted") await deletePlaylist({ playlistId })
router.back() showSuccess("Playlist deleted")
} catch (error) { router.back()
showError( } catch (error) {
error instanceof Error ? error.message : "Failed to delete playlist" showError(
) error instanceof Error ? error.message : "Failed to delete playlist"
} )
} }
function handlePlaylistMenuAction(action: MediaAction) {
if (action === "delete-playlist") {
void handleDelete()
return
} }
void handlePlaylistDetailAction(songIds, action) function handlePlaylistMenuAction(action: MediaAction) {
} if (action === "delete-playlist") {
void handleDelete()
return
}
async function handleRemoveSong(songId: Id<"songs">) { void handlePlaylistDetailAction(songIds, action)
if (!playlist?.id) return
try {
await removeSongs({ playlistId: playlist.id, songIds: [songId] })
showSuccess("Removed from playlist")
} catch (error) {
showError(
error instanceof Error
? error.message
: "Failed to remove from playlist"
)
} }
}
function renderSongRow(song: BrowseSong, includeContextMenu = true) { return {
const row = ( title: "",
<SongRow headerLargeTitle: false,
headerTintColor: palette.foreground,
headerRight: () => (
<MediaActionMenu
selectedCount={songIds.length}
playlistLabel={PLAYLIST_LABEL}
share={{
type: "playlist",
playlistId: playlistId ?? "favorites",
}}
includeActions={canEdit ? OWNER_MENU_ACTIONS : undefined}
onAction={handlePlaylistMenuAction}
>
<Pressable hitSlop={8}>
<Ionicons
name="ellipsis-horizontal"
size={22}
color={palette.foreground}
/>
</Pressable>
</MediaActionMenu>
),
}
}, [
canEdit,
deletePlaylist,
handlePlaylistDetailAction,
palette.foreground,
playlistId,
router,
songIds,
])
const renderItem = useCallback(
({ item: song }: ListRenderItemInfo<BrowseSong>) => (
<PlaylistSongRow
song={song} song={song}
onPress={() => void playFromSong(song.id, songIds)} favorited={isSongFavorite(song.id)}
contextMenu={ removable={canEdit}
includeContextMenu palette={palette}
? { swipeGroup={swipeGroup}
favorited: isSongFavorite(song.id), onPlay={handlePlaySong}
playlistLabel: "Add to Another Playlist", onAction={handleSongMenuAction}
navigation: { onRemove={handleRemoveSong}
artist: { id: song.artist.id },
album: { id: song.album.id },
},
share: {
type: "song",
albumId: song.album.id,
songId: song.id,
},
onAction: (action) => void handleSongAction(song, action),
}
: undefined
}
/> />
) ),
[
return row canEdit,
} handlePlaySong,
handleRemoveSong,
function renderNativeSongContextMenu(song: BrowseSong) { handleSongMenuAction,
return ( isSongFavorite,
<ContextMenu.Items> palette,
<SwiftUIButton swipeGroup,
label="Share" ]
systemImage="square.and.arrow.up" )
onPress={() =>
void shareMediaLink(serverUrl, {
type: "song",
albumId: song.album.id,
songId: song.id,
})
}
/>
<SwiftUIButton
label="Add to Another Playlist"
systemImage="text.badge.plus"
onPress={() => void handleSongAction(song, "playlist")}
/>
<SwiftUIButton
label="Play Next"
systemImage="text.line.first.and.arrowtriangle.forward"
onPress={() => void handleSongAction(song, "play-next")}
/>
<SwiftUIButton
label="Play Last"
systemImage="text.line.last.and.arrowtriangle.forward"
onPress={() => void handleSongAction(song, "play-last")}
/>
<SwiftUIButton
label="Shuffle"
systemImage="shuffle"
onPress={() => void handleSongAction(song, "shuffle")}
/>
<SwiftUIButton
label="Go to Artist"
systemImage="person"
onPress={() => void handleSongAction(song, "go-artist")}
/>
<SwiftUIButton
label="Go to Album"
systemImage="opticaldisc"
onPress={() => void handleSongAction(song, "go-album")}
/>
<SwiftUIButton
label={isSongFavorite(song.id) ? "Unfavorite" : "Favorite"}
systemImage={isSongFavorite(song.id) ? "star.fill" : "star"}
onPress={() => void handleSongAction(song, "favorite")}
/>
</ContextMenu.Items>
)
}
const nativeListRowModifiers = [
listRowBackground(backgroundColor),
listRowInsets({ top: 0, leading: 0, bottom: 0, trailing: 0 }),
listRowSeparator("hidden"),
]
const nativeSongRowModifiers = [frame({ height: 32 })]
const shouldUseNativeSwipeList =
Platform.OS === "ios" && playlist.isOwner && playlist.id
return ( return (
<> <>
<Stack.Screen {isFocused ? (
options={{ <StatusBar style={palette.isDark ? "light" : "dark"} />
title: "", ) : null}
headerLargeTitle: false, <Stack.Screen options={screenOptions} />
headerRight: () => ( <FlatList
<MediaActionMenu {...longListProps}
selectedCount={songIds.length} data={songs}
playlistLabel="Add to Another Playlist" keyExtractor={songKey}
share={{ renderItem={renderItem}
type: "playlist", style={{ flex: 1, backgroundColor: palette.background }}
playlistId: playlist.id ?? "favorites", indicatorStyle={palette.isDark ? "white" : "black"}
}} contentContainerStyle={styles.listContent}
includeActions={ contentInsetAdjustmentBehavior="automatic"
playlist.isOwner && playlist.id onEndReached={onEndReached}
? [ onEndReachedThreshold={0.5}
"share", onScrollBeginDrag={swipeGroup.closeOpenRow}
"playlist", ListHeaderComponent={
"play-next", <PlaylistHero
"play-last", coverUri={coverUri}
"shuffle", hasCover={playlist.cover != null}
"favorite", title={playlist.title}
"delete-playlist", ownerName={playlist.owner.name}
] palette={palette}
: undefined isSubscribed={isSubscribed}
} showSubscribe={!playlist.isOwner && playlistId !== null}
onAction={handlePlaylistMenuAction} onSubscribeToggle={handleSubscribeToggle}
> onPlay={handlePlay}
<Pressable hitSlop={8}> onShuffle={handleShuffle}
<Ionicons />
name="ellipsis-horizontal" }
size={22}
color={colors.foreground}
/>
</Pressable>
</MediaActionMenu>
),
}}
/> />
{shouldUseNativeSwipeList ? (
<Host style={[styles.iosSwipeListHost, { backgroundColor }]}>
<List
modifiers={[
listStyle("plain"),
listSectionSpacing(0),
listRowSpacing(0),
scrollContentBackground("hidden"),
]}
>
<SwipeActions modifiers={nativeListRowModifiers}>
<RNHostView matchContents>
<PlaylistHero
coverUri={coverUri}
hasCover={playlist.cover != null}
title={playlist.title}
ownerName={playlist.owner.name}
colors={colors}
onPlay={() => playlist.id && void playPlaylist(playlist.id)}
onShuffle={() =>
playlist.id && void playPlaylistShuffled(playlist.id)
}
/>
</RNHostView>
</SwipeActions>
{songs.map((song, index) => {
const nearEnd = index >= songs.length - NATIVE_LOAD_MORE_THRESHOLD
return (
<SwipeActions
key={song.id}
modifiers={[
...nativeSongRowModifiers,
...(nearEnd ? [onAppear(maybeLoadMore)] : []),
]}
>
<ContextMenu>
<ContextMenu.Trigger>
<RNHostView matchContents>
<View style={styles.nativeSongRow}>
{renderSongRow(song, false)}
</View>
</RNHostView>
</ContextMenu.Trigger>
{renderNativeSongContextMenu(song)}
</ContextMenu>
<SwipeActions.Actions edge="trailing">
<SwiftUIButton
label=""
systemImage="minus.circle.fill"
role="destructive"
onPress={() => void handleRemoveSong(song.id)}
/>
</SwipeActions.Actions>
</SwipeActions>
)
})}
</List>
</Host>
) : (
<FlatList
data={songs}
keyExtractor={(song) => song.id}
style={{ flex: 1, backgroundColor }}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
onEndReached={maybeLoadMore}
onEndReachedThreshold={0.5}
ListHeaderComponent={
<PlaylistHero
coverUri={coverUri}
hasCover={playlist.cover != null}
title={playlist.title}
ownerName={playlist.owner.name}
colors={colors}
isSubscribed={playlist.isSubscribed}
showSubscribe={!playlist.isOwner && !!playlist.id}
onSubscribeToggle={() => void handleSubscribeToggle()}
onPlay={() => playlist.id && void playPlaylist(playlist.id)}
onShuffle={() =>
playlist.id && void playPlaylistShuffled(playlist.id)
}
/>
}
renderItem={({ item: song }) => {
const row = renderSongRow(song)
if (!playlist.isOwner || !playlist.id) {
return <View>{row}</View>
}
return (
<ReanimatedSwipeable
friction={2}
rightThreshold={56}
overshootRight={false}
enableTrackpadTwoFingerGesture
containerStyle={{ backgroundColor: colors.destructive }}
childrenContainerStyle={{ backgroundColor }}
renderRightActions={(_progress, _translation, swipeable) => (
<Pressable
accessibilityRole="button"
accessibilityLabel={`Remove ${song.title} from playlist`}
onPress={() => {
swipeable.close()
void handleRemoveSong(song.id)
}}
style={[
styles.removeAction,
{ backgroundColor: colors.destructive },
]}
>
<Ionicons
name="trash"
size={22}
color={colors.primaryForeground}
/>
<Text
style={[
styles.removeActionText,
{ color: colors.primaryForeground },
]}
>
Remove
</Text>
</Pressable>
)}
>
{row}
</ReanimatedSwipeable>
)
}}
/>
)}
</> </>
) )
} }
function PlaylistHero({ function songKey(song: BrowseSong) {
return song.id
}
const PlaylistSongRow = memo(function PlaylistSongRow({
song,
favorited,
removable,
palette,
swipeGroup,
onPlay,
onAction,
onRemove,
}: {
song: BrowseSong
favorited: boolean
removable: boolean
palette: CoverPalette
swipeGroup: SwipeRowGroup
onPlay: (song: BrowseSong) => void
onAction: (song: BrowseSong, action: MediaAction) => void
onRemove: (songId: Id<"songs">) => Promise<boolean>
}) {
const colors = useThemeColors()
const handleRemove = useCallback(() => onRemove(song.id), [onRemove, song.id])
const row = (
<SongListRow
song={song}
favorited={favorited}
playlistLabel={PLAYLIST_LABEL}
palette={palette}
inset
onPlay={onPlay}
onAction={onAction}
/>
)
if (!removable) {
return row
}
if (Platform.OS === "ios") {
return (
<SwipeToRemoveRow
group={swipeGroup}
backgroundColor={palette.background}
actionAccessibilityLabel={`Remove ${song.title} from playlist`}
onRemove={handleRemove}
>
{row}
</SwipeToRemoveRow>
)
}
return (
<ReanimatedSwipeable
friction={2}
rightThreshold={56}
overshootRight={false}
enableTrackpadTwoFingerGesture
containerStyle={{ backgroundColor: colors.destructive }}
childrenContainerStyle={{ backgroundColor: palette.background }}
renderRightActions={(_progress, _translation, swipeable) => (
<Pressable
accessibilityRole="button"
accessibilityLabel={`Remove ${song.title} from playlist`}
onPress={() => {
swipeable.close()
void handleRemove()
}}
style={[styles.removeAction, { backgroundColor: colors.destructive }]}
>
<Ionicons name="trash" size={22} color={colors.primaryForeground} />
<Text
style={[
styles.removeActionText,
{ color: colors.primaryForeground },
]}
>
Remove
</Text>
</Pressable>
)}
>
{row}
</ReanimatedSwipeable>
)
})
const PlaylistHero = memo(function PlaylistHero({
coverUri, coverUri,
hasCover, hasCover,
title, title,
ownerName, ownerName,
colors, palette,
isSubscribed, isSubscribed,
showSubscribe = false, showSubscribe = false,
onSubscribeToggle, onSubscribeToggle,
@@ -481,7 +469,7 @@ function PlaylistHero({
hasCover: boolean hasCover: boolean
title: string title: string
ownerName: string ownerName: string
colors: ReturnType<typeof useThemeColors> palette: CoverPalette
isSubscribed?: boolean isSubscribed?: boolean
showSubscribe?: boolean showSubscribe?: boolean
onSubscribeToggle?: () => void onSubscribeToggle?: () => void
@@ -489,56 +477,68 @@ function PlaylistHero({
onShuffle: () => void onShuffle: () => void
}) { }) {
return ( return (
<View style={styles.hero}> <View>
<CoverImage uri={coverUri} hasCover={hasCover} style={styles.cover} /> <View style={styles.hero}>
<Text style={[styles.title, { color: colors.foreground }]}>{title}</Text> <CoverImage uri={coverUri} hasCover={hasCover} style={styles.cover} />
<Text style={{ color: colors.mutedForeground }}>{ownerName}</Text> <Text style={[styles.title, { color: palette.foreground }]}>
<View style={styles.actions}> {title}
{showSubscribe ? ( </Text>
<Text style={{ color: palette.secondaryForeground }}>{ownerName}</Text>
<View style={styles.actions}>
{showSubscribe ? (
<Pressable
accessibilityRole="button"
accessibilityLabel={isSubscribed ? "Subscribed" : "Subscribe"}
accessibilityState={{ selected: isSubscribed }}
hitSlop={8}
onPress={onSubscribeToggle}
style={[
styles.iconAction,
{
backgroundColor: isSubscribed
? palette.surface
: palette.accent,
},
]}
>
<Ionicons
name={isSubscribed ? "checkmark" : "add"}
size={24}
color={
isSubscribed ? palette.foreground : palette.accentForeground
}
/>
</Pressable>
) : null}
<Button
title="Play"
icon="play"
onPress={onPlay}
style={styles.playButton}
tint={{
background: palette.accent,
foreground: palette.accentForeground,
}}
/>
<Pressable <Pressable
accessibilityRole="button" accessibilityRole="button"
accessibilityLabel={isSubscribed ? "Subscribed" : "Subscribe"} accessibilityLabel="Shuffle"
accessibilityState={{ selected: isSubscribed }}
hitSlop={8} hitSlop={8}
onPress={onSubscribeToggle} onPress={onShuffle}
style={[ style={[styles.iconAction, { backgroundColor: palette.surface }]}
styles.iconAction,
{
backgroundColor: isSubscribed ? colors.muted : colors.primary,
},
]}
> >
<Ionicons <Ionicons name="shuffle" size={24} color={palette.foreground} />
name={isSubscribed ? "checkmark" : "add"}
size={24}
color={
isSubscribed ? colors.foreground : colors.primaryForeground
}
/>
</Pressable> </Pressable>
) : null} </View>
<Button
title="Play"
icon="play"
onPress={onPlay}
style={styles.playButton}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={onShuffle}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
</View> </View>
<CollectionDivider color={palette.divider} />
</View> </View>
) )
} })
const styles = StyleSheet.create({ const styles = StyleSheet.create({
empty: { flex: 1, alignItems: "center", justifyContent: "center" }, empty: { flex: 1, alignItems: "center", justifyContent: "center" },
listContent: { paddingBottom: contentBottomInset },
hero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm }, hero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm },
cover: { cover: {
width: 200, width: 200,
@@ -561,15 +561,6 @@ const styles = StyleSheet.create({
alignItems: "center", alignItems: "center",
justifyContent: "center", justifyContent: "center",
}, },
iosSwipeListHost: {
flex: 1,
alignSelf: "stretch",
width: "100%",
},
nativeSongRow: {
height: 64,
overflow: "hidden",
},
removeAction: { removeAction: {
width: 96, width: 96,
alignItems: "center", alignItems: "center",
@@ -1,36 +1,102 @@
import { useQuery } from "convex/react" import { memo, useCallback, useEffect, useMemo } from "react"
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native" import {
FlatList,
Pressable,
StyleSheet,
Text,
View,
type ListRenderItemInfo,
} from "react-native"
import { Button, LoadingView } from "@/components/ui/primitives" import { CollectionDivider } from "@/components/collection-list"
import { contentBottomInset, SongRow } from "@/components/player" import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset, SongListRow } from "@/components/player"
import { useFavorites } from "@/contexts/favorites" import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback" import { usePlaybackActions } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config" import { useServerConfig } from "@/contexts/server-config"
import {
useCachedPaginatedQuery,
useCachedQuery,
} from "@/hooks/use-cached-query"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import type { MediaAction } from "@/components/media-context-menu"
import type { BrowseSong } from "@otunes/convex/types" import type { BrowseSong } from "@otunes/convex/types"
import { longListProps } from "@/lib/list"
import { rememberSongs } from "@/lib/song-cache"
import { radius, spacing, useThemeColors } from "@/lib/theme" import { radius, spacing, useThemeColors } from "@/lib/theme"
import { Ionicons } from "@expo/vector-icons" import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router" import { Stack } from "expo-router"
const PAGE_SIZE = 50
const SCREEN_OPTIONS = { title: "", headerLargeTitle: false }
export default function FavoritesScreen() { export default function FavoritesScreen() {
const colors = useThemeColors() const colors = useThemeColors()
const { config } = useServerConfig() const { config } = useServerConfig()
const favorites = useQuery(api.favorites.browseFavoritesPlaylistDetail) const favorites = useCachedQuery(api.favorites.browseFavoritesSummary)
const {
results: songs,
status,
loadMore,
isCached,
} = useCachedPaginatedQuery(
api.favorites.browseFavoritesSongsPaginated,
{},
{ initialNumItems: PAGE_SIZE }
)
const { playInOrder, playShuffled, playFromSong } = usePlaybackActions() const { playInOrder, playShuffled, playFromSong } = usePlaybackActions()
const { isSongFavorite } = useFavorites() const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions() const { handleSongAction } = useMediaMenuActions()
const loadedSongIds = useMemo(() => songs.map((song) => song.id), [songs])
const songIds = favorites?.songIds ?? loadedSongIds
if (favorites === undefined || !config) { useEffect(() => {
rememberSongs(songs)
}, [songs])
const handlePlaySong = useCallback(
(song: BrowseSong) => void playFromSong(song.id, songIds),
[playFromSong, songIds]
)
const handleSongMenuAction = useCallback(
(song: BrowseSong, action: MediaAction) =>
void handleSongAction(song, action),
[handleSongAction]
)
const handlePlay = useCallback(
() => void playInOrder(songIds),
[playInOrder, songIds]
)
const handleShuffle = useCallback(
() => void playShuffled(songIds),
[playShuffled, songIds]
)
const renderItem = useCallback(
({ item: song }: ListRenderItemInfo<BrowseSong>) => (
<SongListRow
song={song}
favorited={isSongFavorite(song.id)}
playlistLabel="Add to Another Playlist"
inset
onPlay={handlePlaySong}
onAction={handleSongMenuAction}
/>
),
[handlePlaySong, handleSongMenuAction, isSongFavorite]
)
if (
favorites === undefined ||
(status === "LoadingFirstPage" && !isCached) ||
!config
) {
return ( return (
<> <>
<Stack.Screen <Stack.Screen options={SCREEN_OPTIONS} />
options={{ <CollectionDetailSkeleton />
title: "",
headerLargeTitle: false,
}}
/>
<LoadingView />
</> </>
) )
} }
@@ -38,12 +104,7 @@ export default function FavoritesScreen() {
if (favorites === null) { if (favorites === null) {
return ( return (
<> <>
<Stack.Screen <Stack.Screen options={SCREEN_OPTIONS} />
options={{
title: "",
headerLargeTitle: false,
}}
/>
<View style={[styles.empty, { backgroundColor: colors.background }]}> <View style={[styles.empty, { backgroundColor: colors.background }]}>
<Text style={{ color: colors.mutedForeground }}> <Text style={{ color: colors.mutedForeground }}>
Sign in to view your favorites. Sign in to view your favorites.
@@ -53,92 +114,100 @@ export default function FavoritesScreen() {
) )
} }
const songIds = favorites.songs.map((song: BrowseSong) => song.id)
return ( return (
<> <>
<Stack.Screen <Stack.Screen options={SCREEN_OPTIONS} />
options={{
title: "",
headerLargeTitle: false,
}}
/>
<FlatList <FlatList
data={favorites.songs} {...longListProps}
keyExtractor={(song) => song.id} data={songs}
keyExtractor={songKey}
renderItem={renderItem}
style={{ flex: 1, backgroundColor: colors.background }} style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{ paddingBottom: contentBottomInset }} contentContainerStyle={styles.listContent}
contentInsetAdjustmentBehavior="automatic" contentInsetAdjustmentBehavior="automatic"
onEndReached={() => {
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
onEndReachedThreshold={0.5}
ListHeaderComponent={ ListHeaderComponent={
<View style={styles.hero}> <FavoritesHero
<View title={favorites.title}
style={[ onPlay={handlePlay}
styles.cover, onShuffle={handleShuffle}
{
backgroundColor: colors.coverPlaceholder,
alignItems: "center",
justifyContent: "center",
overflow: "hidden",
},
]}
>
<Ionicons name="star" size={120} color={colors.primary} />
</View>
<Text style={[styles.title, { color: colors.foreground }]}>
{favorites.title}
</Text>
<View style={styles.actions}>
<Button
title="Play"
icon="play"
onPress={() => void playInOrder(songIds)}
style={styles.playButton}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() => void playShuffled(songIds)}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
</View>
</View>
}
renderItem={({ item: song }: { item: BrowseSong }) => (
<SongRow
song={song}
onPress={() => void playFromSong(song.id, songIds)}
contextMenu={{
favorited: isSongFavorite(song.id),
playlistLabel: "Add to Another Playlist",
navigation: {
artist: { id: song.artist.id },
album: { id: song.album.id },
},
share: {
type: "song",
albumId: song.album.id,
songId: song.id,
},
onAction: (action) => void handleSongAction(song, action),
}}
/> />
)} }
/> />
</> </>
) )
} }
function songKey(song: BrowseSong) {
return song.id
}
const FavoritesHero = memo(function FavoritesHero({
title,
onPlay,
onShuffle,
}: {
title: string
onPlay: () => void
onShuffle: () => void
}) {
const colors = useThemeColors()
return (
<View>
<View style={styles.hero}>
<View
style={[
styles.cover,
styles.coverPlaceholder,
{ backgroundColor: colors.coverPlaceholder },
]}
>
<Ionicons name="star" size={120} color={colors.primary} />
</View>
<Text style={[styles.title, { color: colors.foreground }]}>
{title}
</Text>
<View style={styles.actions}>
<Button
title="Play"
icon="play"
onPress={onPlay}
style={styles.playButton}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={onShuffle}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
</View>
</View>
<CollectionDivider />
</View>
)
})
const styles = StyleSheet.create({ const styles = StyleSheet.create({
empty: { flex: 1, alignItems: "center", justifyContent: "center" }, empty: { flex: 1, alignItems: "center", justifyContent: "center" },
listContent: { paddingBottom: contentBottomInset },
hero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm }, hero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm },
cover: { cover: {
width: 200, width: 200,
height: 200, height: 200,
borderRadius: radius.lg, borderRadius: radius.lg,
}, },
coverPlaceholder: {
alignItems: "center",
justifyContent: "center",
overflow: "hidden",
},
title: { fontSize: 24, fontWeight: "800" }, title: { fontSize: 24, fontWeight: "800" },
actions: { actions: {
flexDirection: "row", flexDirection: "row",
+96 -81
View File
@@ -1,60 +1,94 @@
import { usePaginatedQuery, useQuery } from "convex/react"
import { Stack, useRouter } from "expo-router" import { Stack, useRouter } from "expo-router"
import { useState } from "react" import { memo, useCallback, useMemo } from "react"
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native" import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
import { Button, LoadingView } from "@/components/ui/primitives" import { Button } from "@/components/ui/primitives"
import { contentBottomInset, SongRow } from "@/components/player" import { contentBottomInset, SongRow } from "@/components/player"
import { SongRowSkeleton } from "@/components/skeletons"
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback" import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
import { api } from "@otunes/convex/_generated/api" import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong } from "@otunes/convex/types" import { longListProps } from "@/lib/list"
import { useSong, useSongs } from "@/lib/song-cache"
import { spacing, useThemeColors } from "@/lib/theme" import { spacing, useThemeColors } from "@/lib/theme"
import { showError } from "@/lib/toast"
const PAGE_SIZE = 50 /** `key` stays stable when earlier songs leave the queue, so rows are not remounted on skip. */
type QueueItem = { songId: Id<"songs">; queueIndex: number; key: string }
function queueItemKey(item: QueueItem) {
return item.key
}
const QueueRow = memo(function QueueRow({
songId,
queueIndex,
isLast,
isCurrent,
onSkipTo,
onMove,
}: Omit<QueueItem, "key"> & {
isLast: boolean
isCurrent: boolean
onSkipTo: (index: number) => void
onMove: (index: number, direction: -1 | 1) => void
}) {
const colors = useThemeColors()
const song = useSong(songId)
return (
<View>
{song ? (
<SongRow song={song} onPress={() => onSkipTo(queueIndex)} />
) : (
<SongRowSkeleton />
)}
<View style={styles.queueActions}>
<Pressable
disabled={queueIndex === 0}
onPress={() => onMove(queueIndex, -1)}
>
<Text style={{ color: colors.foreground }}>Move up</Text>
</Pressable>
<Pressable disabled={isLast} onPress={() => onMove(queueIndex, 1)}>
<Text style={{ color: colors.foreground }}>Move down</Text>
</Pressable>
{isCurrent ? (
<Text style={{ color: colors.primary, fontWeight: "700" }}>
Now playing
</Text>
) : null}
</View>
</View>
)
})
export default function QueueScreen() { export default function QueueScreen() {
const router = useRouter() const router = useRouter()
const colors = useThemeColors() const colors = useThemeColors()
const { queueSongIds, currentSong } = usePlaybackQueue() const { queueSongIds, queueHistorySongIds } = usePlaybackQueue()
const { skipToQueueIndex, clearQueue, reorderQueue } = usePlaybackActions() const { skipToQueueIndex, clearQueue, reorderQueue } = usePlaybackActions()
const [reordering, setReordering] = useState(false) const historySongs = useSongs(queueHistorySongIds)
const queueVersion = queueSongIds.length const items = useMemo<QueueItem[]>(() => {
? `${queueSongIds.length}:${queueSongIds[0]}:${queueSongIds[queueSongIds.length - 1]}` const occurrences = new Map<string, number>()
: "empty" return queueSongIds.map((songId, queueIndex) => {
const occurrence = occurrences.get(songId) ?? 0
occurrences.set(songId, occurrence + 1)
return { songId, queueIndex, key: `${songId}:${occurrence}` }
})
}, [queueSongIds])
const { const moveSong = useCallback(
results: queueSongs, (fromIndex: number, direction: -1 | 1) => {
status, const toIndex = fromIndex + direction
loadMore, if (toIndex < 0 || toIndex >= queueSongIds.length) return
} = usePaginatedQuery( const next = [...queueSongIds]
api.playback.getQueuePaginated, const [item] = next.splice(fromIndex, 1)
queueSongIds.length > 0 ? { queueVersion } : "skip", next.splice(toIndex, 0, item)
{ initialNumItems: PAGE_SIZE } void reorderQueue(next)
},
[queueSongIds, reorderQueue]
) )
const historySongs = useQuery(api.playback.getQueueHistory)
async function moveSong(fromIndex: number, direction: -1 | 1) {
if (reordering) return
const toIndex = fromIndex + direction
if (toIndex < 0 || toIndex >= queueSongIds.length) return
const next = [...queueSongIds]
const [item] = next.splice(fromIndex, 1)
next.splice(toIndex, 0, item)
setReordering(true)
try {
await reorderQueue(next)
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to reorder queue"
)
} finally {
setReordering(false)
}
}
function handleClearQueue() { function handleClearQueue() {
if (router.canGoBack()) { if (router.canGoBack()) {
router.back() router.back()
@@ -67,10 +101,6 @@ export default function QueueScreen() {
void clearQueue() void clearQueue()
} }
if (queueSongIds.length > 0 && queueSongs === undefined) {
return <LoadingView />
}
return ( return (
<> <>
<Stack.Screen <Stack.Screen
@@ -99,51 +129,36 @@ export default function QueueScreen() {
) : null} ) : null}
</View> </View>
} }
data={queueSongs ?? []} {...longListProps}
keyExtractor={(item) => `${item.id}-${item.queueIndex}`} data={items}
keyExtractor={queueItemKey}
contentContainerStyle={{ paddingBottom: contentBottomInset }} contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic" contentInsetAdjustmentBehavior="automatic"
onEndReached={() => {
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
renderItem={({ item }) => ( renderItem={({ item }) => (
<View> <QueueRow
<SongRow songId={item.songId}
song={item} queueIndex={item.queueIndex}
onPress={() => void skipToQueueIndex(item.queueIndex)} isLast={item.queueIndex === queueSongIds.length - 1}
/> isCurrent={item.queueIndex === 0}
<View style={styles.queueActions}> onSkipTo={skipToQueueIndex}
<Pressable onMove={moveSong}
disabled={reordering || item.queueIndex === 0} />
onPress={() => void moveSong(item.queueIndex, -1)}
>
<Text style={{ color: colors.foreground }}>Move up</Text>
</Pressable>
<Pressable
disabled={
reordering || item.queueIndex === queueSongIds.length - 1
}
onPress={() => void moveSong(item.queueIndex, 1)}
>
<Text style={{ color: colors.foreground }}>Move down</Text>
</Pressable>
{currentSong?.id === item.id ? (
<Text style={{ color: colors.primary, fontWeight: "700" }}>
Now playing
</Text>
) : null}
</View>
</View>
)} )}
ListFooterComponent={ ListFooterComponent={
historySongs && historySongs.length > 0 ? ( queueHistorySongIds.length > 0 ? (
<View style={styles.history}> <View style={styles.history}>
<Text style={[styles.section, { color: colors.mutedForeground }]}> <Text style={[styles.section, { color: colors.mutedForeground }]}>
History History
</Text> </Text>
{historySongs.map((song: BrowseSong) => ( {historySongs.map((song, index) =>
<SongRow key={song.id} song={song} /> song ? (
))} <SongRow key={`${song.id}-${index}`} song={song} />
) : (
<SongRowSkeleton
key={`${queueHistorySongIds[index]}-${index}`}
/>
)
)}
</View> </View>
) : null ) : null
} }
@@ -1,21 +1,20 @@
import { usePaginatedQuery } from "convex/react"
import { MediaGridList } from "@/components/media-cards" import { MediaGridList } from "@/components/media-cards"
import { LoadingView } from "@/components/ui/primitives" import { MediaGridSkeleton } from "@/components/skeletons"
import { contentBottomInset } from "@/components/player" import { contentBottomInset } from "@/components/player"
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
const PAGE_SIZE = 16 const PAGE_SIZE = 16
export default function RecentlyAddedScreen() { export default function RecentlyAddedScreen() {
const { results, status, loadMore } = usePaginatedQuery( const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
api.library.browseRecentlyAddedPaginated, api.library.browseRecentlyAddedPaginated,
{}, {},
{ initialNumItems: PAGE_SIZE } { initialNumItems: PAGE_SIZE }
) )
if (results === undefined) { if (status === "LoadingFirstPage" && !isCached) {
return <LoadingView /> return <MediaGridSkeleton />
} }
return ( return (
@@ -1,21 +1,20 @@
import { usePaginatedQuery } from "convex/react"
import { MediaGridList } from "@/components/media-cards" import { MediaGridList } from "@/components/media-cards"
import { LoadingView } from "@/components/ui/primitives" import { MediaGridSkeleton } from "@/components/skeletons"
import { contentBottomInset } from "@/components/player" import { contentBottomInset } from "@/components/player"
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
const PAGE_SIZE = 50 const PAGE_SIZE = 50
export default function RecentlyPlayedScreen() { export default function RecentlyPlayedScreen() {
const { results, status, loadMore } = usePaginatedQuery( const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
api.library.browseRecentlyPlayedPaginated, api.library.browseRecentlyPlayedPaginated,
{}, {},
{ initialNumItems: PAGE_SIZE } { initialNumItems: PAGE_SIZE }
) )
if (results === undefined) { if (status === "LoadingFirstPage" && !isCached) {
return <LoadingView /> return <MediaGridSkeleton />
} }
return ( return (
+84 -68
View File
@@ -19,7 +19,8 @@ import { Button, Input, LoadingView } from "@/components/ui/primitives"
import { useInvalidateAuthSession } from "@/contexts/convex-auth-session" import { useInvalidateAuthSession } from "@/contexts/convex-auth-session"
import { useServerConfig } from "@/contexts/server-config" import { useServerConfig } from "@/contexts/server-config"
import { initialsFromName } from "@/lib/format" import { initialsFromName } from "@/lib/format"
import { signOutToSignIn } from "@/lib/session" import { useCachedQuery } from "@/hooks/use-cached-query"
import { clearLocalData, signOutToSignIn } from "@/lib/session"
import { radius, spacing, useThemeColors } from "@/lib/theme" import { radius, spacing, useThemeColors } from "@/lib/theme"
import { showError, showSuccess } from "@/lib/toast" import { showError, showSuccess } from "@/lib/toast"
import type { PlaybackQuality } from "@/lib/urls" import type { PlaybackQuality } from "@/lib/urls"
@@ -73,7 +74,7 @@ const SECTIONS: SectionConfig[] = [
export default function SettingsScreen() { export default function SettingsScreen() {
const colors = useThemeColors() const colors = useThemeColors()
const router = useRouter() const router = useRouter()
const user = useQuery(api.auth.currentUser) const user = useCachedQuery(api.auth.currentUser)
const { invalidateSession } = useInvalidateAuthSession() const { invalidateSession } = useInvalidateAuthSession()
const { clearServer } = useServerConfig() const { clearServer } = useServerConfig()
const [section, setSection] = useState<Section>("profile") const [section, setSection] = useState<Section>("profile")
@@ -95,6 +96,7 @@ export default function SettingsScreen() {
async function handleChangeServer() { async function handleChangeServer() {
await invalidateSession() await invalidateSession()
await clearLocalData()
await clearServer() await clearServer()
router.replace("/server") router.replace("/server")
} }
@@ -460,7 +462,7 @@ function UsersSection({
<SettingsCard title="Sign Up"> <SettingsCard title="Sign Up">
<SwitchRow <SwitchRow
title="Disable account creation" title="Disable account creation"
subtitle="Prevent new users from creating accounts." subtitle="Stop people from registering themselves. Admins can still create accounts from the web app."
value={appSettings?.disableAccountCreation ?? false} value={appSettings?.disableAccountCreation ?? false}
onValueChange={(checked) => onValueChange={(checked) =>
void setDisableCreation({ disabled: checked }).catch( void setDisableCreation({ disabled: checked }).catch(
@@ -474,77 +476,82 @@ function UsersSection({
title="People" title="People"
subtitle="Manage who can access this server." subtitle="Manage who can access this server."
> >
{users.map((user, index) => ( <View style={styles.userList}>
<View key={user._id}> {users.map((user, index) => (
{index > 0 ? ( <View
<View key={user._id}
style={[styles.divider, { backgroundColor: colors.border }]} style={[
/> styles.userBlock,
) : null} index > 0
<View style={styles.userRow}> ? [styles.userBlockSpaced, { borderTopColor: colors.border }]
<ProfileAvatar user={user} size={44} /> : null,
<View style={styles.userCopy}> ]}
<View style={styles.userNameRow}> >
<View style={styles.userRow}>
<ProfileAvatar user={user} size={44} />
<View style={styles.userCopy}>
<View style={styles.userNameRow}>
<Text
style={[styles.userName, { color: colors.foreground }]}
numberOfLines={1}
>
{user.name}
</Text>
{user.isAdmin ? (
<View
style={[styles.badge, { backgroundColor: colors.muted }]}
>
<Text
style={[
styles.badgeText,
{ color: colors.mutedForeground },
]}
>
Admin
</Text>
</View>
) : null}
</View>
<Text <Text
style={[styles.userName, { color: colors.foreground }]} style={{ color: colors.mutedForeground }}
numberOfLines={1} numberOfLines={1}
> >
{user.name} {user.email}
</Text> </Text>
{user.isAdmin ? (
<View
style={[styles.badge, { backgroundColor: colors.muted }]}
>
<Text
style={[
styles.badgeText,
{ color: colors.mutedForeground },
]}
>
Admin
</Text>
</View>
) : null}
</View> </View>
<Text
style={{ color: colors.mutedForeground }}
numberOfLines={1}
>
{user.email}
</Text>
</View> </View>
{user._id !== currentUserId ? (
<View style={styles.userActions}>
<Button
title={user.isAdmin ? "Remove Admin" : "Make Admin"}
variant="secondary"
onPress={() =>
void setAdmin({
userId: user._id,
isAdmin: !user.isAdmin,
}).then(
() => showSuccess("Updated permissions"),
(error: Error) => showError(error.message)
)
}
style={styles.userActionButton}
/>
<Button
title="Delete"
variant="destructive"
onPress={() =>
void deleteUserMutation({ userId: user._id }).then(
() => showSuccess("User deleted"),
(error: Error) => showError(error.message)
)
}
style={styles.userActionButton}
/>
</View>
) : null}
</View> </View>
{user._id !== currentUserId ? ( ))}
<View style={styles.userActions}> </View>
<Button
title={user.isAdmin ? "Remove Admin" : "Make Admin"}
variant="secondary"
onPress={() =>
void setAdmin({
userId: user._id,
isAdmin: !user.isAdmin,
}).then(
() => showSuccess("Updated permissions"),
(error: Error) => showError(error.message)
)
}
style={styles.userActionButton}
/>
<Button
title="Delete"
variant="destructive"
onPress={() =>
void deleteUserMutation({ userId: user._id }).then(
() => showSuccess("User deleted"),
(error: Error) => showError(error.message)
)
}
style={styles.userActionButton}
/>
</View>
) : null}
</View>
))}
</SettingsCard> </SettingsCard>
</> </>
) )
@@ -831,6 +838,16 @@ const styles = StyleSheet.create({
alignItems: "center", alignItems: "center",
gap: spacing.md, gap: spacing.md,
}, },
userList: {
gap: spacing.lg,
},
userBlock: {
gap: spacing.md,
},
userBlockSpaced: {
paddingTop: spacing.lg,
borderTopWidth: StyleSheet.hairlineWidth,
},
userRow: { userRow: {
flexDirection: "row", flexDirection: "row",
alignItems: "center", alignItems: "center",
@@ -853,7 +870,6 @@ const styles = StyleSheet.create({
userActions: { userActions: {
flexDirection: "row", flexDirection: "row",
gap: spacing.sm, gap: spacing.sm,
marginTop: spacing.md,
}, },
userActionButton: { userActionButton: {
flex: 1, flex: 1,
@@ -16,17 +16,18 @@ export default function LibraryLayout() {
screenOptions={({ route }) => ({ screenOptions={({ route }) => ({
...baseOptions, ...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Library", title: tabStackScreenTitles[route.name] ?? "Library",
headerRight: route.name === "settings" ? undefined : () => <ProfileHeaderButton />, headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems: unstable_headerRightItems:
route.name === "settings" route.name === "index"
? undefined ? () => [
: () => [
{ {
type: "custom", type: "custom",
element: <ProfileHeaderButton />, element: <ProfileHeaderButton />,
hidesSharedBackground: true, hidesSharedBackground: true,
}, },
], ]
: undefined,
})} })}
/> />
) )
@@ -1,4 +1,3 @@
import { usePaginatedQuery } from "convex/react"
import { useMemo } from "react" import { useMemo } from "react"
import { Pressable, StyleSheet, Text, View } from "react-native" import { Pressable, StyleSheet, Text, View } from "react-native"
import { SymbolView } from "expo-symbols" import { SymbolView } from "expo-symbols"
@@ -7,7 +6,8 @@ import { Ionicons } from "@expo/vector-icons"
import { MediaGridList } from "@/components/media-cards" import { MediaGridList } from "@/components/media-cards"
import { tabContentBottomInset } from "@/components/player" import { tabContentBottomInset } from "@/components/player"
import { LoadingView } from "@/components/ui/primitives" import { MediaGridSkeleton } from "@/components/skeletons"
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
import { useAppNavigation } from "@/lib/app-navigation" import { useAppNavigation } from "@/lib/app-navigation"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import { appleMusic, spacing, useThemeColors } from "@/lib/theme" import { appleMusic, spacing, useThemeColors } from "@/lib/theme"
@@ -49,7 +49,7 @@ function LibraryIcon({ name }: { name: (typeof links)[number]["icon"] }) {
export default function LibraryScreen() { export default function LibraryScreen() {
const { push } = useAppNavigation() const { push } = useAppNavigation()
const colors = useThemeColors() const colors = useThemeColors()
const { results, status, loadMore } = usePaginatedQuery( const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
api.library.browseRecentlyAddedPaginated, api.library.browseRecentlyAddedPaginated,
{}, {},
{ initialNumItems: PAGE_SIZE } { initialNumItems: PAGE_SIZE }
@@ -83,11 +83,11 @@ export default function LibraryScreen() {
[colors.border, colors.foreground, colors.mutedForeground, push] [colors.border, colors.foreground, colors.mutedForeground, push]
) )
if (results === undefined) { if (status === "LoadingFirstPage" && !isCached) {
return ( return (
<View style={{ flex: 1, backgroundColor: colors.background }}> <View style={{ flex: 1, backgroundColor: colors.background }}>
{listHeader} {listHeader}
<LoadingView /> <MediaGridSkeleton contentInset={false} />
</View> </View>
) )
} }
@@ -16,17 +16,18 @@ export default function SearchLayout() {
screenOptions={({ route }) => ({ screenOptions={({ route }) => ({
...baseOptions, ...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Search", title: tabStackScreenTitles[route.name] ?? "Search",
headerRight: route.name === "settings" ? undefined : () => <ProfileHeaderButton />, headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems: unstable_headerRightItems:
route.name === "settings" route.name === "index"
? undefined ? () => [
: () => [
{ {
type: "custom", type: "custom",
element: <ProfileHeaderButton />, element: <ProfileHeaderButton />,
hidesSharedBackground: true, hidesSharedBackground: true,
}, },
], ]
: undefined,
})} })}
/> />
) )
+15 -9
View File
@@ -1,5 +1,8 @@
import { useConvexAuth as useLocalConvexAuth } from "@convex-dev/auth/react" import { useConvexAuth as useLocalConvexAuth } from "@convex-dev/auth/react"
import { useConvexAuth as useServerConvexAuth } from "convex/react" import {
useConvexAuth as useServerConvexAuth,
useConvexConnectionState,
} from "convex/react"
import { Redirect, Stack } from "expo-router" import { Redirect, Stack } from "expo-router"
import { Platform } from "react-native" import { Platform } from "react-native"
import { useEffect } from "react" import { useEffect } from "react"
@@ -20,14 +23,21 @@ export default function AppLayout() {
const { config } = useServerConfig() const { config } = useServerConfig()
const localAuth = useLocalConvexAuth() const localAuth = useLocalConvexAuth()
const serverAuth = useServerConvexAuth() const serverAuth = useServerConvexAuth()
const { isWebSocketConnected } = useConvexConnectionState()
const { invalidateSession } = useInvalidateAuthSession() const { invalidateSession } = useInvalidateAuthSession()
const stackOptions = useStackScreenOptions() const stackOptions = useStackScreenOptions()
useEffect(() => { useEffect(() => {
if (!localAuth?.isAuthenticated || serverAuth?.isAuthenticated) { if (
!localAuth?.isAuthenticated ||
serverAuth?.isAuthenticated ||
!isWebSocketConnected
) {
return return
} }
// Only a reachable server that never accepts the session counts as a
// failed handshake; offline launches keep the session and cached data.
const timer = setTimeout(() => { const timer = setTimeout(() => {
void invalidateSession() void invalidateSession()
}, AUTH_HANDSHAKE_TIMEOUT_MS) }, AUTH_HANDSHAKE_TIMEOUT_MS)
@@ -35,6 +45,7 @@ export default function AppLayout() {
return () => clearTimeout(timer) return () => clearTimeout(timer)
}, [ }, [
invalidateSession, invalidateSession,
isWebSocketConnected,
localAuth?.isAuthenticated, localAuth?.isAuthenticated,
serverAuth?.isAuthenticated, serverAuth?.isAuthenticated,
]) ])
@@ -51,13 +62,8 @@ export default function AppLayout() {
return <Redirect href="/signin" /> return <Redirect href="/signin" />
} }
if (!serverAuth || serverAuth.isLoading || serverAuth.isRefreshing) { // Convex holds queries until the stored token is confirmed, so the app can
return <LoadingView /> // render cached data while the server handshake is still in progress.
}
if (!serverAuth.isAuthenticated) {
return <LoadingView />
}
return ( return (
<ConvexAuthRecovery onInvalidate={invalidateSession}> <ConvexAuthRecovery onInvalidate={invalidateSession}>
+4 -2
View File
@@ -52,8 +52,10 @@ export default function PlayerScreen() {
skipPrevious, skipPrevious,
} = usePlayback() } = usePlayback()
const hasQueue = queueSongIds.length > 0
useEffect(() => { useEffect(() => {
if (currentSong) { if (hasQueue) {
hadSongRef.current = true hadSongRef.current = true
return return
} }
@@ -61,7 +63,7 @@ export default function PlayerScreen() {
if (hadSongRef.current) { if (hadSongRef.current) {
router.back() router.back()
} }
}, [currentSong, router]) }, [hasQueue, router])
if (!currentSong || !config) { if (!currentSong || !config) {
return null return null
@@ -0,0 +1,46 @@
import { memo } from "react"
import { StyleSheet, Text, View } from "react-native"
import { useThemeColors } from "@/lib/theme"
/** Horizontal inset for rows and dividers in album and playlist track lists. */
export const collectionInset = 20
/** Separates a collection's header from its track list. */
export function CollectionDivider({ color }: { color?: string }) {
const colors = useThemeColors()
return (
<View
style={[styles.divider, { backgroundColor: color ?? colors.border }]}
/>
)
}
export const DiscHeader = memo(function DiscHeader({
label,
color,
}: {
label: string
color?: string
}) {
const colors = useThemeColors()
return (
<Text style={[styles.discHeader, { color: color ?? colors.foreground }]}>
{label}
</Text>
)
})
const styles = StyleSheet.create({
divider: {
height: StyleSheet.hairlineWidth,
marginHorizontal: collectionInset,
},
discHeader: {
fontSize: 17,
fontWeight: "700",
paddingHorizontal: collectionInset,
paddingTop: 24,
paddingBottom: 8,
},
})
@@ -10,7 +10,10 @@ import {
} from "react" } from "react"
import { LoadingView } from "@/components/ui/primitives" import { LoadingView } from "@/components/ui/primitives"
import { shouldInvalidateAuthSession } from "@/lib/auth-errors" import {
isConvexAuthError,
shouldInvalidateAuthSession,
} from "@/lib/auth-errors"
type ConvexAuthRecoveryProps = { type ConvexAuthRecoveryProps = {
children: ReactNode children: ReactNode
@@ -43,10 +46,22 @@ class ConvexAuthErrorBoundary extends Component<
} }
} }
componentDidUpdate(previous: ConvexAuthErrorBoundaryProps) {
// Screens render before the handshake finishes, so an auth error from that
// window clears once the server accepts the session.
if (
this.state.error &&
!previous.sessionEstablished &&
this.props.sessionEstablished
) {
this.setState({ error: null })
}
}
render() { render() {
const { error } = this.state const { error } = this.state
if (error) { if (error) {
if (shouldInvalidateAuthSession(error, this.props.sessionEstablished)) { if (isConvexAuthError(error)) {
return <LoadingView /> return <LoadingView />
} }
throw error throw error
+23 -14
View File
@@ -1,6 +1,6 @@
import { Ionicons } from "@expo/vector-icons" import { Ionicons } from "@expo/vector-icons"
import { Image, type ImageContentFit, type ImageStyle } from "expo-image" import { Image, type ImageContentFit, type ImageStyle } from "expo-image"
import { memo } from "react" import { memo, useMemo } from "react"
import { import {
PixelRatio, PixelRatio,
StyleProp, StyleProp,
@@ -17,6 +17,7 @@ import {
} from "@/lib/urls" } from "@/lib/urls"
const DEFAULT_SOURCE_SIZE: CoverImageSize = 1024 const DEFAULT_SOURCE_SIZE: CoverImageSize = 1024
const PIXEL_RATIO = PixelRatio.get()
function sourceSize(style: ImageStyle): CoverImageSize { function sourceSize(style: ImageStyle): CoverImageSize {
const layoutSizes = [ const layoutSizes = [
@@ -28,7 +29,7 @@ function sourceSize(style: ImageStyle): CoverImageSize {
if (layoutSizes.length === 0) return DEFAULT_SOURCE_SIZE if (layoutSizes.length === 0) return DEFAULT_SOURCE_SIZE
const requiredPixels = Math.max(...layoutSizes) * PixelRatio.get() const requiredPixels = Math.max(...layoutSizes) * PIXEL_RATIO
return ( return (
coverImageSizes.find((size) => size >= requiredPixels) ?? coverImageSizes.find((size) => size >= requiredPixels) ??
DEFAULT_SOURCE_SIZE DEFAULT_SOURCE_SIZE
@@ -49,6 +50,12 @@ function placeholderIconSize(style: ImageStyle): number {
return 48 return 48
} }
const placeholderBaseStyle: ViewStyle = {
alignItems: "center",
justifyContent: "center",
overflow: "hidden",
}
export const CoverImage = memo(function CoverImage({ export const CoverImage = memo(function CoverImage({
uri, uri,
hasCover, hasCover,
@@ -65,18 +72,22 @@ export const CoverImage = memo(function CoverImage({
placeholderVariant?: "icon" | "solid" placeholderVariant?: "icon" | "solid"
}) { }) {
const colors = useThemeColors() const colors = useThemeColors()
const flatStyle = StyleSheet.flatten(style) ?? {} const flatStyle = useMemo(() => StyleSheet.flatten(style) ?? {}, [style])
const sourceUri = useMemo(
() => (hasCover ? withCoverImageSize(uri, sourceSize(flatStyle)) : ""),
[flatStyle, hasCover, uri]
)
const source = useMemo(() => ({ uri: sourceUri }), [sourceUri])
if (!hasCover) { if (!hasCover) {
const placeholderStyle: ViewStyle = {
backgroundColor: colors.coverPlaceholder,
alignItems: "center",
justifyContent: "center",
overflow: "hidden",
}
return ( return (
<View style={[style, placeholderStyle]}> <View
style={[
style,
placeholderBaseStyle,
{ backgroundColor: colors.coverPlaceholder },
]}
>
{placeholderVariant === "icon" ? ( {placeholderVariant === "icon" ? (
<Ionicons <Ionicons
name="musical-note" name="musical-note"
@@ -88,11 +99,9 @@ export const CoverImage = memo(function CoverImage({
) )
} }
const sourceUri = withCoverImageSize(uri, sourceSize(flatStyle))
return ( return (
<Image <Image
source={{ uri: sourceUri }} source={source}
style={[style, { backgroundColor: colors.coverPlaceholder }]} style={[style, { backgroundColor: colors.coverPlaceholder }]}
contentFit={contentFit} contentFit={contentFit}
transition={150} transition={150}
@@ -0,0 +1,359 @@
import * as Haptics from "expo-haptics"
import { SymbolView } from "expo-symbols"
import { useCallback, useMemo, useState, type ReactNode } from "react"
import {
PlatformColor,
Pressable,
StyleSheet,
type LayoutChangeEvent,
} from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import Animated, {
cancelAnimation,
Extrapolation,
interpolate,
useAnimatedStyle,
useSharedValue,
withSpring,
withTiming,
} from "react-native-reanimated"
import { scheduleOnRN } from "react-native-worklets"
const ACTION_WIDTH = 82
const CARD_ROUNDING_REVEAL = 40
const PILL_MIN_MARGIN = 10
const PILL_COMMITTED_MARGIN = 6
const PILL_WIDTH_INPUT = [24, ACTION_WIDTH, 220]
const PILL_WIDTH_OUTPUT = [0, 62, 200]
const PILL_HEIGHT_INPUT = [0, 24, 62, 140, 200]
const PILL_HEIGHT_RATIO = [0, 0.3, 0.77, 0.82, 0.86]
const ICON_FULL_SIZE_REVEAL = 64
const FULL_SWIPE_RATIO = 0.55
const FLING_VELOCITY = 400
const SETTLE_SPRING = { duration: 450, dampingRatio: 1 }
const LABEL_SPRING = { duration: 300, dampingRatio: 0.85 }
const SLIDE_OUT = { duration: 200 }
const COLLAPSE = { duration: 250 }
/**
* Keeps at most one row open, like a `UITableView`: opening a row closes the
* previous one, and `closeOpenRow` closes whichever is open (call it when the
* list starts scrolling).
*/
export type SwipeRowGroup = {
setOpen: (close: () => void) => void
clear: (close: () => void) => void
closeOpenRow: () => void
}
export function useSwipeRowGroup(): SwipeRowGroup {
const [group] = useState<SwipeRowGroup>(() => {
let openRowClose: (() => void) | null = null
return {
setOpen(close) {
if (openRowClose && openRowClose !== close) openRowClose()
openRowClose = close
},
clear(close) {
if (openRowClose === close) openRowClose = null
},
closeOpenRow() {
openRowClose?.()
openRowClose = null
},
}
})
return group
}
type SwipeToRemoveRowProps = {
group: SwipeRowGroup
backgroundColor: string
actionAccessibilityLabel: string
/** Resolves `false` if the removal failed, which restores the row. */
onRemove: () => Promise<boolean>
children: ReactNode
}
/**
* The iOS 26 trailing swipe-to-delete row: the row lifts into a rounded card
* and a red pill grows in the revealed space. Release past half the pill to
* leave it open, or drag past the full-swipe point (haptic, the pill fills the
* space) to remove on release.
*/
export function SwipeToRemoveRow(props: SwipeToRemoveRowProps) {
const [generation, setGeneration] = useState(0)
const restore = useCallback(() => setGeneration((value) => value + 1), [])
return <SwipeRowBody key={generation} {...props} onRestore={restore} />
}
function SwipeRowBody({
group,
backgroundColor,
actionAccessibilityLabel,
onRemove,
onRestore,
children,
}: SwipeToRemoveRowProps & { onRestore: () => void }) {
const width = useSharedValue(0)
const height = useSharedValue(0)
const translateX = useSharedValue(0)
const startX = useSharedValue(0)
const committed = useSharedValue(false)
const commitProgress = useSharedValue(0)
const collapse = useSharedValue(0)
const removing = useSharedValue(false)
const [isOpen, setIsOpen] = useState(false)
const close = useCallback(() => {
if (removing.value) return
translateX.value = withSpring(0, SETTLE_SPRING)
setIsOpen(false)
}, [removing, translateX])
const handleSwipeStart = useCallback(() => group.setOpen(close), [close, group])
const handleSettle = useCallback(
(open: boolean) => {
setIsOpen(open)
if (!open) group.clear(close)
},
[close, group]
)
const handleRemove = useCallback(async () => {
group.clear(close)
if (!(await onRemove())) onRestore()
}, [close, group, onRemove, onRestore])
const animateRemoval = useCallback(() => {
"worklet"
removing.value = true
commitProgress.value = withSpring(1, LABEL_SPRING)
translateX.value = withTiming(-width.value, SLIDE_OUT, (slid) => {
if (!slid) return
collapse.value = withTiming(1, COLLAPSE, (collapsed) => {
if (collapsed) scheduleOnRN(handleRemove)
})
})
}, [collapse, commitProgress, handleRemove, removing, translateX, width])
const pan = useMemo(() => {
const gesture = Gesture.Pan()
.failOffsetY([-10, 10])
.onStart(() => {
if (removing.value) return
cancelAnimation(translateX)
startX.value = translateX.value
scheduleOnRN(handleSwipeStart)
})
.onUpdate((event) => {
if (removing.value) return
const rowWidth = width.value
const x = Math.max(
-rowWidth,
Math.min(0, startX.value + event.translationX)
)
translateX.value = x
const shouldCommit = -x > rowWidth * FULL_SWIPE_RATIO
if (shouldCommit !== committed.value) {
committed.value = shouldCommit
commitProgress.value = withSpring(shouldCommit ? 1 : 0, LABEL_SPRING)
scheduleOnRN(impact)
}
})
.onEnd((event) => {
if (removing.value) return
if (committed.value) {
animateRemoval()
return
}
const velocity = event.velocityX
const open =
velocity < -FLING_VELOCITY ||
(velocity <= FLING_VELOCITY && translateX.value < -ACTION_WIDTH / 2)
translateX.value = withSpring(open ? -ACTION_WIDTH : 0, {
...SETTLE_SPRING,
velocity,
})
scheduleOnRN(handleSettle, open)
})
return isOpen
? gesture.activeOffsetX([-10, 10])
: gesture.activeOffsetX(-10).failOffsetX(10)
}, [
animateRemoval,
commitProgress,
committed,
handleSettle,
handleSwipeStart,
isOpen,
removing,
startX,
translateX,
width,
])
const handleLayout = useCallback(
(event: LayoutChangeEvent) => {
if (removing.value) return
width.value = event.nativeEvent.layout.width
height.value = event.nativeEvent.layout.height
},
[height, removing, width]
)
const containerStyle = useAnimatedStyle(() =>
collapse.value > 0 ? { height: height.value * (1 - collapse.value) } : {}
)
const contentStyle = useAnimatedStyle(() => ({
borderRadius: interpolate(
-translateX.value,
[0, CARD_ROUNDING_REVEAL],
[0, height.value / 2],
Extrapolation.CLAMP
),
transform: [{ translateX: translateX.value }],
}))
const cardFillStyle = useAnimatedStyle(() => ({
opacity: interpolate(
-translateX.value,
[0, CARD_ROUNDING_REVEAL],
[0, 1],
Extrapolation.CLAMP
),
}))
const actionStyle = useAnimatedStyle(() => ({
width: -translateX.value,
}))
// The pill grows out of a dot centered in the revealed space; past the
// full-swipe point it stretches to fill that space.
const pillStyle = useAnimatedStyle(() => {
const revealed = -translateX.value
const rowHeight = height.value
const resting = Math.min(
revealed - PILL_MIN_MARGIN * 2,
interpolate(
revealed,
PILL_WIDTH_INPUT,
PILL_WIDTH_OUTPUT,
Extrapolation.EXTEND
)
)
const pillWidth = Math.max(
0,
resting +
(revealed - PILL_COMMITTED_MARGIN * 2 - resting) *
commitProgress.value
)
const restingHeight = interpolate(
pillWidth,
PILL_HEIGHT_INPUT,
PILL_HEIGHT_RATIO.map((ratio) => ratio * rowHeight),
Extrapolation.CLAMP
)
const pillHeight =
restingHeight +
(rowHeight - PILL_COMMITTED_MARGIN * 2 - restingHeight) *
commitProgress.value
return {
width: pillWidth,
height: pillHeight,
borderRadius: pillHeight / 2,
opacity: 1 - collapse.value,
}
})
const iconStyle = useAnimatedStyle(() => ({
transform: [
{
scale: interpolate(
-translateX.value,
[PILL_WIDTH_INPUT[0], ICON_FULL_SIZE_REVEAL],
[0, 1],
Extrapolation.CLAMP
),
},
],
}))
return (
<Animated.View
onLayout={handleLayout}
style={[styles.container, containerStyle]}
>
<Animated.View style={[styles.action, actionStyle]}>
<Pressable
accessibilityRole="button"
accessibilityLabel={actionAccessibilityLabel}
onPress={() => animateRemoval()}
style={styles.actionButton}
>
<Animated.View style={[styles.pill, pillStyle]}>
<Animated.View style={iconStyle}>
<SymbolView
name="minus.circle.fill"
size={20}
tintColor="white"
/>
</Animated.View>
</Animated.View>
</Pressable>
</Animated.View>
<GestureDetector gesture={pan}>
<Animated.View style={[styles.card, { backgroundColor }, contentStyle]}>
<Animated.View
pointerEvents="none"
style={[styles.cardFill, cardFillStyle]}
/>
{children}
{isOpen ? (
<Pressable
accessible={false}
onPress={close}
style={StyleSheet.absoluteFill}
/>
) : null}
</Animated.View>
</GestureDetector>
</Animated.View>
)
}
function impact() {
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium)
}
const styles = StyleSheet.create({
container: { overflow: "hidden" },
card: { overflow: "hidden" },
cardFill: {
...StyleSheet.absoluteFill,
backgroundColor: PlatformColor("tertiarySystemFill"),
},
action: {
position: "absolute",
top: 0,
right: 0,
bottom: 0,
},
actionButton: {
flex: 1,
alignItems: "center",
justifyContent: "center",
},
pill: {
alignItems: "center",
justifyContent: "center",
overflow: "hidden",
backgroundColor: PlatformColor("systemRed"),
},
})
+38 -13
View File
@@ -1,12 +1,20 @@
import { Ionicons } from "@expo/vector-icons" import { Ionicons } from "@expo/vector-icons"
import { memo, useCallback, type ReactElement } from "react" import { memo, useCallback, type ReactElement } from "react"
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native" import {
FlatList,
Pressable,
StyleSheet,
Text,
View,
type ListRenderItemInfo,
} from "react-native"
import { CoverImage } from "@/components/cover-image" import { CoverImage } from "@/components/cover-image"
import { MediaContextMenu } from "@/components/media-context-menu" import { MediaContextMenu } from "@/components/media-context-menu"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { useServerConfig } from "@/contexts/server-config" import { useServerConfig } from "@/contexts/server-config"
import { useAppNavigation } from "@/lib/app-navigation" import { useAppNavigation } from "@/lib/app-navigation"
import { longListProps } from "@/lib/list"
import type { import type {
BrowseAlbum, BrowseAlbum,
BrowseArtist, BrowseArtist,
@@ -23,6 +31,8 @@ import {
export type MediaItem = BrowseAlbum | BrowseArtist | PlaylistSummary export type MediaItem = BrowseAlbum | BrowseArtist | PlaylistSummary
const GRID_INITIAL_ROWS = 5
export const AlbumCard = memo(function AlbumCard({ export const AlbumCard = memo(function AlbumCard({
album, album,
width = carouselCardWidth, width = carouselCardWidth,
@@ -206,12 +216,24 @@ export function MediaGridList({
}) { }) {
const cardWidth = useTwoColumnCardWidth() const cardWidth = useTwoColumnCardWidth()
const colors = useThemeColors() const colors = useThemeColors()
const renderItem = useCallback(
({ item }: ListRenderItemInfo<MediaItem>) => (
<View style={{ width: cardWidth }}>
<CarouselCard item={item} width={cardWidth} />
</View>
),
[cardWidth]
)
return ( return (
<FlatList <FlatList
data={content} data={content}
keyExtractor={(item) => item.id} keyExtractor={mediaItemKey}
renderItem={renderItem}
numColumns={2} numColumns={2}
initialNumToRender={GRID_INITIAL_ROWS}
maxToRenderPerBatch={GRID_INITIAL_ROWS}
windowSize={longListProps.windowSize}
style={{ flex: 1, backgroundColor: colors.background }} style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={[ contentContainerStyle={[
contentInset ? styles.gridListContent : styles.gridListContentInset, contentInset ? styles.gridListContent : styles.gridListContentInset,
@@ -225,15 +247,22 @@ export function MediaGridList({
ListHeaderComponent={ListHeaderComponent} ListHeaderComponent={ListHeaderComponent}
onEndReached={onEndReached} onEndReached={onEndReached}
onEndReachedThreshold={0.5} onEndReachedThreshold={0.5}
renderItem={({ item }) => (
<View style={{ width: cardWidth }}>
<CarouselCard item={item} width={cardWidth} />
</View>
)}
/> />
) )
} }
function mediaItemKey(item: MediaItem) {
return item.id
}
function renderCarouselItem({ item }: ListRenderItemInfo<MediaItem>) {
return (
<View>
<CarouselCard item={item} width={carouselCardWidth} />
</View>
)
}
function ContentCarouselBody({ function ContentCarouselBody({
title, title,
href, href,
@@ -271,15 +300,11 @@ function ContentCarouselBody({
</Pressable> </Pressable>
<FlatList <FlatList
data={content} data={content}
keyExtractor={(item) => item.id} keyExtractor={mediaItemKey}
renderItem={renderCarouselItem}
horizontal horizontal
showsHorizontalScrollIndicator={false} showsHorizontalScrollIndicator={false}
contentContainerStyle={styles.carouselContent} contentContainerStyle={styles.carouselContent}
renderItem={({ item }) => (
<View>
<CarouselCard item={item} width={carouselCardWidth} />
</View>
)}
/> />
</View> </View>
) )
+70 -2
View File
@@ -1,6 +1,12 @@
import { MenuView, type MenuAction } from "@expo/ui/community/menu" import { MenuView, type MenuAction } from "@expo/ui/community/menu"
import type { ReactNode } from "react" import { requireNativeView } from "expo"
import type { StyleProp, ViewStyle } from "react-native" import type { ComponentType, ReactNode } from "react"
import {
Platform,
type StyleProp,
type ViewProps,
type ViewStyle,
} from "react-native"
import { useServerConfig } from "@/contexts/server-config" import { useServerConfig } from "@/contexts/server-config"
import type { MediaShareContext } from "@/lib/media-links" import type { MediaShareContext } from "@/lib/media-links"
@@ -190,7 +196,69 @@ function MediaMenuBase({
) )
} }
// Long-press menus are mounted once per list row. `MenuView` hosts a SwiftUI
// view tree per row, which makes opening long lists stall the main thread, so
// on iOS rows use the UIKit context menu view that ships with expo-router.
const NativeContextMenuView =
Platform.OS === "ios"
? requireNativeView<
ViewProps & { disableForceFlatten?: boolean; children: ReactNode }
>("ExpoRouterNativeLinkPreview", "NativeLinkPreviewView")
: null
const NativeContextMenuAction: ComponentType<{
identifier: string
title: string
icon?: string
onSelected: () => void
}> | null =
Platform.OS === "ios"
? requireNativeView(
"ExpoRouterNativeLinkPreview",
"LinkPreviewNativeActionView"
)
: null
function NativeMediaContextMenu({
children,
onAction,
share,
...actionConfig
}: MediaMenuWrapperProps) {
const { config } = useServerConfig()
if (!NativeContextMenuView || !NativeContextMenuAction) {
return children
}
const handleAction = (action: MediaAction) => {
if (action === "share" && share && config) {
void shareMediaLink(config.serverUrl, share)
return
}
onAction(action)
}
return (
<NativeContextMenuView style={{ display: "contents" }} disableForceFlatten>
{children}
{buildMediaMenuActions({ ...actionConfig, share }).map((action) => (
<NativeContextMenuAction
key={action.id}
identifier={action.id ?? action.title}
title={action.title}
icon={typeof action.image === "string" ? action.image : undefined}
onSelected={() => handleAction(action.id as MediaAction)}
/>
))}
</NativeContextMenuView>
)
}
export function MediaContextMenu(props: MediaMenuWrapperProps) { export function MediaContextMenu(props: MediaMenuWrapperProps) {
if (Platform.OS === "ios") {
return <NativeMediaContextMenu {...props} />
}
return <MediaMenuBase {...props} shouldOpenOnLongPress /> return <MediaMenuBase {...props} shouldOpenOnLongPress />
} }
+110 -21
View File
@@ -1,26 +1,27 @@
import { collectionInset } from "@/components/collection-list"
import { CoverImage } from "@/components/cover-image" import { CoverImage } from "@/components/cover-image"
import { useServerConfig } from "@/contexts/server-config" import { useServerConfig } from "@/contexts/server-config"
import type { BrowseSong } from "@otunes/convex/types" import type { BrowseSong } from "@otunes/convex/types"
import type { CoverPalette } from "@/lib/cover-palette"
import { formatDuration } from "@/lib/format" import { formatDuration } from "@/lib/format"
import { albumCoverUrl } from "@/lib/urls" import { albumCoverUrl } from "@/lib/urls"
import { import { miniPlayerHeight, spacing, useThemeColors } from "@/lib/theme"
miniPlayerHeight, import { memo, useCallback } from "react"
spacing,
tabBarHeight,
useThemeColors,
} from "@/lib/theme"
import { Pressable, StyleSheet, Text, View } from "react-native" import { Pressable, StyleSheet, Text, View } from "react-native"
import { import {
MediaContextMenu, MediaContextMenu,
type MediaAction,
type MediaMenuConfig, type MediaMenuConfig,
} from "@/components/media-context-menu" } from "@/components/media-context-menu"
export function SongRow({ export const SongRow = memo(function SongRow({
song, song,
onPress, onPress,
contextMenu, contextMenu,
trailing, trailing,
palette,
inset = false,
}: { }: {
song: BrowseSong song: BrowseSong
onPress?: () => void onPress?: () => void
@@ -28,14 +29,41 @@ export function SongRow({
onAction: MediaMenuConfig["onAction"] onAction: MediaMenuConfig["onAction"]
} }
trailing?: React.ReactNode trailing?: React.ReactNode
palette?: Pick<CoverPalette, "foreground" | "secondaryForeground" | "divider">
/** Album/playlist layout: the divider starts at the title, not the artwork. */
inset?: boolean
}) { }) {
const { config } = useServerConfig() const { config } = useServerConfig()
const colors = useThemeColors() const colors = useThemeColors()
if (!config) return null if (!config) return null
const foreground = palette?.foreground ?? colors.foreground
const secondaryForeground =
palette?.secondaryForeground ?? colors.mutedForeground
const divider = palette?.divider ?? colors.border
const content = (
<>
<View style={styles.rowMeta}>
<Text style={[styles.rowTitle, { color: foreground }]} numberOfLines={1}>
{song.title}
</Text>
<Text style={[styles.rowSubtitle, { color: secondaryForeground }]} numberOfLines={1}>
{song.artist.name} · {song.album.title}
</Text>
</View>
<Text style={[styles.duration, { color: secondaryForeground }]}>
{formatDuration(song.durationSeconds)}
</Text>
{trailing}
</>
)
const row = ( const row = (
<Pressable <Pressable
style={[styles.row, { borderBottomColor: colors.border }]} style={
inset ? styles.insetRow : [styles.row, { borderBottomColor: divider }]
}
onPress={onPress} onPress={onPress}
> >
<CoverImage <CoverImage
@@ -43,18 +71,13 @@ export function SongRow({
hasCover={song.album.cover != null} hasCover={song.album.cover != null}
style={styles.rowArtwork} style={styles.rowArtwork}
/> />
<View style={styles.rowMeta}> {inset ? (
<Text style={[styles.rowTitle, { color: colors.foreground }]} numberOfLines={1}> <View style={[styles.insetContent, { borderBottomColor: divider }]}>
{song.title} {content}
</Text> </View>
<Text style={[styles.rowSubtitle, { color: colors.mutedForeground }]} numberOfLines={1}> ) : (
{song.artist.name} · {song.album.title} content
</Text> )}
</View>
<Text style={[styles.duration, { color: colors.mutedForeground }]}>
{formatDuration(song.durationSeconds)}
</Text>
{trailing}
</Pressable> </Pressable>
) )
@@ -67,7 +90,55 @@ export function SongRow({
{row} {row}
</MediaContextMenu> </MediaContextMenu>
) )
} })
/**
* A `SongRow` with the standard song context menu. Pass stable `onPlay` and
* `onAction` callbacks so rows in long lists only re-render when their own
* song or favorite state changes.
*/
export const SongListRow = memo(function SongListRow({
song,
favorited,
playlistLabel,
palette,
inset,
onPlay,
onAction,
}: {
song: BrowseSong
favorited: boolean
playlistLabel?: string
palette?: Pick<CoverPalette, "foreground" | "secondaryForeground" | "divider">
inset?: boolean
onPlay: (song: BrowseSong) => void
onAction: (song: BrowseSong, action: MediaAction) => void
}) {
const handlePress = useCallback(() => onPlay(song), [onPlay, song])
return (
<SongRow
song={song}
palette={palette}
inset={inset}
onPress={handlePress}
contextMenu={{
favorited,
playlistLabel,
navigation: {
artist: { id: song.artist.id },
album: { id: song.album.id },
},
share: {
type: "song",
albumId: song.album.id,
songId: song.id,
},
onAction: (action) => onAction(song, action),
}}
/>
)
})
export const tabContentBottomInset = spacing.lg export const tabContentBottomInset = spacing.lg
export const contentBottomInset = miniPlayerHeight + spacing.lg export const contentBottomInset = miniPlayerHeight + spacing.lg
@@ -82,6 +153,24 @@ const styles = StyleSheet.create({
paddingHorizontal: spacing.lg, paddingHorizontal: spacing.lg,
borderBottomWidth: StyleSheet.hairlineWidth, borderBottomWidth: StyleSheet.hairlineWidth,
}, },
insetRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
paddingLeft: collectionInset,
},
insetContent: {
flex: 1,
minWidth: 0,
flexDirection: "row",
alignItems: "center",
alignSelf: "stretch",
gap: spacing.md,
minHeight: 64,
paddingVertical: 10,
marginRight: collectionInset,
borderBottomWidth: StyleSheet.hairlineWidth,
},
rowArtwork: { rowArtwork: {
width: 44, width: 44,
height: 44, height: 44,
@@ -1,8 +1,8 @@
import { useQuery } from "convex/react"
import { Image } from "expo-image" import { Image } from "expo-image"
import { useRouter } from "expo-router" import { useRouter } from "expo-router"
import { Pressable, StyleSheet, Text, View } from "react-native" import { Pressable, StyleSheet, Text, View } from "react-native"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { initialsFromName } from "@/lib/format" import { initialsFromName } from "@/lib/format"
import { radius, useThemeColors } from "@/lib/theme" import { radius, useThemeColors } from "@/lib/theme"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
@@ -10,7 +10,7 @@ import { api } from "@otunes/convex/_generated/api"
export function ProfileHeaderButton() { export function ProfileHeaderButton() {
const router = useRouter() const router = useRouter()
const colors = useThemeColors() const colors = useThemeColors()
const user = useQuery(api.auth.currentUser) const user = useCachedQuery(api.auth.currentUser)
return ( return (
<Pressable <Pressable
+36 -27
View File
@@ -1,12 +1,19 @@
import { useQuery } from "convex/react" import { memo, useCallback, useMemo } from "react"
import { memo, useMemo } from "react" import {
import { FlatList, StyleSheet, Text, View } from "react-native" FlatList,
StyleSheet,
Text,
View,
type ListRenderItemInfo,
} from "react-native"
import { ContentCarousel } from "@/components/media-cards" import { ContentCarousel } from "@/components/media-cards"
import { tabContentBottomInset, SongRow } from "@/components/player" import type { MediaAction } from "@/components/media-context-menu"
import { LoadingView } from "@/components/ui/primitives" import { tabContentBottomInset, SongListRow } from "@/components/player"
import { SongListSkeleton } from "@/components/skeletons"
import { useFavorites } from "@/contexts/favorites" import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback" import { usePlaybackActions } from "@/contexts/playback"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import type { BrowseSong } from "@otunes/convex/types" import type { BrowseSong } from "@otunes/convex/types"
@@ -19,11 +26,11 @@ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
const { handleSongAction } = useMediaMenuActions() const { handleSongAction } = useMediaMenuActions()
const hasQuery = searchQuery.length > 0 const hasQuery = searchQuery.length > 0
const results = useQuery( const results = useCachedQuery(
api.library.searchLibrary, api.library.searchLibrary,
hasQuery ? { query: searchQuery } : "skip" hasQuery ? { query: searchQuery } : "skip"
) )
const playlistResults = useQuery( const playlistResults = useCachedQuery(
api.playlists.searchPlaylists, api.playlists.searchPlaylists,
hasQuery ? { query: searchQuery } : "skip" hasQuery ? { query: searchQuery } : "skip"
) )
@@ -47,9 +54,29 @@ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
() => results?.songs.map((song) => song.id) ?? [], () => results?.songs.map((song) => song.id) ?? [],
[results?.songs] [results?.songs]
) )
const handlePlaySong = useCallback(
(song: BrowseSong) => void playFromSong(song.id, songIds),
[playFromSong, songIds]
)
const handleSongMenuAction = useCallback(
(song: BrowseSong, action: MediaAction) =>
void handleSongAction(song, action),
[handleSongAction]
)
const renderItem = useCallback(
({ item: song }: ListRenderItemInfo<BrowseSong>) => (
<SongListRow
song={song}
favorited={isSongFavorite(song.id)}
onPlay={handlePlaySong}
onAction={handleSongMenuAction}
/>
),
[handlePlaySong, handleSongMenuAction, isSongFavorite]
)
if (isSearching) { if (isSearching) {
return <LoadingView /> return <SongListSkeleton />
} }
if (!hasQuery) { if (!hasQuery) {
@@ -89,25 +116,7 @@ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
) : null} ) : null}
</> </>
} }
renderItem={({ item: song }: { item: BrowseSong }) => ( renderItem={renderItem}
<SongRow
song={song}
onPress={() => void playFromSong(song.id, songIds)}
contextMenu={{
favorited: isSongFavorite(song.id),
navigation: {
artist: { id: song.artist.id },
album: { id: song.album.id },
},
share: {
type: "song",
albumId: song.album.id,
songId: song.id,
},
onAction: (action) => void handleSongAction(song, action),
}}
/>
)}
ListFooterComponent={ ListFooterComponent={
playlistResults && playlistResults.length > 0 ? ( playlistResults && playlistResults.length > 0 ? (
<View style={styles.section}> <View style={styles.section}>
+257
View File
@@ -0,0 +1,257 @@
import { useEffect, useRef } from "react"
import {
Animated,
ScrollView,
StyleSheet,
View,
type DimensionValue,
type StyleProp,
type ViewStyle,
} from "react-native"
import { contentBottomInset } from "@/components/player"
import {
carouselCardWidth,
radius,
spacing,
useThemeColors,
useTwoColumnCardWidth,
} from "@/lib/theme"
export function Skeleton({ style }: { style?: StyleProp<ViewStyle> }) {
const colors = useThemeColors()
const opacity = useRef(new Animated.Value(1)).current
useEffect(() => {
const pulse = Animated.loop(
Animated.sequence([
Animated.timing(opacity, {
toValue: 0.5,
duration: 800,
useNativeDriver: true,
}),
Animated.timing(opacity, {
toValue: 1,
duration: 800,
useNativeDriver: true,
}),
])
)
pulse.start()
return () => pulse.stop()
}, [opacity])
return (
<Animated.View
style={[
{ backgroundColor: colors.muted, borderRadius: radius.sm, opacity },
style,
]}
/>
)
}
function TextLine({
width,
height = 14,
}: {
width: DimensionValue
height?: number
}) {
return <Skeleton style={{ width, height, borderRadius: 4 }} />
}
export function SongRowSkeleton() {
const colors = useThemeColors()
return (
<View style={[styles.songRow, { borderBottomColor: colors.border }]}>
<Skeleton style={styles.songArtwork} />
<View style={styles.songMeta}>
<TextLine width="60%" height={16} />
<TextLine width="40%" />
</View>
</View>
)
}
export function SongListSkeleton({ rows = 10 }: { rows?: number }) {
return (
<View accessibilityLabel="Loading" accessibilityRole="progressbar">
{Array.from({ length: rows }, (_, index) => (
<SongRowSkeleton key={index} />
))}
</View>
)
}
function CardSkeleton({
width,
round = false,
}: {
width: number
round?: boolean
}) {
return (
<View style={[styles.card, { width }]}>
<Skeleton
style={{
width,
height: width,
borderRadius: round ? width / 2 : radius.md,
}}
/>
<TextLine width="80%" />
{round ? null : <TextLine width="50%" height={12} />}
</View>
)
}
export function MediaGridSkeleton({
items = 6,
contentInset = true,
}: {
items?: number
contentInset?: boolean
}) {
const cardWidth = useTwoColumnCardWidth()
return (
<View
accessibilityLabel="Loading"
accessibilityRole="progressbar"
style={[
styles.grid,
contentInset ? styles.gridInset : styles.gridRowInset,
]}
>
{Array.from({ length: items }, (_, index) => (
<CardSkeleton key={index} width={cardWidth} />
))}
</View>
)
}
export function CarouselSkeleton() {
return (
<View style={styles.carousel}>
<TextLine width={160} height={22} />
<View style={styles.carouselRow}>
{Array.from({ length: 3 }, (_, index) => (
<CardSkeleton key={index} width={carouselCardWidth} />
))}
</View>
</View>
)
}
export function HomeSkeleton() {
const colors = useThemeColors()
return (
<ScrollView
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={styles.home}
contentInsetAdjustmentBehavior="automatic"
scrollEnabled={false}
accessibilityLabel="Loading"
>
<CarouselSkeleton />
<CarouselSkeleton />
</ScrollView>
)
}
/** Album and playlist pages: cover, title, play buttons, then tracks. */
export function CollectionDetailSkeleton({
round = false,
}: {
round?: boolean
}) {
const colors = useThemeColors()
const coverSize = round ? 180 : 210
return (
<ScrollView
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
scrollEnabled={false}
accessibilityLabel="Loading"
>
<View style={styles.hero}>
<Skeleton
style={{
width: coverSize,
height: coverSize,
borderRadius: round ? coverSize / 2 : radius.lg,
}}
/>
<TextLine width={200} height={24} />
<TextLine width={120} height={16} />
<View style={styles.actions}>
<Skeleton style={styles.iconAction} />
<Skeleton style={styles.playButton} />
<Skeleton style={styles.iconAction} />
</View>
</View>
{round ? (
<MediaGridSkeleton items={4} contentInset={false} />
) : (
<SongListSkeleton rows={8} />
)}
</ScrollView>
)
}
export function ArtistListSkeleton({ rows = 12 }: { rows?: number }) {
const colors = useThemeColors()
return (
<View accessibilityLabel="Loading" accessibilityRole="progressbar">
{Array.from({ length: rows }, (_, index) => (
<View
key={index}
style={[styles.artistRow, { borderBottomColor: colors.border }]}
>
<Skeleton style={styles.artistAvatar} />
<TextLine width="50%" height={16} />
</View>
))}
</View>
)
}
const styles = StyleSheet.create({
songRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
minHeight: 64,
paddingVertical: 10,
paddingHorizontal: spacing.lg,
borderBottomWidth: StyleSheet.hairlineWidth,
},
songArtwork: { width: 44, height: 44, borderRadius: 6 },
songMeta: { flex: 1, gap: 6 },
card: { gap: spacing.xs },
grid: { flexDirection: "row", flexWrap: "wrap", gap: spacing.md },
gridInset: { padding: spacing.lg },
gridRowInset: { paddingHorizontal: spacing.lg },
carousel: { gap: spacing.md },
carouselRow: { flexDirection: "row", gap: spacing.md },
home: { padding: spacing.lg, gap: spacing.xl },
hero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm },
actions: {
flexDirection: "row",
alignItems: "center",
gap: spacing.sm,
marginTop: spacing.sm,
},
iconAction: { width: 44, height: 44, borderRadius: 22 },
playButton: { width: 160, height: 44, borderRadius: 999 },
artistRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
paddingHorizontal: spacing.lg,
paddingVertical: spacing.md,
borderBottomWidth: StyleSheet.hairlineWidth,
},
artistAvatar: { width: 44, height: 44, borderRadius: 22 },
})
+9 -4
View File
@@ -20,6 +20,8 @@ type ButtonProps = Omit<PressableProps, "style"> & {
loading?: boolean loading?: boolean
icon?: React.ComponentProps<typeof Ionicons>["name"] icon?: React.ComponentProps<typeof Ionicons>["name"]
style?: StyleProp<ViewStyle> style?: StyleProp<ViewStyle>
/** Overrides the variant's colors, e.g. on screens tinted by cover art. */
tint?: { background: string; foreground: string }
} }
export function Button({ export function Button({
@@ -29,13 +31,15 @@ export function Button({
disabled, disabled,
icon, icon,
style, style,
tint,
...props ...props
}: ButtonProps) { }: ButtonProps) {
const colors = useThemeColors() const colors = useThemeColors()
const isDisabled = disabled || loading const isDisabled = disabled || loading
const backgroundColor = const backgroundColor = tint
variant === "primary" ? tint.background
: variant === "primary"
? colors.primary ? colors.primary
: variant === "secondary" : variant === "secondary"
? colors.muted ? colors.muted
@@ -43,8 +47,9 @@ export function Button({
? colors.destructive ? colors.destructive
: "transparent" : "transparent"
const textColor = const textColor = tint
variant === "primary" ? tint.foreground
: variant === "primary"
? colors.primaryForeground ? colors.primaryForeground
: variant === "destructive" : variant === "destructive"
? "#fff" ? "#fff"
+24 -12
View File
@@ -1,4 +1,4 @@
import { useConvex, useMutation, useQuery } from "convex/react" import { useConvex, useMutation } from "convex/react"
import { import {
createContext, createContext,
useCallback, useCallback,
@@ -19,6 +19,9 @@ import {
} from "react-native" } from "react-native"
import { Button, Input } from "@/components/ui/primitives" import { Button, Input } from "@/components/ui/primitives"
import { useCacheScope } from "@/contexts/persistent-cache"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import type { OwnedPlaylistForAdd } from "@otunes/convex/types" import type { OwnedPlaylistForAdd } from "@otunes/convex/types"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
@@ -50,6 +53,7 @@ export function useAddToPlaylist() {
export function AddToPlaylistProvider({ children }: { children: ReactNode }) { export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
const convex = useConvex() const convex = useConvex()
const cacheScope = useCacheScope()
const { push } = useAppNavigation() const { push } = useAppNavigation()
const colors = useThemeColors() const colors = useThemeColors()
const addSongs = useMutation(api.playlists.addSongsToPlaylist) const addSongs = useMutation(api.playlists.addSongsToPlaylist)
@@ -63,7 +67,7 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
const [addingToPlaylistId, setAddingToPlaylistId] = const [addingToPlaylistId, setAddingToPlaylistId] =
useState<Id<"playlists"> | null>(null) useState<Id<"playlists"> | null>(null)
const selectionRequestIdRef = useRef(0) const selectionRequestIdRef = useRef(0)
const ownedPlaylists = useQuery( const ownedPlaylists = useCachedQuery(
api.playlists.listOwnedPlaylists, api.playlists.listOwnedPlaylists,
open ? {} : "skip" open ? {} : "skip"
) )
@@ -92,9 +96,12 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
async (albumId: Id<"albums">) => { async (albumId: Id<"albums">) => {
const requestId = ++selectionRequestIdRef.current const requestId = ++selectionRequestIdRef.current
try { try {
const songIds = await convex.query(api.playlists.getAlbumSongIds, { const songIds = await fetchCachedQuery(
albumId, convex,
}) cacheScope,
api.playlists.getAlbumSongIds,
{ albumId }
)
if (selectionRequestIdRef.current !== requestId) return if (selectionRequestIdRef.current !== requestId) return
setPendingSongIds(songIds) setPendingSongIds(songIds)
setOpen(true) setOpen(true)
@@ -105,16 +112,19 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
) )
} }
}, },
[convex] [convex, cacheScope]
) )
const openAddPlaylistToPlaylist = useCallback( const openAddPlaylistToPlaylist = useCallback(
async (playlistId: Id<"playlists">) => { async (playlistId: Id<"playlists">) => {
const requestId = ++selectionRequestIdRef.current const requestId = ++selectionRequestIdRef.current
try { try {
const songIds = await convex.query(api.playlists.getPlaylistSongIds, { const songIds = await fetchCachedQuery(
playlistId, convex,
}) cacheScope,
api.playlists.getPlaylistSongIds,
{ playlistId }
)
if (selectionRequestIdRef.current !== requestId) return if (selectionRequestIdRef.current !== requestId) return
setPendingSongIds(songIds) setPendingSongIds(songIds)
setOpen(true) setOpen(true)
@@ -125,14 +135,16 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
) )
} }
}, },
[convex] [convex, cacheScope]
) )
const openAddArtistToPlaylist = useCallback( const openAddArtistToPlaylist = useCallback(
async (artistId: Id<"artists">) => { async (artistId: Id<"artists">) => {
const requestId = ++selectionRequestIdRef.current const requestId = ++selectionRequestIdRef.current
try { try {
const songIds = await convex.query( const songIds = await fetchCachedQuery(
convex,
cacheScope,
api.playlists.getOrderedArtistSongIds, api.playlists.getOrderedArtistSongIds,
{ artistId } { artistId }
) )
@@ -146,7 +158,7 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
) )
} }
}, },
[convex] [convex, cacheScope]
) )
const openCreatePlaylist = useCallback(() => { const openCreatePlaylist = useCallback(() => {
+4 -1
View File
@@ -3,6 +3,7 @@ import { ConvexReactClient } from "convex/react"
import { useCallback, useMemo, useState, type ReactNode } from "react" import { useCallback, useMemo, useState, type ReactNode } from "react"
import { ConvexAuthSessionProvider } from "@/contexts/convex-auth-session" import { ConvexAuthSessionProvider } from "@/contexts/convex-auth-session"
import { PersistentCacheProvider } from "@/contexts/persistent-cache"
import { useServerConfig } from "@/contexts/server-config" import { useServerConfig } from "@/contexts/server-config"
import { clearStoredAuthTokens, secureStorage } from "@/lib/auth-storage" import { clearStoredAuthTokens, secureStorage } from "@/lib/auth-storage"
@@ -35,7 +36,9 @@ export function ConvexAppProvider({ children }: { children: ReactNode }) {
storage={secureStorage} storage={secureStorage}
storageNamespace={config.convexUrl} storageNamespace={config.convexUrl}
> >
{children} <PersistentCacheProvider serverUrl={config.serverUrl}>
{children}
</PersistentCacheProvider>
</ConvexAuthProvider> </ConvexAuthProvider>
</ConvexAuthSessionProvider> </ConvexAuthSessionProvider>
) )
+134 -104
View File
@@ -1,16 +1,33 @@
import { useMutation, useQuery } from "convex/react" import type { OptimisticUpdate } from "convex/browser"
import { useMutation, type ReactMutation } from "convex/react"
import type { FunctionArgs, FunctionReference } from "convex/server"
import { import {
createContext, createContext,
useCallback, useCallback,
useContext, useContext,
useMemo, useMemo,
useRef,
type ReactNode, type ReactNode,
} from "react" } from "react"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
import { showError, showSuccess } from "@/lib/toast" import { showError, showSuccess } from "@/lib/toast"
/**
* `useMutation(...).withOptimisticUpdate(...)` with a stable identity. The
* update is captured on first render, so it must not close over render state.
*/
function useOptimisticMutation<Mutation extends FunctionReference<"mutation">>(
mutation: Mutation,
optimisticUpdate: OptimisticUpdate<FunctionArgs<Mutation>>
): ReactMutation<Mutation> {
const base = useMutation(mutation)
const updateRef = useRef(optimisticUpdate)
return useMemo(() => base.withOptimisticUpdate(updateRef.current), [base])
}
type FavoritesContextValue = { type FavoritesContextValue = {
isSongFavorite: (songId: string) => boolean isSongFavorite: (songId: string) => boolean
isAlbumFavorite: (albumId: string) => boolean isAlbumFavorite: (albumId: string) => boolean
@@ -32,103 +49,114 @@ export function useFavorites() {
} }
export function FavoritesProvider({ children }: { children: ReactNode }) { export function FavoritesProvider({ children }: { children: ReactNode }) {
const favorites = useQuery(api.favorites.getUserFavorites) const favorites = useCachedQuery(api.favorites.getUserFavorites)
const favoriteSong = useMutation( const favoriteSong = useOptimisticMutation(
api.favorites.favoriteSong api.favorites.favoriteSong,
).withOptimisticUpdate((store, { songId }) => { (store, { songId }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {}) const current = store.getQuery(api.favorites.getUserFavorites, {})
if (!current || current.favoriteSongs.includes(songId)) return if (!current || current.favoriteSongs.includes(songId)) return
store.setQuery( store.setQuery(
api.favorites.getUserFavorites, api.favorites.getUserFavorites,
{}, {},
{ {
...current, ...current,
favoriteSongs: [...current.favoriteSongs, songId], favoriteSongs: [...current.favoriteSongs, songId],
} }
) )
}) }
const unfavoriteSong = useMutation( )
api.favorites.unfavoriteSong const unfavoriteSong = useOptimisticMutation(
).withOptimisticUpdate((store, { songId }) => { api.favorites.unfavoriteSong,
const current = store.getQuery(api.favorites.getUserFavorites, {}) (store, { songId }) => {
if (!current) return const current = store.getQuery(api.favorites.getUserFavorites, {})
store.setQuery( if (!current) return
api.favorites.getUserFavorites, store.setQuery(
{}, api.favorites.getUserFavorites,
{ {},
...current, {
favoriteSongs: current.favoriteSongs.filter((id) => id !== songId), ...current,
} favoriteSongs: current.favoriteSongs.filter((id) => id !== songId),
) }
}) )
const favoriteAlbum = useMutation( }
api.favorites.favoriteAlbum )
).withOptimisticUpdate((store, { albumId }) => { const favoriteAlbum = useOptimisticMutation(
const current = store.getQuery(api.favorites.getUserFavorites, {}) api.favorites.favoriteAlbum,
if (!current || current.favoriteAlbums.includes(albumId)) return (store, { albumId }) => {
store.setQuery( const current = store.getQuery(api.favorites.getUserFavorites, {})
api.favorites.getUserFavorites, if (!current || current.favoriteAlbums.includes(albumId)) return
{}, store.setQuery(
{ api.favorites.getUserFavorites,
...current, {},
favoriteAlbums: [...current.favoriteAlbums, albumId], {
} ...current,
) favoriteAlbums: [...current.favoriteAlbums, albumId],
}) }
const unfavoriteAlbum = useMutation( )
api.favorites.unfavoriteAlbum }
).withOptimisticUpdate((store, { albumId }) => { )
const current = store.getQuery(api.favorites.getUserFavorites, {}) const unfavoriteAlbum = useOptimisticMutation(
if (!current) return api.favorites.unfavoriteAlbum,
store.setQuery( (store, { albumId }) => {
api.favorites.getUserFavorites, const current = store.getQuery(api.favorites.getUserFavorites, {})
{}, if (!current) return
{ store.setQuery(
...current, api.favorites.getUserFavorites,
favoriteAlbums: current.favoriteAlbums.filter((id) => id !== albumId), {},
} {
) ...current,
}) favoriteAlbums: current.favoriteAlbums.filter((id) => id !== albumId),
const favoriteArtist = useMutation( }
api.favorites.favoriteArtist )
).withOptimisticUpdate((store, { artistId }) => { }
const current = store.getQuery(api.favorites.getUserFavorites, {}) )
if (!current || current.favoriteArtists.includes(artistId)) return const favoriteArtist = useOptimisticMutation(
store.setQuery( api.favorites.favoriteArtist,
api.favorites.getUserFavorites, (store, { artistId }) => {
{}, const current = store.getQuery(api.favorites.getUserFavorites, {})
{ if (!current || current.favoriteArtists.includes(artistId)) return
...current, store.setQuery(
favoriteArtists: [...current.favoriteArtists, artistId], api.favorites.getUserFavorites,
} {},
) {
}) ...current,
const unfavoriteArtist = useMutation( favoriteArtists: [...current.favoriteArtists, artistId],
api.favorites.unfavoriteArtist }
).withOptimisticUpdate((store, { artistId }) => { )
const current = store.getQuery(api.favorites.getUserFavorites, {}) }
if (!current) return )
store.setQuery( const unfavoriteArtist = useOptimisticMutation(
api.favorites.getUserFavorites, api.favorites.unfavoriteArtist,
{}, (store, { artistId }) => {
{ const current = store.getQuery(api.favorites.getUserFavorites, {})
...current, if (!current) return
favoriteArtists: current.favoriteArtists.filter( store.setQuery(
(id) => id !== artistId api.favorites.getUserFavorites,
), {},
} {
) ...current,
}) favoriteArtists: current.favoriteArtists.filter(
const favoriteSongsMutation = useMutation( (id) => id !== artistId
api.favorites.favoriteSongs ),
).withOptimisticUpdate((store, { songIds }) => { }
const current = store.getQuery(api.favorites.getUserFavorites, {}) )
if (!current) return }
store.setQuery(api.favorites.getUserFavorites, {}, { )
...current, const favoriteSongsMutation = useOptimisticMutation(
favoriteSongs: [...new Set([...current.favoriteSongs, ...songIds])], api.favorites.favoriteSongs,
}) (store, { songIds }) => {
}) const current = store.getQuery(api.favorites.getUserFavorites, {})
if (!current) return
store.setQuery(
api.favorites.getUserFavorites,
{},
{
...current,
favoriteSongs: [...new Set([...current.favoriteSongs, ...songIds])],
}
)
}
)
const songIds = useMemo( const songIds = useMemo(
() => new Set(favorites?.favoriteSongs.map(String) ?? []), () => new Set(favorites?.favoriteSongs.map(String) ?? []),
@@ -142,11 +170,13 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
() => new Set(favorites?.favoriteArtists.map(String) ?? []), () => new Set(favorites?.favoriteArtists.map(String) ?? []),
[favorites?.favoriteArtists] [favorites?.favoriteArtists]
) )
const idsRef = useRef({ songIds, albumIds, artistIds })
idsRef.current = { songIds, albumIds, artistIds }
const toggleSongFavorite = useCallback( const toggleSongFavorite = useCallback(
async (songId: Id<"songs">) => { async (songId: Id<"songs">) => {
try { try {
if (songIds.has(songId)) { if (idsRef.current.songIds.has(songId)) {
await unfavoriteSong({ songId }) await unfavoriteSong({ songId })
showSuccess("Removed from favorites") showSuccess("Removed from favorites")
} else { } else {
@@ -159,13 +189,13 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
) )
} }
}, },
[songIds, favoriteSong, unfavoriteSong] [favoriteSong, unfavoriteSong]
) )
const toggleAlbumFavorite = useCallback( const toggleAlbumFavorite = useCallback(
async (albumId: Id<"albums">) => { async (albumId: Id<"albums">) => {
try { try {
if (albumIds.has(albumId)) { if (idsRef.current.albumIds.has(albumId)) {
await unfavoriteAlbum({ albumId }) await unfavoriteAlbum({ albumId })
showSuccess("Removed from favorites") showSuccess("Removed from favorites")
} else { } else {
@@ -178,13 +208,13 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
) )
} }
}, },
[albumIds, favoriteAlbum, unfavoriteAlbum] [favoriteAlbum, unfavoriteAlbum]
) )
const toggleArtistFavorite = useCallback( const toggleArtistFavorite = useCallback(
async (artistId: Id<"artists">) => { async (artistId: Id<"artists">) => {
try { try {
if (artistIds.has(artistId)) { if (idsRef.current.artistIds.has(artistId)) {
await unfavoriteArtist({ artistId }) await unfavoriteArtist({ artistId })
showSuccess("Removed from favorites") showSuccess("Removed from favorites")
} else { } else {
@@ -197,7 +227,7 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
) )
} }
}, },
[artistIds, favoriteArtist, unfavoriteArtist] [favoriteArtist, unfavoriteArtist]
) )
const favoriteSongs = useCallback( const favoriteSongs = useCallback(
+51
View File
@@ -0,0 +1,51 @@
import { useAuthToken } from "@convex-dev/auth/react"
import { createContext, useContext, useMemo, type ReactNode } from "react"
import { loadPersistentCache } from "@/lib/persistent-cache"
export const ANONYMOUS_CACHE_SCOPE = "anon"
const CacheScopeContext = createContext(ANONYMOUS_CACHE_SCOPE)
void loadPersistentCache()
function userIdFromToken(token: string | null) {
const payload = token?.split(".")[1]
if (!payload) {
return null
}
try {
const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"))
const subject = (JSON.parse(json) as { sub?: unknown }).sub
return typeof subject === "string" ? (subject.split("|")[0] ?? null) : null
} catch {
return null
}
}
/** Namespaces persisted client data by server and signed-in user. */
export function PersistentCacheProvider({
serverUrl,
children,
}: {
serverUrl: string
children: ReactNode
}) {
const token = useAuthToken()
const userId = userIdFromToken(token)
const scope = useMemo(
() => (userId ? `${serverUrl}|${userId}` : ANONYMOUS_CACHE_SCOPE),
[serverUrl, userId]
)
return (
<CacheScopeContext.Provider value={scope}>
{children}
</CacheScopeContext.Provider>
)
}
export function useCacheScope() {
return useContext(CacheScopeContext)
}
File diff suppressed because it is too large. Load diff
+88
View File
@@ -0,0 +1,88 @@
import {
usePaginatedQuery,
useQuery,
type OptionalRestArgsOrSkip,
type PaginatedQueryArgs,
type PaginatedQueryItem,
type PaginatedQueryReference,
} from "convex/react"
import type { FunctionReference } from "convex/server"
import { useCallback, useEffect, useSyncExternalStore } from "react"
import { useCacheScope } from "@/contexts/persistent-cache"
import { queryCacheKey } from "@otunes/convex/client/cached-query"
import { readCache, subscribeCache, writeCache } from "@/lib/persistent-cache"
const MAX_CACHED_PAGINATED_ITEMS = 100
const noopUnsubscribe = () => {}
function useCachedValue<T>(key: string | null) {
const subscribe = useCallback(
(listener: () => void) =>
key ? subscribeCache(key, listener) : noopUnsubscribe,
[key]
)
return useSyncExternalStore(subscribe, () =>
key ? readCache<T>(key) : undefined
)
}
/**
* `useQuery` that falls back to the last result persisted on this device while
* the live subscription is loading, so revisits render immediately.
*/
export function useCachedQuery<Query extends FunctionReference<"query">>(
query: Query,
...args: OptionalRestArgsOrSkip<Query>
): Query["_returnType"] | undefined {
const scope = useCacheScope()
const live = useQuery(query, ...args)
const queryArgs = args[0]
const key =
queryArgs === "skip"
? null
: queryCacheKey(
scope,
query,
(queryArgs ?? {}) as Record<string, unknown>
)
const cached = useCachedValue<Query["_returnType"]>(key)
useEffect(() => {
if (key && live !== undefined) {
writeCache(key, live)
}
}, [key, live])
return live !== undefined ? live : cached
}
/**
* `usePaginatedQuery` that shows the first persisted pages while the first live
* page loads. `isCached` is true while those persisted results are shown.
*/
export function useCachedPaginatedQuery<Query extends PaginatedQueryReference>(
query: Query,
args: PaginatedQueryArgs<Query> | "skip",
options: { initialNumItems: number }
) {
const scope = useCacheScope()
const result = usePaginatedQuery(query, args, options)
const key =
args === "skip"
? null
: `${queryCacheKey(scope, query, args as Record<string, unknown>)}:pages`
const cached = useCachedValue<PaginatedQueryItem<Query>[]>(key)
useEffect(() => {
if (key && result.status !== "LoadingFirstPage") {
writeCache(key, result.results.slice(0, MAX_CACHED_PAGINATED_ITEMS))
}
}, [key, result.status, result.results])
if (result.status === "LoadingFirstPage" && cached !== undefined) {
return { ...result, results: cached, isCached: true }
}
return { ...result, isCached: false }
}
@@ -1,58 +0,0 @@
import { useEffect, useState } from "react"
import { getColors, type ImageColorsResult } from "react-native-image-colors"
import { withCoverImageSize } from "@/lib/urls"
function prominentColor(result: ImageColorsResult): string {
switch (result.platform) {
case "ios":
return result.primary || result.background
case "android":
return result.vibrant || result.dominant || result.average
case "web":
return result.vibrant || result.dominant
}
}
export function useCoverBackgroundColor(
uri: string,
hasCover: boolean,
fallback: string,
) {
const [backgroundColor, setBackgroundColor] = useState(fallback)
useEffect(() => {
let cancelled = false
if (!hasCover) {
setBackgroundColor(fallback)
return
}
setBackgroundColor(fallback)
const colorSourceUri = withCoverImageSize(uri, 64)
void getColors(colorSourceUri, {
fallback,
cache: true,
key: colorSourceUri,
quality: "low",
pixelSpacing: 8,
})
.then((result) => {
if (!cancelled) {
setBackgroundColor(prominentColor(result))
}
})
.catch(() => {
if (!cancelled) {
setBackgroundColor(fallback)
}
})
return () => {
cancelled = true
}
}, [fallback, hasCover, uri])
return backgroundColor
}
+163
View File
@@ -0,0 +1,163 @@
import { useEffect, useMemo, useState } from "react"
import { getColors, type ImageColorsResult } from "react-native-image-colors"
import {
deriveCoverPalette,
themeCoverPalette,
type CoverPalette,
type CoverSwatches,
} from "@/lib/cover-palette"
import { readCache, writeCache } from "@/lib/persistent-cache"
import { useIsDark, useThemeColors } from "@/lib/theme"
import { withCoverImageSize } from "@/lib/urls"
// How long a screen holds its skeleton for the first extraction of a cover,
// so rows render once with final colors instead of flashing from the theme.
export const COVER_PALETTE_WAIT_MS = 400
// image-colors substitutes this for swatches it couldn't find.
const MISSING = "#010203"
const swatchesByKey = new Map<string, CoverSwatches | null>()
const pending = new Map<string, Promise<CoverSwatches | null>>()
function cacheKey(colorSourceUri: string) {
return `palette:${colorSourceUri}`
}
function present(colors: (string | undefined)[]) {
return colors.filter(
(color): color is string => !!color && color.toLowerCase() !== MISSING
)
}
function toSwatches(result: ImageColorsResult): CoverSwatches | null {
if (result.platform === "ios") {
const text = present([result.primary, result.secondary, result.detail])
return result.background.toLowerCase() === MISSING
? null
: { background: result.background, text, accent: text }
}
const background = present([result.dominant, result.muted])[0]
if (!background) return null
return {
background,
text: present([
result.lightVibrant,
result.lightMuted,
result.darkVibrant,
result.darkMuted,
result.vibrant,
result.muted,
]),
accent: present([
result.vibrant,
result.lightVibrant,
result.darkVibrant,
result.muted,
]),
}
}
function sameSwatches(
a: CoverSwatches | null | undefined,
b: CoverSwatches | null | undefined
) {
return a === b || JSON.stringify(a) === JSON.stringify(b)
}
function cachedSwatches(key: string): CoverSwatches | null | undefined {
if (swatchesByKey.has(key)) return swatchesByKey.get(key)
return readCache<CoverSwatches>(cacheKey(key))
}
function extractSwatches(key: string) {
const inFlight = pending.get(key)
if (inFlight) return inFlight
const request = getColors(key, {
fallback: MISSING,
cache: true,
key,
quality: "low",
pixelSpacing: 4,
})
.then(toSwatches)
.catch(() => null)
.then((swatches) => {
swatchesByKey.set(key, swatches)
if (swatches) writeCache(cacheKey(key), swatches)
pending.delete(key)
return swatches
})
pending.set(key, request)
return request
}
/**
* Colors for a screen tinted by `uri`'s cover art. Extraction runs once per
* cover and is cached on device. Pass `hasCover` as `undefined` while it isn't
* known yet so extraction can start early.
*
* `settled` turns true once the palette is final or after
* `COVER_PALETTE_WAIT_MS`, whichever comes first.
*/
export function useCoverPalette(
uri: string,
hasCover: boolean | undefined
): { palette: CoverPalette; settled: boolean } {
const theme = useThemeColors()
const isDark = useIsDark()
const key = uri ? withCoverImageSize(uri, 64) : ""
const [resolved, setResolved] = useState(() => ({
key,
swatches: key ? cachedSwatches(key) : null,
}))
const [waitedKey, setWaitedKey] = useState<string | null>(null)
const swatches =
resolved.key === key ? resolved.swatches : key ? cachedSwatches(key) : null
useEffect(() => {
if (!key || hasCover === false) return
let cancelled = false
const known = cachedSwatches(key)
const show = (next: CoverSwatches | null) =>
setResolved((prev) =>
prev.key === key && sameSwatches(prev.swatches, next)
? prev
: { key, swatches: next }
)
if (known !== undefined && swatchesByKey.has(key)) {
show(known)
return
}
// Persisted swatches render immediately; refresh them in the background in
// case the cover changed.
const timer =
known === undefined
? setTimeout(() => !cancelled && setWaitedKey(key), COVER_PALETTE_WAIT_MS)
: null
void extractSwatches(key).then((next) => {
if (!cancelled) show(next ?? known ?? null)
})
return () => {
cancelled = true
if (timer) clearTimeout(timer)
}
}, [hasCover, key])
const palette = useMemo(() => {
const fromArt =
hasCover !== false && swatches ? deriveCoverPalette(swatches, isDark) : null
return fromArt ?? themeCoverPalette(theme, isDark)
}, [hasCover, isDark, swatches, theme])
return {
palette,
settled:
!key || hasCover === false || swatches !== undefined || waitedKey === key,
}
}
+31 -8
View File
@@ -3,11 +3,13 @@ import { useCallback } from "react"
import type { MediaAction } from "@/components/media-context-menu" import type { MediaAction } from "@/components/media-context-menu"
import { useAddToPlaylist } from "@/contexts/add-to-playlist" import { useAddToPlaylist } from "@/contexts/add-to-playlist"
import { useCacheScope } from "@/contexts/persistent-cache"
import { useFavorites } from "@/contexts/favorites" import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback" import { usePlaybackActions } from "@/contexts/playback"
import { useAppNavigation } from "@/lib/app-navigation" import { useAppNavigation } from "@/lib/app-navigation"
import { showError, showSuccess } from "@/lib/toast" import { showError, showSuccess } from "@/lib/toast"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
import type { import type {
BrowseAlbum, BrowseAlbum,
@@ -28,6 +30,7 @@ async function runMediaAction(action: () => Promise<void>) {
export function useMediaMenuActions() { export function useMediaMenuActions() {
const convex = useConvex() const convex = useConvex()
const cacheScope = useCacheScope()
const { push } = useAppNavigation() const { push } = useAppNavigation()
const { const {
openAddToPlaylist, openAddToPlaylist,
@@ -110,9 +113,12 @@ export function useMediaMenuActions() {
case "play-next": case "play-next":
case "play-last": case "play-last":
case "shuffle": { case "shuffle": {
const songIds = await convex.query(api.playlists.getAlbumSongIds, { const songIds = await fetchCachedQuery(
albumId: album.id as Id<"albums">, convex,
}) cacheScope,
api.playlists.getAlbumSongIds,
{ albumId: album.id as Id<"albums"> }
)
await runQueueAction(action, songIds) await runQueueAction(action, songIds)
break break
} }
@@ -124,7 +130,14 @@ export function useMediaMenuActions() {
} }
}) })
}, },
[convex, openAddAlbumToPlaylist, push, runQueueAction, toggleAlbumFavorite] [
convex,
cacheScope,
openAddAlbumToPlaylist,
push,
runQueueAction,
toggleAlbumFavorite,
]
) )
const handleArtistAction = useCallback( const handleArtistAction = useCallback(
@@ -140,7 +153,9 @@ export function useMediaMenuActions() {
case "play-next": case "play-next":
case "play-last": case "play-last":
case "shuffle": { case "shuffle": {
const songIds = await convex.query( const songIds = await fetchCachedQuery(
convex,
cacheScope,
api.playlists.getOrderedArtistSongIds, api.playlists.getOrderedArtistSongIds,
{ artistId: artist.id as Id<"artists"> } { artistId: artist.id as Id<"artists"> }
) )
@@ -152,7 +167,13 @@ export function useMediaMenuActions() {
} }
}) })
}, },
[convex, openAddArtistToPlaylist, runQueueAction, toggleArtistFavorite] [
convex,
cacheScope,
openAddArtistToPlaylist,
runQueueAction,
toggleArtistFavorite,
]
) )
const handlePlaylistAction = useCallback( const handlePlaylistAction = useCallback(
@@ -165,7 +186,9 @@ export function useMediaMenuActions() {
case "play-next": case "play-next":
case "play-last": case "play-last":
case "shuffle": { case "shuffle": {
const songIds = await convex.query( const songIds = await fetchCachedQuery(
convex,
cacheScope,
api.playlists.getPlaylistSongIds, api.playlists.getPlaylistSongIds,
{ {
playlistId: playlist.id as Id<"playlists">, playlistId: playlist.id as Id<"playlists">,
@@ -179,7 +202,7 @@ export function useMediaMenuActions() {
} }
}) })
}, },
[convex, openAddPlaylistToPlaylist, runQueueAction] [convex, cacheScope, openAddPlaylistToPlaylist, runQueueAction]
) )
const handleAlbumDetailAction = useCallback( const handleAlbumDetailAction = useCallback(
+296
View File
@@ -0,0 +1,296 @@
import type { ThemeColors } from "@/lib/theme"
/**
* Colors for a screen tinted by its cover art, modeled on Apple Music's
* artwork colors (`bgColor`, `textColor1`, `textColor2`).
*/
export type CoverPalette = {
background: string
foreground: string
secondaryForeground: string
accent: string
accentForeground: string
/** `accent` adjusted to be legible as body text. */
accentText: string
surface: string
divider: string
isDark: boolean
}
/**
* Raw colors sampled from the art. `background` is the color the art bleeds
* into; `text` is ordered by preference and `accent` holds candidates for the
* Play button.
*/
export type CoverSwatches = {
background: string
text: string[]
accent: string[]
}
// Best effort: `legibleBackground` only guarantees that white or black reaches
// 7:1, so on some backgrounds primary text settles for pure white or black.
const PRIMARY_MIN_CONTRAST = 10
const SECONDARY_MIN_CONTRAST = 4.5
const SECONDARY_TO_PRIMARY_CONTRAST = 0.62
const ACCENT_MIN_CONTRAST = 3
const ACCENT_MIN_CHROMA = 0.05
const ACCENT_MAX_LIGHTNESS_SHIFT = 0.25
// Backgrounds between these luminances can't reach 7:1 with white or black.
const DARK_BACKGROUND_MAX_LUMINANCE = 0.095
const LIGHT_BACKGROUND_MIN_LUMINANCE = 0.31
type Rgb = [number, number, number]
type Oklch = { l: number; c: number; h: number }
export function themeCoverPalette(theme: ThemeColors, isDark: boolean): CoverPalette {
return {
background: theme.background,
foreground: theme.foreground,
secondaryForeground: theme.mutedForeground,
accent: theme.primary,
accentForeground: theme.primaryForeground,
accentText: theme.primary,
surface: theme.muted,
divider: theme.border,
isDark,
}
}
export function deriveCoverPalette(
swatches: CoverSwatches,
schemeIsDark: boolean
): CoverPalette | null {
const source = parseHex(swatches.background)
if (!source) return null
const background = legibleBackground(source, schemeIsDark)
const lightText = prefersLightText(background)
const parsedText = swatches.text
.map(parseHex)
.filter((color): color is Rgb => color !== null)
const backgroundLuminance = luminance(background)
const sameSideText = parsedText.filter((color) =>
lightText
? luminance(color) > backgroundLuminance
: luminance(color) < backgroundLuminance
)
const textCandidates = sameSideText.length > 0 ? sameSideText : parsedText
const fallbackText: Rgb = lightText ? [255, 255, 255] : [0, 0, 0]
const foreground = withMinContrast(
textCandidates[0] ?? fallbackText,
background,
PRIMARY_MIN_CONTRAST
)
const primaryContrast = contrastRatio(foreground, background)
const secondaryTarget = Math.max(
SECONDARY_MIN_CONTRAST,
primaryContrast * SECONDARY_TO_PRIMARY_CONTRAST
)
const secondaryForeground = softenTo(
withMinContrast(
textCandidates[1] ?? foreground,
background,
SECONDARY_MIN_CONTRAST
),
background,
secondaryTarget
)
const accent = pickAccent(swatches.accent, background) ?? foreground
const accentForeground: Rgb = prefersLightText(accent)
? [255, 255, 255]
: [0, 0, 0]
return {
background: toHex(background),
foreground: toHex(foreground),
secondaryForeground: toHex(secondaryForeground),
accent: toHex(accent),
accentForeground: toHex(accentForeground),
accentText: toHex(withMinContrast(accent, background, SECONDARY_MIN_CONTRAST)),
surface: toHex(mix(foreground, background, lightText ? 0.16 : 0.1)),
divider: toHex(mix(foreground, background, lightText ? 0.2 : 0.14)),
isDark: lightText,
}
}
function legibleBackground(color: Rgb, schemeIsDark: boolean): Rgb {
const lch = toOklch(color)
// Keep the art's hue but avoid a glaring page in dark mode or a murky one in
// light mode.
const clamped = schemeIsDark
? withLightness(color, Math.min(lch.l, 0.86))
: withLightness(color, Math.max(lch.l, 0.2))
const y = luminance(clamped)
if (y <= DARK_BACKGROUND_MAX_LUMINANCE || y >= LIGHT_BACKGROUND_MIN_LUMINANCE) {
return clamped
}
const pivot = schemeIsDark ? 0.28 : 0.14
return y < pivot
? withLuminance(clamped, DARK_BACKGROUND_MAX_LUMINANCE)
: withLuminance(clamped, LIGHT_BACKGROUND_MIN_LUMINANCE)
}
function pickAccent(candidates: string[], background: Rgb): Rgb | null {
let best: Rgb | null = null
let bestChroma = ACCENT_MIN_CHROMA
for (const hex of candidates) {
const color = parseHex(hex)
if (!color) continue
const adjusted = withMinContrast(color, background, ACCENT_MIN_CONTRAST)
const before = toOklch(color)
const after = toOklch(adjusted)
// A color pushed far from its own lightness (yellow turned olive) no
// longer reads as coming from the art.
if (Math.abs(after.l - before.l) > ACCENT_MAX_LIGHTNESS_SHIFT) continue
if (after.c > bestChroma) {
best = adjusted
bestChroma = after.c
}
}
return best
}
function prefersLightText(background: Rgb) {
return contrastRatio([255, 255, 255], background) >= contrastRatio([0, 0, 0], background)
}
/** Moves `color`'s lightness away from `background` until it reaches `min`. */
function withMinContrast(color: Rgb, background: Rgb, min: number): Rgb {
if (contrastRatio(color, background) >= min) return color
const lighten = prefersLightText(background)
const start = toOklch(color).l
const extreme = lighten ? 1 : 0
if (contrastRatio(withLightness(color, extreme), background) < min) {
return lighten ? [255, 255, 255] : [0, 0, 0]
}
let near = start
let far = extreme
for (let i = 0; i < 16; i++) {
const mid = (near + far) / 2
if (contrastRatio(withLightness(color, mid), background) >= min) {
far = mid
} else {
near = mid
}
}
return withLightness(color, far)
}
/** Blends `color` toward `background` until its contrast drops to `max`. */
function softenTo(color: Rgb, background: Rgb, max: number): Rgb {
if (contrastRatio(color, background) <= max) return color
let keep = 0
let blend = 1
for (let i = 0; i < 16; i++) {
const mid = (keep + blend) / 2
if (contrastRatio(mix(color, background, mid), background) >= max) {
blend = mid
} else {
keep = mid
}
}
return mix(color, background, blend)
}
function withLuminance(color: Rgb, target: number): Rgb {
let low = 0
let high = 1
for (let i = 0; i < 16; i++) {
const mid = (low + high) / 2
if (luminance(withLightness(color, mid)) < target) {
low = mid
} else {
high = mid
}
}
return withLightness(color, target <= DARK_BACKGROUND_MAX_LUMINANCE ? low : high)
}
/** `amount` of `color` over `base`. */
function mix(color: Rgb, base: Rgb, amount: number): Rgb {
return [0, 1, 2].map((i) =>
Math.round(base[i] + (color[i] - base[i]) * amount)
) as Rgb
}
function contrastRatio(a: Rgb, b: Rgb) {
const la = luminance(a)
const lb = luminance(b)
return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05)
}
function luminance([r, g, b]: Rgb) {
return 0.2126 * toLinear(r) + 0.7152 * toLinear(g) + 0.0722 * toLinear(b)
}
function toLinear(channel: number) {
const c = channel / 255
return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
}
function fromLinear(value: number) {
const c = value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055
return c * 255
}
function toOklch(color: Rgb): Oklch {
const [r, g, b] = color.map(toLinear)
const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b)
const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b)
const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b)
const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s
const A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s
const B = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s
return { l: L, c: Math.hypot(A, B), h: Math.atan2(B, A) }
}
function oklchToLinear({ l: L, c, h }: Oklch): Rgb {
const A = c * Math.cos(h)
const B = c * Math.sin(h)
const l = (L + 0.3963377774 * A + 0.2158037573 * B) ** 3
const m = (L - 0.1055613458 * A - 0.0638541728 * B) ** 3
const s = (L - 0.0894841775 * A - 1.291485548 * B) ** 3
return [
4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
]
}
/** Sets OKLCH lightness, reducing chroma as needed to stay within sRGB. */
function withLightness(color: Rgb, lightness: number): Rgb {
const lch = toOklch(color)
const l = Math.min(1, Math.max(0, lightness))
let c = lch.c
let linear = oklchToLinear({ l, c, h: lch.h })
for (let i = 0; i < 12 && !inGamut(linear); i++) {
c *= 0.8
linear = oklchToLinear({ l, c, h: lch.h })
}
return linear.map((value) =>
Math.round(Math.min(255, Math.max(0, fromLinear(value))))
) as Rgb
}
function inGamut(linear: Rgb) {
return linear.every((value) => value >= -0.0005 && value <= 1.0005)
}
function parseHex(hex: string | undefined): Rgb | null {
if (!hex) return null
const match = /^#?([0-9a-f]{6})/i.exec(hex.trim())
if (!match) return null
const value = parseInt(match[1], 16)
return [(value >> 16) & 255, (value >> 8) & 255, value & 255]
}
function toHex(color: Rgb) {
return `#${color.map((c) => c.toString(16).padStart(2, "0")).join("")}`
}
+9
View File
@@ -0,0 +1,9 @@
/**
* `FlatList` windowing for long media lists: enough rows to fill the first
* screen, and a smaller render window than the default 21 screens.
*/
export const longListProps = {
initialNumToRender: 14,
maxToRenderPerBatch: 10,
windowSize: 11,
} as const
+67
View File
@@ -0,0 +1,67 @@
import AsyncStorage from "@react-native-async-storage/async-storage"
import {
configurePersistentCache,
type PersistentCacheBackend,
type PersistentCacheEntry,
} from "@otunes/convex/client/persistent-cache"
export * from "@otunes/convex/client/persistent-cache"
const KEY_PREFIX = "otunes-cache:"
const READ_BATCH_SIZE = 200
async function cacheStorageKeys() {
const keys = await AsyncStorage.getAllKeys()
return keys.filter((key) => key.startsWith(KEY_PREFIX))
}
const asyncStorageBackend: PersistentCacheBackend = {
async loadAll() {
const keys = await cacheStorageKeys()
const entries: Array<[string, PersistentCacheEntry]> = []
for (let start = 0; start < keys.length; start += READ_BATCH_SIZE) {
const pairs = await AsyncStorage.multiGet(
keys.slice(start, start + READ_BATCH_SIZE)
)
for (const [storageKey, raw] of pairs) {
if (!raw) continue
try {
entries.push([
storageKey.slice(KEY_PREFIX.length),
JSON.parse(raw) as PersistentCacheEntry,
])
} catch {
// Skip entries that were cut off mid-write.
}
}
}
return entries
},
async write(writes) {
const sets: [string, string][] = []
const removes: string[] = []
for (const [key, entry] of writes) {
if (entry === null) {
removes.push(KEY_PREFIX + key)
} else {
sets.push([KEY_PREFIX + key, JSON.stringify(entry)])
}
}
await Promise.all([
sets.length > 0 ? AsyncStorage.multiSet(sets) : null,
removes.length > 0 ? AsyncStorage.multiRemove(removes) : null,
])
},
async clear() {
await AsyncStorage.multiRemove(await cacheStorageKeys())
},
}
// Android's AsyncStorage database is capped at 6 MB by default, so keep fewer
// entries than the web cache.
configurePersistentCache(asyncStorageBackend, {
maxEntriesByPrefix: { q: 200, song: 3000, files: 500, palette: 500 },
})
+48
View File
@@ -0,0 +1,48 @@
import type { ConvexReactClient } from "convex/react"
import type { FunctionReturnType } from "convex/server"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import {
loadPersistentCache,
readCache,
writeCache,
} from "@/lib/persistent-cache"
export type PlaybackSong = NonNullable<
FunctionReturnType<typeof api.library.getSongsForPlayback>[number]
>
function filesKey(scope: string, songId: Id<"songs">) {
return `files:${scope}|${songId}`
}
/**
* Stream info for each song, served from this device when possible so a
* cached queue can start playing without waiting on Convex.
*/
export async function loadPlaybackSongs(
convex: ConvexReactClient,
scope: string,
songIds: Id<"songs">[]
): Promise<(PlaybackSong | null)[]> {
await loadPersistentCache()
const missing = songIds.filter(
(songId) => readCache<PlaybackSong>(filesKey(scope, songId)) === undefined
)
if (missing.length > 0) {
const fetched = await convex.query(api.library.getSongsForPlayback, {
ids: missing,
})
fetched.forEach((song, index) => {
if (song) {
writeCache(filesKey(scope, missing[index]), song)
}
})
}
return songIds.map(
(songId) => readCache<PlaybackSong>(filesKey(scope, songId)) ?? null
)
}
+10
View File
@@ -1,11 +1,21 @@
import type { useRouter } from "expo-router" import type { useRouter } from "expo-router"
import { resetPlaybackStores } from "@otunes/convex/client/playback-store"
import { clearPersistentCache } from "@/lib/persistent-cache"
type AppRouter = ReturnType<typeof useRouter> type AppRouter = ReturnType<typeof useRouter>
/** Forgets this device's cached library and playback state. */
export async function clearLocalData() {
resetPlaybackStores()
await clearPersistentCache()
}
export async function signOutToSignIn( export async function signOutToSignIn(
router: Pick<AppRouter, "replace">, router: Pick<AppRouter, "replace">,
invalidateSession: () => Promise<void> invalidateSession: () => Promise<void>
) { ) {
await invalidateSession() await invalidateSession()
await clearLocalData()
router.replace("/signin") router.replace("/signin")
} }
+67
View File
@@ -0,0 +1,67 @@
import { useConvex } from "convex/react"
import { useEffect, useMemo, useSyncExternalStore } from "react"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong } from "@otunes/convex/types"
import {
getCachedSong,
getSongsVersion,
requestSongs,
subscribeSongs,
} from "@otunes/convex/client/song-cache"
import { isPersistentCacheLoaded } from "@/lib/persistent-cache"
export {
albumDetailSongs,
getCachedSong,
rememberSongs,
} from "@otunes/convex/client/song-cache"
/**
* Resolves song metadata from the persistent song cache, fetching anything
* missing in batches. Entries are `undefined` until loaded.
*/
export function useSongs(songIds: readonly Id<"songs">[]) {
const convex = useConvex()
const songsVersion = useSyncExternalStore(subscribeSongs, getSongsVersion)
const songs = useMemo(
() => songIds.map((songId) => getCachedSong(songId)),
// songsVersion invalidates the lookup when the cache changes.
[songIds, songsVersion]
)
useEffect(() => {
if (!isPersistentCacheLoaded()) {
return
}
const missing = songIds.filter((songId, index) => !songs[index])
if (missing.length > 0) {
requestSongs(convex, missing)
}
}, [convex, songIds, songs])
return songs
}
/**
* Like `useSongs` for one song, but only re-renders when that song changes
* once it is cached.
*/
export function useSong(songId: Id<"songs"> | null): BrowseSong | null {
const convex = useConvex()
// While the song is missing the snapshot is the cache version, so every
// cache change re-renders and retries the fetch below.
const snapshot = useSyncExternalStore(subscribeSongs, () =>
songId ? (getCachedSong(songId) ?? getSongsVersion()) : null
)
const song = typeof snapshot === "object" ? snapshot : null
useEffect(() => {
if (songId && !song && isPersistentCacheLoaded()) {
requestSongs(convex, [songId])
}
}, [convex, songId, song, snapshot])
return song
}
+3
View File
@@ -7,6 +7,9 @@ export const coverImageSizes = [64, 128, 192, 256, 384, 512, 768, 1024] as const
export type CoverImageSize = (typeof coverImageSizes)[number] export type CoverImageSize = (typeof coverImageSizes)[number]
export function withCoverImageSize(uri: string, size: CoverImageSize) { export function withCoverImageSize(uri: string, size: CoverImageSize) {
if (!uri.includes("?") && !uri.includes("#")) {
return `${uri}?size=${size}`
}
const url = new URL(uri) const url = new URL(uri)
url.searchParams.set("size", String(size)) url.searchParams.set("size", String(size))
return url.toString() return url.toString()
@@ -0,0 +1,64 @@
const { createRequire } = require("module");
const expoRequire = createRequire(require.resolve("expo/package.json"));
const { withPodfile } = expoRequire("@expo/config-plugins");
const MARKER = "Xcode 26 rejects Pod deployment targets below iOS 15.0";
const DEPLOYMENT_TARGET_FIX = `
# ${MARKER}. Resource bundles keep the podspec
# version (AsyncStorage 13.4, RNSVG 12.4); React Native only bumps native targets.
installer.pods_project.targets.each do |target|
target.build_configurations.each do |build_config|
deployment_target = build_config.build_settings['IPHONEOS_DEPLOYMENT_TARGET']
next if deployment_target.nil?
next unless deployment_target.to_s.match?(/\\A\\d+(?:\\.\\d+)?\\z/)
if deployment_target.to_f < 15.1
build_config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '15.1'
end
end
end
`;
function insertPodDeploymentTargetFix(contents) {
if (contents.includes(MARKER)) {
return contents;
}
const call = "react_native_post_install(";
const start = contents.indexOf(call);
if (start === -1) {
throw new Error(
"Podfile is missing react_native_post_install, so the iOS deployment target fix could not be applied.",
);
}
let depth = 0;
for (let index = start + call.length - 1; index < contents.length; index += 1) {
const character = contents[index];
if (character === "(") {
depth += 1;
} else if (character === ")") {
depth -= 1;
if (depth === 0) {
const end = index + 1;
return `${contents.slice(0, end)}\n${DEPLOYMENT_TARGET_FIX}${contents.slice(end)}`;
}
}
}
throw new Error(
"Podfile has an unbalanced react_native_post_install call, so the iOS deployment target fix could not be applied.",
);
}
/** Raise Pod target deployment targets to the Xcode 26 minimum. */
function withIosPodDeploymentTarget(config) {
return withPodfile(config, (mod) => {
mod.modResults.contents = insertPodDeploymentTargetFix(mod.modResults.contents);
return mod;
});
}
module.exports = withIosPodDeploymentTarget;
module.exports.insertPodDeploymentTargetFix = insertPodDeploymentTargetFix;
@@ -0,0 +1,125 @@
const { createRequire } = require("module");
const expoRequire = createRequire(require.resolve("expo/package.json"));
const { withAppDelegate, withInfoPlist } = expoRequire("@expo/config-plugins");
const WINDOW_BLOCK = `#if os(iOS) || os(tvOS)
window = UIWindow(frame: UIScreen.main.bounds)
factory.startReactNative(
withModuleName: "main",
in: window,
launchOptions: launchOptions)
#endif`;
const SCENE_DELEGATE = `
@objc(SceneDelegate)
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(
_ scene: UIScene,
willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions
) {
guard let windowScene = scene as? UIWindowScene,
let appDelegate = UIApplication.shared.delegate as? AppDelegate
else {
return
}
if let existingWindow = window {
existingWindow.windowScene = windowScene
return
}
let window = UIWindow(windowScene: windowScene)
self.window = window
appDelegate.window = window
appDelegate.reactNativeFactory?.startReactNative(
withModuleName: "main",
in: window,
launchOptions: appDelegate.launchOptions
)
deliver(connectionOptions, to: appDelegate)
}
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
for context in URLContexts {
_ = appDelegate.application(UIApplication.shared, open: context.url, options: [:])
}
}
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
_ = appDelegate.application(
UIApplication.shared,
continue: userActivity,
restorationHandler: { _ in }
)
}
private func deliver(
_ connectionOptions: UIScene.ConnectionOptions,
to appDelegate: AppDelegate
) {
for context in connectionOptions.urlContexts {
_ = appDelegate.application(UIApplication.shared, open: context.url, options: [:])
}
for userActivity in connectionOptions.userActivities {
_ = appDelegate.application(
UIApplication.shared,
continue: userActivity,
restorationHandler: { _ in }
)
}
}
}
`;
function enableSceneLifecycle(contents) {
if (contents.includes("@objc(SceneDelegate)")) {
return contents;
}
if (!contents.includes(WINDOW_BLOCK)) {
throw new Error(
"AppDelegate.swift is missing the UIWindow startup block, so the UIScene lifecycle could not be applied.",
);
}
let next = contents.replace(
"var window: UIWindow?\n",
"var window: UIWindow?\n var launchOptions: [UIApplication.LaunchOptionsKey: Any]?\n",
);
next = next.replace(
WINDOW_BLOCK,
" // The window is created in SceneDelegate. This SDK refuses to launch without a UIScene.\n self.launchOptions = launchOptions",
);
return `${next.trimEnd()}\n${SCENE_DELEGATE}`;
}
/** Adopt the UIScene lifecycle required by the current iOS SDK. */
function withIosSceneLifecycle(config) {
config = withInfoPlist(config, (mod) => {
mod.modResults.UIApplicationSceneManifest = {
UIApplicationSupportsMultipleScenes: false,
UISceneConfigurations: {
UIWindowSceneSessionRoleApplication: [
{
UISceneConfigurationName: "Default Configuration",
UISceneDelegateClassName: "SceneDelegate",
},
],
},
};
return mod;
});
return withAppDelegate(config, (mod) => {
mod.modResults.contents = enableSceneLifecycle(mod.modResults.contents);
return mod;
});
}
module.exports = withIosSceneLifecycle;
@@ -20,7 +20,7 @@ import { Input } from "@/components/ui/input"
import { ScrollArea } from "@/components/ui/scroll-area" import { ScrollArea } from "@/components/ui/scroll-area"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
import { fetchCachedQuery } from "@/lib/cached-query" import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
function countSongsToAdd( function countSongsToAdd(
playlistSongIds: Id<"songs">[], playlistSongIds: Id<"songs">[],
+1 -1
View File
@@ -26,7 +26,7 @@ import type { BrowseAlbum } from "@otunes/convex/types"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
import { albumCoverUrl } from "@/lib/cover-urls" import { albumCoverUrl } from "@/lib/cover-urls"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import { fetchCachedQuery } from "@/lib/cached-query" import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
let activeAlbumCardMenuClose: (() => void) | null = null let activeAlbumCardMenuClose: (() => void) | null = null
+1 -1
View File
@@ -45,7 +45,7 @@ import { api } from "@otunes/convex/_generated/api"
import { useCachedQuery } from "@/hooks/use-cached-query" import { useCachedQuery } from "@/hooks/use-cached-query"
import { useMounted } from "@/hooks/use-mounted" import { useMounted } from "@/hooks/use-mounted"
import { clearPersistentCache } from "@/lib/persistent-cache" import { clearPersistentCache } from "@/lib/persistent-cache"
import { resetPlaybackStores } from "@/lib/playback-store" import { resetPlaybackStores } from "@otunes/convex/client/playback-store"
const OptionsModal = dynamic(() => const OptionsModal = dynamic(() =>
import("@/components/options-modal").then((module) => module.OptionsModal) import("@/components/options-modal").then((module) => module.OptionsModal)
+1 -1
View File
@@ -23,7 +23,7 @@ import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types" import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types"
import { albumGridClassName } from "@/lib/album-grid-classes" import { albumGridClassName } from "@/lib/album-grid-classes"
import { artistCoverUrl } from "@/lib/cover-urls" import { artistCoverUrl } from "@/lib/cover-urls"
import { fetchCachedQuery } from "@/lib/cached-query" import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
export function ArtistView({ export function ArtistView({
artist, artist,
+1 -1
View File
@@ -24,7 +24,7 @@ import { cn } from "@/lib/utils"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types" import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types"
import { artistCoverUrl } from "@/lib/cover-urls" import { artistCoverUrl } from "@/lib/cover-urls"
import { fetchCachedQuery } from "@/lib/cached-query" import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
function ArtistAvatar({ artist }: { artist: BrowseArtist }) { function ArtistAvatar({ artist }: { artist: BrowseArtist }) {
return ( return (
+46 -21
View File
@@ -15,6 +15,7 @@ import {
CarouselItem, CarouselItem,
CarouselNext, CarouselNext,
CarouselPrevious, CarouselPrevious,
useCarousel,
} from "@/components/ui/carousel" } from "@/components/ui/carousel"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import { ArtistCard } from "./artist-card" import { ArtistCard } from "./artist-card"
@@ -34,6 +35,34 @@ function CarouselCard({
return <ArtistCard artist={item} /> return <ArtistCard artist={item} />
} }
const carouselNavButtonClassName =
"pointer-events-none z-10 h-16! w-6! border-0 bg-primary text-primary-foreground opacity-0 shadow-md transition-opacity hover:bg-primary/80 hover:text-primary-foreground focus-visible:pointer-events-auto! focus-visible:opacity-100! group-hover/carousel:pointer-events-auto! group-hover/carousel:opacity-100! group-focus-within/carousel:pointer-events-auto! group-focus-within/carousel:opacity-100! active:not-aria-[haspopup]:-translate-y-1/2 dark:bg-primary dark:text-primary-foreground dark:hover:bg-primary/80 [@media(hover:none)]:pointer-events-auto! [@media(hover:none)]:opacity-100!"
function CarouselControls() {
const { canScrollPrev, canScrollNext } = useCarousel()
if (!canScrollPrev && !canScrollNext) {
return null
}
return (
<div className="pointer-events-none absolute inset-x-8 top-0 z-10 aspect-[2/1] sm:aspect-[3/1] md:aspect-[4/1] lg:aspect-[5/1] xl:aspect-[6/1]">
{canScrollPrev ? (
<CarouselPrevious
variant="default"
className={cn(carouselNavButtonClassName, "-left-8")}
/>
) : null}
{canScrollNext ? (
<CarouselNext
variant="default"
className={cn(carouselNavButtonClassName, "-right-8")}
/>
) : null}
</div>
)
}
export function ContentCarousel({ export function ContentCarousel({
title, title,
href, href,
@@ -51,40 +80,36 @@ export function ContentCarousel({
}) { }) {
return ( return (
<section className={cn("flex min-w-0 flex-col gap-4", className)}> <section className={cn("flex min-w-0 flex-col gap-4", className)}>
{href ? ( <div className="px-8">
<Link {href ? (
href={href} <Link
className="group inline-flex w-fit items-center gap-1 text-xl font-bold tracking-tight" href={href}
> className="group inline-flex w-fit items-center gap-1 text-xl font-bold tracking-tight"
{title} >
<ChevronRightIcon className="size-5 text-muted-foreground transition-transform group-hover:translate-x-0.5" /> {title}
</Link> <ChevronRightIcon className="size-5 text-muted-foreground transition-transform group-hover:translate-x-0.5" />
) : ( </Link>
<h2 className="text-xl font-bold tracking-tight">{title}</h2> ) : (
)} <h2 className="text-xl font-bold tracking-tight">{title}</h2>
)}
</div>
<Carousel <Carousel
opts={{ opts={{
align: "start", align: "start",
dragFree: true, dragFree: true,
containScroll: false, slidesToScroll: "auto",
slidesToScroll: 5,
}} }}
className="relative min-w-0" className="group/carousel relative min-w-0 px-8"
> >
<CarouselContent <CarouselContent className={cn("w-full", carouselContentClassName)}>
className={cn("w-full", carouselContentClassName)}
>
{content.map((item) => ( {content.map((item) => (
<CarouselItem key={item.id} className={slideClassName}> <CarouselItem key={item.id} className={slideClassName}>
<CarouselCard item={item} /> <CarouselCard item={item} />
</CarouselItem> </CarouselItem>
))} ))}
</CarouselContent> </CarouselContent>
<div className="pointer-events-none absolute top-1/2 flex w-1/2 -translate-y-1/2 justify-between sm:w-2/3 md:w-3/4 lg:w-4/5 xl:w-5/6"> <CarouselControls />
<CarouselPrevious className="relative -left-4 h-16 w-6 bg-primary/90 opacity-0 pointer-events-none hover:pointer-events-auto hover:opacity-100 disabled:pointer-events-none disabled:opacity-0" />
<CarouselNext className="relative -right-2 h-16 w-6 bg-primary/90 opacity-0 pointer-events-none hover:pointer-events-auto hover:opacity-100 disabled:pointer-events-none disabled:opacity-0" />
</div>
</Carousel> </Carousel>
</section> </section>
) )
+9 -3
View File
@@ -848,9 +848,15 @@ function UsersSection({
.catch((error: Error) => toast.error(error.message)) .catch((error: Error) => toast.error(error.message))
}} }}
/> />
<Label htmlFor="disable-signups" className="font-normal"> <div className="space-y-1">
Disable account creation <Label htmlFor="disable-signups" className="font-normal">
</Label> Disable account creation
</Label>
<p className="text-sm text-muted-foreground">
Stops people from registering themselves. You can still create
accounts.
</p>
</div>
</div> </div>
<Button type="button" size="sm" onClick={() => setCreateOpen(true)}> <Button type="button" size="sm" onClick={() => setCreateOpen(true)}>
<UserPlus /> <UserPlus />
+4 -4
View File
@@ -26,15 +26,15 @@ import {
} from "@/components/persistent-cache-provider" } from "@/components/persistent-cache-provider"
import { useCachedQuery } from "@/hooks/use-cached-query" import { useCachedQuery } from "@/hooks/use-cached-query"
import { useMediaSession } from "@/hooks/use-media-session" import { useMediaSession } from "@/hooks/use-media-session"
import { fetchCachedQuery } from "@/lib/cached-query" import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
import { supportsDolbyAtmosPlayback } from "@/lib/dolby-atmos-support" import { supportsDolbyAtmosPlayback } from "@/lib/dolby-atmos-support"
import { flushPersistentCache } from "@/lib/persistent-cache" import { flushPersistentCache } from "@/lib/persistent-cache"
import * as playbackQueue from "@/lib/playback-queue" import * as playbackQueue from "@otunes/convex/client/playback-queue"
import type { RepeatMode } from "@/lib/playback-queue" import type { RepeatMode } from "@otunes/convex/client/playback-queue"
import { import {
getPlaybackStore, getPlaybackStore,
getServerPlaybackSnapshot, getServerPlaybackSnapshot,
} from "@/lib/playback-store" } from "@otunes/convex/client/playback-store"
import { rememberSongs, useSong } from "@/lib/song-cache" import { rememberSongs, useSong } from "@/lib/song-cache"
import { songHlsPlaylistUrl, songPlayUrl } from "@/lib/song-play-url" import { songHlsPlaylistUrl, songPlayUrl } from "@/lib/song-play-url"
+1 -1
View File
@@ -24,7 +24,7 @@ import {
} from "@/components/ui/dropdown-menu" } from "@/components/ui/dropdown-menu"
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import { fetchCachedQuery } from "@/lib/cached-query" import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) { export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
const convex = useConvex() const convex = useConvex()
+1 -1
View File
@@ -12,7 +12,7 @@ import type { FunctionReference } from "convex/server"
import { useCallback, useEffect, useSyncExternalStore } from "react" import { useCallback, useEffect, useSyncExternalStore } from "react"
import { useCacheScope } from "@/components/persistent-cache-provider" import { useCacheScope } from "@/components/persistent-cache-provider"
import { queryCacheKey } from "@/lib/cached-query" import { queryCacheKey } from "@otunes/convex/client/cached-query"
import { readCache, subscribeCache, writeCache } from "@/lib/persistent-cache" import { readCache, subscribeCache, writeCache } from "@/lib/persistent-cache"
const MAX_CACHED_PAGINATED_ITEMS = 200 const MAX_CACHED_PAGINATED_ITEMS = 200
+43 -195
View File
@@ -1,24 +1,16 @@
import {
configurePersistentCache,
type PersistentCacheBackend,
type PersistentCacheEntry,
} from "@otunes/convex/client/persistent-cache"
export * from "@otunes/convex/client/persistent-cache"
const DB_NAME = "otunes-cache" const DB_NAME = "otunes-cache"
const DB_VERSION = 1 const DB_VERSION = 1
const STORE_NAME = "entries" const STORE_NAME = "entries"
const WRITE_DELAY_MS = 250
/** Keys are `<prefix>:<rest>`; prefixes without a limit are never evicted. */
const MAX_ENTRIES_BY_PREFIX: Record<string, number> = {
q: 400,
song: 5000,
}
type Entry = { value: unknown; touchedAt: number }
const memory = new Map<string, Entry>()
const prefixCounts = new Map<string, number>()
const listeners = new Map<string, Set<() => void>>()
const loadListeners = new Set<() => void>()
const pendingWrites = new Map<string, Entry | null>()
let flushTimer: ReturnType<typeof setTimeout> | null = null
let dbPromise: Promise<IDBDatabase | null> | null = null let dbPromise: Promise<IDBDatabase | null> | null = null
let loadPromise: Promise<void> | null = null
let loaded = false
function requestToPromise<T>(request: IDBRequest<T>) { function requestToPromise<T>(request: IDBRequest<T>) {
return new Promise<T>((resolve, reject) => { return new Promise<T>((resolve, reject) => {
@@ -64,36 +56,35 @@ function openDb() {
return dbPromise return dbPromise
} }
function notify(key: string) { const indexedDbBackend: PersistentCacheBackend = {
for (const listener of listeners.get(key) ?? []) { async loadAll() {
listener() const db = await openDb()
} if (!db) {
} return []
}
function notifyAll() { const transaction = db.transaction(STORE_NAME, "readonly")
for (const key of listeners.keys()) { const store = transaction.objectStore(STORE_NAME)
notify(key) const [keys, values] = await Promise.all([
} requestToPromise(store.getAllKeys()),
for (const listener of loadListeners) { requestToPromise(store.getAll() as IDBRequest<PersistentCacheEntry[]>),
listener() ])
} const entries: Array<[string, PersistentCacheEntry]> = []
} keys.forEach((key, index) => {
const entry = values[index]
if (typeof key === "string" && entry) {
entries.push([key, entry])
}
})
return entries
},
async function flushWrites() { async write(writes) {
flushTimer = null const db = await openDb()
if (pendingWrites.size === 0) { if (!db) {
return return
} }
const writes = [...pendingWrites]
pendingWrites.clear()
const db = await openDb()
if (!db) {
return
}
try {
const transaction = db.transaction(STORE_NAME, "readwrite") const transaction = db.transaction(STORE_NAME, "readwrite")
const store = transaction.objectStore(STORE_NAME) const store = transaction.objectStore(STORE_NAME)
for (const [key, entry] of writes) { for (const [key, entry] of writes) {
@@ -104,165 +95,22 @@ async function flushWrites() {
} }
} }
await transactionDone(transaction) await transactionDone(transaction)
} catch { },
// Persisting is best-effort; the in-memory copy stays authoritative.
}
}
function scheduleWrite(key: string, entry: Entry | null) { async clear() {
pendingWrites.set(key, entry)
if (flushTimer === null) {
flushTimer = setTimeout(() => void flushWrites(), WRITE_DELAY_MS)
}
}
function entryPrefix(key: string) {
const index = key.indexOf(":")
return index === -1 ? key : key.slice(0, index)
}
function evictOldEntries(prefix: string, force = false) {
const limit = MAX_ENTRIES_BY_PREFIX[prefix]
const count = prefixCounts.get(prefix) ?? 0
if (limit === undefined || count <= (force ? limit : limit * 1.25)) {
return
}
const oldest = [...memory.entries()]
.filter(([key]) => entryPrefix(key) === prefix)
.sort(([, a], [, b]) => a.touchedAt - b.touchedAt)
.slice(0, count - limit)
for (const [key] of oldest) {
removeFromMemory(key)
scheduleWrite(key, null)
}
}
function setInMemory(key: string, entry: Entry) {
if (!memory.has(key)) {
const prefix = entryPrefix(key)
prefixCounts.set(prefix, (prefixCounts.get(prefix) ?? 0) + 1)
}
memory.set(key, entry)
}
function removeFromMemory(key: string) {
if (memory.delete(key)) {
const prefix = entryPrefix(key)
prefixCounts.set(prefix, (prefixCounts.get(prefix) ?? 1) - 1)
}
}
/** Writes pending entries now instead of after the batching delay. */
export function flushPersistentCache() {
if (flushTimer !== null) {
clearTimeout(flushTimer)
}
void flushWrites()
}
export function loadPersistentCache() {
if (loadPromise) {
return loadPromise
}
loadPromise = (async () => {
const db = await openDb() const db = await openDb()
if (db) { if (!db) {
try { return
const transaction = db.transaction(STORE_NAME, "readonly")
const store = transaction.objectStore(STORE_NAME)
const [keys, values] = await Promise.all([
requestToPromise(store.getAllKeys()),
requestToPromise(store.getAll() as IDBRequest<Entry[]>),
])
keys.forEach((key, index) => {
const entry = values[index]
if (typeof key === "string" && entry && !memory.has(key)) {
setInMemory(key, entry)
}
})
for (const prefix of Object.keys(MAX_ENTRIES_BY_PREFIX)) {
evictOldEntries(prefix, true)
}
} catch {
// Treat an unreadable cache as empty.
}
} }
loaded = true
notifyAll()
})()
return loadPromise
}
export function isPersistentCacheLoaded() {
return loaded
}
export function readCache<T>(key: string): T | undefined {
return memory.get(key)?.value as T | undefined
}
export function writeCache(
key: string,
value: unknown,
options: { notify?: boolean } = {}
) {
const entry = { value, touchedAt: Date.now() }
setInMemory(key, entry)
scheduleWrite(key, entry)
evictOldEntries(entryPrefix(key))
if (options.notify) {
notify(key)
}
}
export async function clearPersistentCache() {
memory.clear()
prefixCounts.clear()
pendingWrites.clear()
if (flushTimer !== null) {
clearTimeout(flushTimer)
flushTimer = null
}
notifyAll()
const db = await openDb()
if (!db) {
return
}
try {
const transaction = db.transaction(STORE_NAME, "readwrite") const transaction = db.transaction(STORE_NAME, "readwrite")
transaction.objectStore(STORE_NAME).clear() transaction.objectStore(STORE_NAME).clear()
await transactionDone(transaction) await transactionDone(transaction)
} catch { },
// Ignore; stale entries are scoped per user and evicted over time.
}
} }
export function subscribeCache(key: string, listener: () => void) { if (typeof window !== "undefined") {
let keyListeners = listeners.get(key) configurePersistentCache(indexedDbBackend, {
if (!keyListeners) { maxEntriesByPrefix: { q: 400, song: 5000 },
keyListeners = new Set() })
listeners.set(key, keyListeners)
}
keyListeners.add(listener)
return () => {
keyListeners.delete(listener)
if (keyListeners.size === 0) {
listeners.delete(key)
}
}
}
export function subscribeCacheLoaded(listener: () => void) {
loadListeners.add(listener)
return () => {
loadListeners.delete(listener)
}
} }
-8
View File
@@ -1,8 +0,0 @@
export function shuffleArray<T>(items: T[]): T[] {
const next = [...items]
for (let i = next.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[next[i], next[j]] = [next[j], next[i]]
}
return next
}
+14 -133
View File
@@ -1,139 +1,20 @@
import { useConvex, type ConvexReactClient } from "convex/react" import { useConvex } from "convex/react"
import { useEffect, useMemo, useSyncExternalStore } from "react" import { useEffect, useMemo, useSyncExternalStore } from "react"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseAlbumDetail, BrowseSong } from "@otunes/convex/types"
import { import {
isPersistentCacheLoaded, getCachedSong,
readCache, getSongsVersion,
subscribeCacheLoaded, requestSongs,
writeCache, subscribeSongs,
} from "@/lib/persistent-cache" } from "@otunes/convex/client/song-cache"
import { isPersistentCacheLoaded } from "@/lib/persistent-cache"
const FETCH_BATCH_SIZE = 100 export {
const FETCH_DELAY_MS = 16 albumDetailSongs,
getCachedSong,
const listeners = new Set<() => void>() rememberSongs,
const missingSongIds = new Set<string>() } from "@otunes/convex/client/song-cache"
const inFlightSongIds = new Set<string>()
const queuedSongIds = new Set<Id<"songs">>()
let version = 0
let fetchTimer: ReturnType<typeof setTimeout> | null = null
function songKey(songId: string) {
return `song:${songId}`
}
function notify() {
version += 1
for (const listener of listeners) {
listener()
}
}
if (typeof window !== "undefined") {
subscribeCacheLoaded(notify)
}
function subscribe(listener: () => void) {
listeners.add(listener)
return () => {
listeners.delete(listener)
}
}
function sameSong(a: BrowseSong, b: BrowseSong) {
return (
a.title === b.title &&
a.durationSeconds === b.durationSeconds &&
a.explicit === b.explicit &&
a.artist.id === b.artist.id &&
a.artist.name === b.artist.name &&
a.artist.photo === b.artist.photo &&
a.album.id === b.album.id &&
a.album.title === b.album.title &&
a.album.cover === b.album.cover
)
}
export function getCachedSong(songId: string) {
return readCache<BrowseSong>(songKey(songId))
}
/** Stores song metadata so the player and queue can render it offline. */
export function rememberSongs(songs: readonly BrowseSong[]) {
let changed = false
for (const song of songs) {
const existing = getCachedSong(song.id)
if (existing && sameSong(existing, song)) {
continue
}
writeCache(songKey(song.id), song)
missingSongIds.delete(song.id)
changed = true
}
if (changed) {
notify()
}
}
export function albumDetailSongs(album: BrowseAlbumDetail): BrowseSong[] {
return album.tracks.map((track) => ({
id: track.id,
title: track.title,
artist: album.artist,
album: { id: album.id, title: album.title, cover: album.cover },
durationSeconds: track.durationSeconds,
}))
}
async function fetchQueuedSongs(convex: ConvexReactClient) {
fetchTimer = null
const ids = [...queuedSongIds]
queuedSongIds.clear()
for (let start = 0; start < ids.length; start += FETCH_BATCH_SIZE) {
const batch = ids.slice(start, start + FETCH_BATCH_SIZE)
try {
const songs = await convex.query(api.library.browseSongsByIds, {
ids: batch,
})
const found = new Set(songs.map((song) => song.id as string))
for (const id of batch) {
if (!found.has(id)) {
missingSongIds.add(id)
}
}
rememberSongs(songs)
} catch {
// Leave them uncached so a later render retries.
} finally {
for (const id of batch) {
inFlightSongIds.delete(id)
}
}
}
notify()
}
function requestSongs(convex: ConvexReactClient, songIds: Id<"songs">[]) {
for (const songId of songIds) {
if (
getCachedSong(songId) ||
missingSongIds.has(songId) ||
inFlightSongIds.has(songId)
) {
continue
}
inFlightSongIds.add(songId)
queuedSongIds.add(songId)
}
if (queuedSongIds.size > 0 && fetchTimer === null) {
fetchTimer = setTimeout(() => void fetchQueuedSongs(convex), FETCH_DELAY_MS)
}
}
/** /**
* Resolves song metadata from the persistent song cache, fetching anything * Resolves song metadata from the persistent song cache, fetching anything
@@ -142,8 +23,8 @@ function requestSongs(convex: ConvexReactClient, songIds: Id<"songs">[]) {
export function useSongs(songIds: readonly Id<"songs">[]) { export function useSongs(songIds: readonly Id<"songs">[]) {
const convex = useConvex() const convex = useConvex()
const songsVersion = useSyncExternalStore( const songsVersion = useSyncExternalStore(
subscribe, subscribeSongs,
() => version, getSongsVersion,
() => 0 () => 0
) )
+1 -1
View File
@@ -8,7 +8,7 @@
# the bundled functions, and never exported to the web server. # the bundled functions, and never exported to the web server.
set -euo pipefail set -euo pipefail
NODE=/opt/node/bin/node NODE=/usr/local/bin/node
CONVEX_DATA_DIR=/convex/data CONVEX_DATA_DIR=/convex/data
FUNCTIONS_DIR=/opt/otunes/convex/packages/convex FUNCTIONS_DIR=/opt/otunes/convex/packages/convex
BACKEND_URL=http://127.0.0.1:3210 BACKEND_URL=http://127.0.0.1:3210
@@ -1,4 +1,3 @@
import type { ConvexReactClient } from "convex/react"
import { import {
getFunctionName, getFunctionName,
type FunctionArgs, type FunctionArgs,
@@ -7,11 +6,15 @@ import {
} from "convex/server" } from "convex/server"
import { convexToJson, type Value } from "convex/values" import { convexToJson, type Value } from "convex/values"
import { import { loadPersistentCache, readCache, writeCache } from "./persistent-cache"
loadPersistentCache,
readCache, /** The part of `ConvexReactClient` the cache needs. */
writeCache, export type QueryClient = {
} from "@/lib/persistent-cache" query<Query extends FunctionReference<"query">>(
query: Query,
args: FunctionArgs<Query>
): Promise<FunctionReturnType<Query>>
}
export function queryCacheKey( export function queryCacheKey(
scope: string, scope: string,
@@ -30,7 +33,7 @@ export function queryCacheKey(
export async function fetchCachedQuery< export async function fetchCachedQuery<
Query extends FunctionReference<"query">, Query extends FunctionReference<"query">,
>( >(
convex: ConvexReactClient, convex: QueryClient,
scope: string, scope: string,
query: Query, query: Query,
args: FunctionArgs<Query> args: FunctionArgs<Query>
+222
View File
@@ -0,0 +1,222 @@
export type PersistentCacheEntry = { value: unknown; touchedAt: number }
/** Storage for persisted entries; `null` in `write` deletes the key. */
export type PersistentCacheBackend = {
loadAll(): Promise<Array<[string, PersistentCacheEntry]>>
write(writes: Array<[string, PersistentCacheEntry | null]>): Promise<void>
clear(): Promise<void>
}
export type PersistentCacheOptions = {
/** Keys are `<prefix>:<rest>`; prefixes without a limit are never evicted. */
maxEntriesByPrefix: Record<string, number>
writeDelayMs?: number
}
const DEFAULT_WRITE_DELAY_MS = 250
const memory = new Map<string, PersistentCacheEntry>()
const prefixCounts = new Map<string, number>()
const listeners = new Map<string, Set<() => void>>()
const loadListeners = new Set<() => void>()
const pendingWrites = new Map<string, PersistentCacheEntry | null>()
let flushTimer: ReturnType<typeof setTimeout> | null = null
let loadPromise: Promise<void> | null = null
let loaded = false
let backend: PersistentCacheBackend | null = null
let options: PersistentCacheOptions = { maxEntriesByPrefix: {} }
let resolveConfigured: () => void
const configured = new Promise<void>((resolve) => {
resolveConfigured = resolve
})
/**
* Must be called once per app before the cache is used. Loading waits until
* then, so modules can read the cache before the app picks a backend.
*/
export function configurePersistentCache(
nextBackend: PersistentCacheBackend,
nextOptions: PersistentCacheOptions
) {
backend = nextBackend
options = nextOptions
resolveConfigured()
}
function notify(key: string) {
for (const listener of listeners.get(key) ?? []) {
listener()
}
}
function notifyAll() {
for (const key of listeners.keys()) {
notify(key)
}
for (const listener of loadListeners) {
listener()
}
}
async function flushWrites() {
flushTimer = null
if (pendingWrites.size === 0 || !backend) {
return
}
const writes = [...pendingWrites]
pendingWrites.clear()
try {
await backend.write(writes)
} catch {
// Persisting is best-effort; the in-memory copy stays authoritative.
}
}
function scheduleWrite(key: string, entry: PersistentCacheEntry | null) {
pendingWrites.set(key, entry)
if (flushTimer === null) {
flushTimer = setTimeout(
() => void flushWrites(),
options.writeDelayMs ?? DEFAULT_WRITE_DELAY_MS
)
}
}
function entryPrefix(key: string) {
const index = key.indexOf(":")
return index === -1 ? key : key.slice(0, index)
}
function evictOldEntries(prefix: string, force = false) {
const limit = options.maxEntriesByPrefix[prefix]
const count = prefixCounts.get(prefix) ?? 0
if (limit === undefined || count <= (force ? limit : limit * 1.25)) {
return
}
const oldest = [...memory.entries()]
.filter(([key]) => entryPrefix(key) === prefix)
.sort(([, a], [, b]) => a.touchedAt - b.touchedAt)
.slice(0, count - limit)
for (const [key] of oldest) {
removeFromMemory(key)
scheduleWrite(key, null)
}
}
function setInMemory(key: string, entry: PersistentCacheEntry) {
if (!memory.has(key)) {
const prefix = entryPrefix(key)
prefixCounts.set(prefix, (prefixCounts.get(prefix) ?? 0) + 1)
}
memory.set(key, entry)
}
function removeFromMemory(key: string) {
if (memory.delete(key)) {
const prefix = entryPrefix(key)
prefixCounts.set(prefix, (prefixCounts.get(prefix) ?? 1) - 1)
}
}
/** Writes pending entries now instead of after the batching delay. */
export function flushPersistentCache() {
if (flushTimer !== null) {
clearTimeout(flushTimer)
}
void flushWrites()
}
export function loadPersistentCache() {
if (loadPromise) {
return loadPromise
}
loadPromise = (async () => {
await configured
try {
const entries = (await backend?.loadAll()) ?? []
for (const [key, entry] of entries) {
if (!memory.has(key)) {
setInMemory(key, entry)
}
}
for (const prefix of Object.keys(options.maxEntriesByPrefix)) {
evictOldEntries(prefix, true)
}
} catch {
// Treat an unreadable cache as empty.
}
loaded = true
notifyAll()
})()
return loadPromise
}
export function isPersistentCacheLoaded() {
return loaded
}
export function readCache<T>(key: string): T | undefined {
return memory.get(key)?.value as T | undefined
}
export function writeCache(
key: string,
value: unknown,
writeOptions: { notify?: boolean } = {}
) {
const entry = { value, touchedAt: Date.now() }
setInMemory(key, entry)
scheduleWrite(key, entry)
evictOldEntries(entryPrefix(key))
if (writeOptions.notify) {
notify(key)
}
}
export async function clearPersistentCache() {
memory.clear()
prefixCounts.clear()
pendingWrites.clear()
if (flushTimer !== null) {
clearTimeout(flushTimer)
flushTimer = null
}
notifyAll()
try {
await backend?.clear()
} catch {
// Ignore; stale entries are scoped per user and evicted over time.
}
}
export function subscribeCache(key: string, listener: () => void) {
let keyListeners = listeners.get(key)
if (!keyListeners) {
keyListeners = new Set()
listeners.set(key, keyListeners)
}
keyListeners.add(listener)
return () => {
keyListeners.delete(listener)
if (keyListeners.size === 0) {
listeners.delete(key)
}
}
}
export function subscribeCacheLoaded(listener: () => void) {
loadListeners.add(listener)
return () => {
loadListeners.delete(listener)
}
}
@@ -1,8 +1,16 @@
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "../convex/_generated/dataModel"
import { shuffleArray } from "@/lib/shuffle-array"
/** Mirrors the queue rules in `packages/convex/convex/playback.ts`. */ /** Mirrors the queue rules in `packages/convex/convex/playback.ts`. */
function shuffleArray<T>(items: T[]): T[] {
const next = [...items]
for (let i = next.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[next[i], next[j]] = [next[j], next[i]]
}
return next
}
export type RepeatMode = "none" | "once" | "always" export type RepeatMode = "none" | "once" | "always"
export type PlaybackQueueState = { export type PlaybackQueueState = {
@@ -1,14 +1,10 @@
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "../convex/_generated/dataModel"
import { import {
EMPTY_PLAYBACK_QUEUE, EMPTY_PLAYBACK_QUEUE,
type PlaybackQueueState, type PlaybackQueueState,
type RepeatMode, type RepeatMode,
} from "@/lib/playback-queue" } from "./playback-queue"
import { import { loadPersistentCache, readCache, writeCache } from "./persistent-cache"
loadPersistentCache,
readCache,
writeCache,
} from "@/lib/persistent-cache"
const SYNC_DELAY_MS = 300 const SYNC_DELAY_MS = 300
const RETRY_DELAYS_MS = [1_000, 3_000, 10_000, 30_000] const RETRY_DELAYS_MS = [1_000, 3_000, 10_000, 30_000]
+135
View File
@@ -0,0 +1,135 @@
import { api } from "../convex/_generated/api"
import type { Id } from "../convex/_generated/dataModel"
import type { BrowseAlbumDetail, BrowseSong } from "../convex/types"
import type { QueryClient } from "./cached-query"
import { readCache, subscribeCacheLoaded, writeCache } from "./persistent-cache"
const FETCH_BATCH_SIZE = 100
const FETCH_DELAY_MS = 16
const listeners = new Set<() => void>()
const missingSongIds = new Set<string>()
const inFlightSongIds = new Set<string>()
const queuedSongIds = new Set<Id<"songs">>()
let version = 0
let fetchTimer: ReturnType<typeof setTimeout> | null = null
function songKey(songId: string) {
return `song:${songId}`
}
function notify() {
version += 1
for (const listener of listeners) {
listener()
}
}
if (typeof window !== "undefined") {
subscribeCacheLoaded(notify)
}
export function subscribeSongs(listener: () => void) {
listeners.add(listener)
return () => {
listeners.delete(listener)
}
}
/** Changes whenever any cached song changes. */
export function getSongsVersion() {
return version
}
function sameSong(a: BrowseSong, b: BrowseSong) {
return (
a.title === b.title &&
a.durationSeconds === b.durationSeconds &&
a.explicit === b.explicit &&
a.artist.id === b.artist.id &&
a.artist.name === b.artist.name &&
a.artist.photo === b.artist.photo &&
a.album.id === b.album.id &&
a.album.title === b.album.title &&
a.album.cover === b.album.cover
)
}
export function getCachedSong(songId: string) {
return readCache<BrowseSong>(songKey(songId))
}
/** Stores song metadata so the player and queue can render it offline. */
export function rememberSongs(songs: readonly BrowseSong[]) {
let changed = false
for (const song of songs) {
const existing = getCachedSong(song.id)
if (existing && sameSong(existing, song)) {
continue
}
writeCache(songKey(song.id), song)
missingSongIds.delete(song.id)
changed = true
}
if (changed) {
notify()
}
}
export function albumDetailSongs(album: BrowseAlbumDetail): BrowseSong[] {
return album.tracks.map((track) => ({
id: track.id,
title: track.title,
artist: album.artist,
album: { id: album.id, title: album.title, cover: album.cover },
durationSeconds: track.durationSeconds,
}))
}
async function fetchQueuedSongs(convex: QueryClient) {
fetchTimer = null
const ids = [...queuedSongIds]
queuedSongIds.clear()
for (let start = 0; start < ids.length; start += FETCH_BATCH_SIZE) {
const batch = ids.slice(start, start + FETCH_BATCH_SIZE)
try {
const songs = await convex.query(api.library.browseSongsByIds, {
ids: batch,
})
const found = new Set(songs.map((song) => song.id as string))
for (const id of batch) {
if (!found.has(id)) {
missingSongIds.add(id)
}
}
rememberSongs(songs)
} catch {
// Leave them uncached so a later render retries.
} finally {
for (const id of batch) {
inFlightSongIds.delete(id)
}
}
}
notify()
}
/** Fetches metadata for songs that are not cached yet, in batches. */
export function requestSongs(convex: QueryClient, songIds: Id<"songs">[]) {
for (const songId of songIds) {
if (
getCachedSong(songId) ||
missingSongIds.has(songId) ||
inFlightSongIds.has(songId)
) {
continue
}
inFlightSongIds.add(songId)
queuedSongIds.add(songId)
}
if (queuedSongIds.size > 0 && fetchTimer === null) {
fetchTimer = setTimeout(() => void fetchQueuedSongs(convex), FETCH_DELAY_MS)
}
}
+21 -15
View File
@@ -21,22 +21,28 @@ export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({
if (existingUserId === null) { if (existingUserId === null) {
const settings = await db.query("appSettings").first() const settings = await db.query("appSettings").first()
if (settings?.disableAccountCreation) { if (settings?.disableAccountCreation) {
const sessions = await db // Self-service sign-up has no admin session. Accounts created from
.query("authSessions") // the admin tools run as that admin, so they stay allowed.
.withIndex("userId", (q) => q.eq("userId", userId)) const actorId = await getAuthUserId(ctx)
.collect() const actor = actorId === null ? null : await db.get(actorId)
for (const session of sessions) { if (!actor?.isAdmin) {
await db.delete(session._id) const sessions = await db
.query("authSessions")
.withIndex("userId", (q) => q.eq("userId", userId))
.collect()
for (const session of sessions) {
await db.delete(session._id)
}
const accounts = await db
.query("authAccounts")
.withIndex("userIdAndProvider", (q) => q.eq("userId", userId))
.collect()
for (const account of accounts) {
await db.delete(account._id)
}
await db.delete(userId)
throw new ConvexError("Account creation is currently disabled")
} }
const accounts = await db
.query("authAccounts")
.withIndex("userIdAndProvider", (q) => q.eq("userId", userId))
.collect()
for (const account of accounts) {
await db.delete(account._id)
}
await db.delete(userId)
throw new ConvexError("Account creation is currently disabled")
} }
const users = await db.query("users").take(2) const users = await db.query("users").take(2)
+20
View File
@@ -22,6 +22,26 @@
"./server-url": { "./server-url": {
"types": "./server-url.ts", "types": "./server-url.ts",
"default": "./server-url.ts" "default": "./server-url.ts"
},
"./client/cached-query": {
"types": "./client/cached-query.ts",
"default": "./client/cached-query.ts"
},
"./client/persistent-cache": {
"types": "./client/persistent-cache.ts",
"default": "./client/persistent-cache.ts"
},
"./client/playback-queue": {
"types": "./client/playback-queue.ts",
"default": "./client/playback-queue.ts"
},
"./client/playback-store": {
"types": "./client/playback-store.ts",
"default": "./client/playback-store.ts"
},
"./client/song-cache": {
"types": "./client/song-cache.ts",
"default": "./client/song-cache.ts"
} }
}, },
"scripts": { "scripts": {