Compare commits
No files matched your search
+30
-156
@@ -1,5 +1,3 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# ============================================
|
||||
# Stage 1: Dependencies Installation Stage
|
||||
# ============================================
|
||||
@@ -9,16 +7,12 @@
|
||||
# To ensure security and compatibility, regularly update the NODE_VERSION ARG to the latest LTS version.
|
||||
ARG NODE_VERSION=24.13.0-slim
|
||||
|
||||
# The Convex backend runs inside the oTunes image. Pin to a commit tag from
|
||||
# https://github.com/get-convex/convex-backend/pkgs/container/convex-backend
|
||||
ARG CONVEX_BACKEND_IMAGE=ghcr.io/get-convex/convex-backend:5c7cb5bc7db457290f1769f95f1d1340912f7fd7
|
||||
FROM node:${NODE_VERSION} AS runner-base
|
||||
|
||||
# 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
|
||||
RUN apt-get update && \
|
||||
apt-get install -y ffmpeg && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
FROM node:${NODE_VERSION} AS node
|
||||
|
||||
FROM node:${NODE_VERSION} AS dependencies
|
||||
|
||||
@@ -35,12 +29,7 @@ RUN printf '%s\n' \
|
||||
'packages:' \
|
||||
' - "apps/web"' \
|
||||
' - "packages/convex"' \
|
||||
>> pnpm-workspace.yaml \
|
||||
&& printf '\n%s\n' \
|
||||
'supportedArchitectures.os=current' \
|
||||
'supportedArchitectures.cpu=current' \
|
||||
'supportedArchitectures.libc=current' \
|
||||
>> .npmrc
|
||||
> pnpm-workspace.yaml
|
||||
|
||||
RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
|
||||
corepack enable pnpm && \
|
||||
@@ -50,168 +39,53 @@ RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
|
||||
# Stage 2: Build Next.js application in standalone mode
|
||||
# ============================================
|
||||
|
||||
# Reuse the installed workspace. Copying node_modules into a new layer retars
|
||||
# hundreds of thousands of files on every source change.
|
||||
# Reuse the installed workspace — no need to re-copy node_modules from a blank image.
|
||||
FROM dependencies AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY apps/web /tmp/src/apps/web
|
||||
COPY packages/convex /tmp/src/packages/convex
|
||||
# Overlay sources; nested node_modules must be dockerignored so they do not
|
||||
# replace the install from the dependencies stage with host pnpm symlinks.
|
||||
COPY apps/web ./apps/web
|
||||
COPY packages/convex ./packages/convex
|
||||
|
||||
# Merge sources onto the install. cp does not remove the existing
|
||||
# node_modules tree, and the build context already dockerignores it.
|
||||
RUN cp -a /tmp/src/apps/web/. ./apps/web/ \
|
||||
&& cp -a /tmp/src/packages/convex/. ./packages/convex/ \
|
||||
&& rm -rf /tmp/src
|
||||
# Re-apply the install tree after source COPY so module resolution cannot be
|
||||
# clobbered even if a nested node_modules slips into the build context.
|
||||
COPY --from=dependencies /app/node_modules ./node_modules
|
||||
COPY --from=dependencies /app/apps/web/node_modules ./apps/web/node_modules
|
||||
COPY --from=dependencies /app/packages/convex/node_modules ./packages/convex/node_modules
|
||||
|
||||
ENV NODE_ENV=production
|
||||
|
||||
ARG NEXT_PUBLIC_CONVEX_URL
|
||||
|
||||
WORKDIR /app/apps/web
|
||||
|
||||
RUN --mount=type=cache,target=/app/apps/web/.next/cache \
|
||||
corepack enable pnpm && pnpm build
|
||||
|
||||
# ============================================
|
||||
# Stage 3: Convex functions, deployed to the bundled backend on boot
|
||||
# Stage 3: Run Next.js application
|
||||
# ============================================
|
||||
|
||||
FROM node:${NODE_VERSION} AS convex-functions
|
||||
FROM runner-base AS runner
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json pnpm-lock.yaml .npmrc ./
|
||||
COPY packages/convex/package.json ./packages/convex/
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=3000
|
||||
ENV HOSTNAME="0.0.0.0"
|
||||
|
||||
RUN printf '%s\n' \
|
||||
'packages:' \
|
||||
' - "packages/convex"' \
|
||||
> pnpm-workspace.yaml \
|
||||
&& printf '\n%s\n' \
|
||||
'supportedArchitectures.os=current' \
|
||||
'supportedArchitectures.cpu=current' \
|
||||
'supportedArchitectures.libc=current' \
|
||||
>> .npmrc
|
||||
RUN mkdir /data
|
||||
|
||||
RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
|
||||
corepack enable pnpm && \
|
||||
pnpm install --frozen-lockfile --prod --filter @otunes/convex...
|
||||
COPY --from=builder --chown=node:node /app/apps/web/public ./apps/web/public
|
||||
COPY --from=builder --chown=node:node /app/apps/web/.next/standalone ./
|
||||
COPY --from=builder --chown=node:node /app/apps/web/.next/static ./apps/web/.next/static
|
||||
|
||||
COPY packages/convex ./packages/convex
|
||||
RUN mkdir -p apps/web/.next && chown -R node:node apps/web/.next
|
||||
|
||||
# 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
|
||||
USER node
|
||||
|
||||
# ============================================
|
||||
# Stage 4: Audio-only ffmpeg
|
||||
# ============================================
|
||||
EXPOSE 3000
|
||||
|
||||
FROM ubuntu:24.04 AS ffmpeg
|
||||
|
||||
ARG FFMPEG_VERSION
|
||||
ARG FFMPEG_SHA256
|
||||
|
||||
RUN apt-get update && \
|
||||
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/*
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
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 docker/generate-auth-keys.mjs /opt/otunes/generate-auth-keys.mjs
|
||||
COPY --chmod=755 docker/entrypoint.sh /usr/local/bin/otunes-entrypoint
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=builder --chown=otunes:otunes /app/apps/web/public ./apps/web/public
|
||||
COPY --from=builder --chown=otunes:otunes /app/apps/web/.next/standalone ./
|
||||
COPY --from=builder --chown=otunes:otunes /app/apps/web/.next/static ./apps/web/.next/static
|
||||
|
||||
RUN mkdir -p apps/web/.next /data && chown -R otunes:otunes apps/web/.next
|
||||
|
||||
ENV PATH="/usr/local/bin:${PATH}"
|
||||
|
||||
EXPOSE 3000 3210
|
||||
|
||||
HEALTHCHECK --interval=10s --timeout=5s --start-period=60s \
|
||||
CMD curl -fsS http://127.0.0.1:3210/version && curl -fsS -o /dev/null http://127.0.0.1:3000/signin
|
||||
|
||||
ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/otunes-entrypoint"]
|
||||
CMD []
|
||||
CMD ["node", "apps/web/server.js"]
|
||||
@@ -40,12 +40,6 @@ Run the Convex backend (from the shared package):
|
||||
pnpm dev:convex
|
||||
```
|
||||
|
||||
Point the dev deployment at your music folder (it defaults to `/data`):
|
||||
|
||||
```bash
|
||||
cd packages/convex && npx convex env set DATA "/path/to/Music"
|
||||
```
|
||||
|
||||
Other commands:
|
||||
|
||||
```bash
|
||||
@@ -57,39 +51,61 @@ pnpm format # format with Prettier
|
||||
|
||||
## Hosting with Docker
|
||||
|
||||
The image runs both the web app and its Convex backend, so there is nothing to configure. Here's an example `docker-compose.yml`:
|
||||
Here's an example `docker-compose.yml` file to get you started:
|
||||
|
||||
```yaml
|
||||
name: music
|
||||
services:
|
||||
otunes:
|
||||
image: git.abunchofknowitalls.com/joshuafhiggins/otunes:latest
|
||||
ports:
|
||||
- "3000:3000" # web app
|
||||
- "3210:3210" # Convex
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
- ./otunes-data:/convex/data
|
||||
- /SomeAttachedStorage/Music:/data
|
||||
stop_grace_period: 10s
|
||||
environment:
|
||||
- NEXT_PUBLIC_CONVEX_URL=http://127.0.0.1:3210
|
||||
- CONVEX_SELF_HOSTED_URL=http://127.0.0.1:3210
|
||||
- CONVEX_SELF_HOSTED_ADMIN_KEY=REPLACE_ME
|
||||
restart: unless-stopped
|
||||
image: otunes
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
- NEXT_PUBLIC_CONVEX_URL=http://127.0.0.1:3210
|
||||
backend:
|
||||
stop_grace_period: 10s
|
||||
stop_signal: SIGINT
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "3210:3210"
|
||||
- "3211:3211"
|
||||
volumes:
|
||||
- ./database:/convex/data
|
||||
environment:
|
||||
- CONVEX_CLOUD_ORIGIN=http://127.0.0.1:3210
|
||||
- CONVEX_SITE_ORIGIN=http://127.0.0.1:3211
|
||||
- APPLICATION_MAX_CONCURRENT_MUTATIONS=16
|
||||
- APPLICATION_MAX_CONCURRENT_NODE_ACTIONS=16
|
||||
- APPLICATION_MAX_CONCURRENT_QUERIES=16
|
||||
- APPLICATION_MAX_CONCURRENT_V8_ACTIONS=16
|
||||
- DISABLE_BEACON=true
|
||||
- DISABLE_METRICS_ENDPOINT=true
|
||||
- DOCUMENT_RETENTION_DELAY=172800
|
||||
- DO_NOT_REQUIRE_SSL=true
|
||||
- REDACT_LOGS_TO_CLIENT=true
|
||||
- RUST_LOG=info
|
||||
image: ghcr.io/get-convex/convex-backend:latest
|
||||
healthcheck:
|
||||
test: curl -f http://localhost:3210/version
|
||||
interval: 5s
|
||||
start_period: 10s
|
||||
```
|
||||
|
||||
Change `/SomeAttachedStorage/Music` to the folder containing your `lossless`, `normal`, and `atmos` libraries, then run `docker compose up -d`. The first account you create becomes the admin.
|
||||
First run `docker compose up -d backend` and `docker compose exec backend ./generate_admin_key.sh` to generate the admin key needed for the frontend. Take this key and put it in the `CONVEX_SELF_HOSTED_ADMIN_KEY` environment variable for the `otunes` service.
|
||||
|
||||
On first boot the container generates its own Convex instance secret and sign-in keys and stores them in `./otunes-data`, so no two installs share secrets. Back up that folder: it holds your database and keys.
|
||||
`CONVEX_SELF_HOSTED_URL`, `CONVEX_CLOUD_ORIGIN`, and `NEXT_PUBLIC_CONVEX_URL` should be changed to the same reversed proxied, SSL protected, domain and `CONVEX_SITE_ORIGIN` on a different domain.
|
||||
|
||||
### Reverse proxy
|
||||
|
||||
The web app finds Convex from the address you open it at:
|
||||
|
||||
| You open | Convex is expected at |
|
||||
| --- | --- |
|
||||
| `https://music.example.com` | `https://convex.music.example.com` |
|
||||
| `http://192.168.1.5:3000` or `http://localhost:3000` | port `3210` on the same host |
|
||||
|
||||
So for a domain, point `music.example.com` at port `3000` and `convex.music.example.com` at port `3210` (WebSockets must be allowed). The mobile app uses the same convention.
|
||||
|
||||
If Convex has to live somewhere else, set `PUBLIC_CONVEX_URL` on the container to its public URL.
|
||||
Then change `/SomeAttachedStorage/Music` to the path where your music is stored and run `docker compose down && docker compose up -d` to start the whole app together.
|
||||
|
||||
## Downloads
|
||||
|
||||
|
||||
@@ -65,9 +65,7 @@
|
||||
}
|
||||
],
|
||||
"expo-image",
|
||||
"expo-status-bar",
|
||||
"./plugins/with-ios-pod-deployment-target.js",
|
||||
"./plugins/with-ios-scene-lifecycle.js"
|
||||
"expo-status-bar"
|
||||
],
|
||||
"experiments": {
|
||||
"typedRoutes": true
|
||||
|
||||
@@ -1,38 +1,26 @@
|
||||
import { Stack, useIsFocused, useLocalSearchParams } from "expo-router"
|
||||
import { StatusBar } from "expo-status-bar"
|
||||
import { memo, useCallback, useEffect, useMemo } from "react"
|
||||
import { useQuery } from "convex/react"
|
||||
import { Stack, useLocalSearchParams } from "expo-router"
|
||||
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
|
||||
import {
|
||||
CollectionDivider,
|
||||
collectionInset,
|
||||
DiscHeader,
|
||||
} from "@/components/collection-list"
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
|
||||
import {
|
||||
MediaActionMenu,
|
||||
MediaContextMenu,
|
||||
type MediaAction,
|
||||
} from "@/components/media-actions-sheet"
|
||||
import { CollectionDetailSkeleton } from "@/components/skeletons"
|
||||
import { Button } from "@/components/ui/primitives"
|
||||
import { Button, LoadingView } from "@/components/ui/primitives"
|
||||
import { contentBottomInset } from "@/components/player"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlaybackActions } from "@/contexts/playback"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useCoverPalette } from "@/hooks/use-cover-palette"
|
||||
import { useCoverBackgroundColor } from "@/hooks/use-cover-background-color"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { BrowseAlbumDetail, BrowseAlbumTrack } from "@otunes/convex/types"
|
||||
import type { CoverPalette } from "@/lib/cover-palette"
|
||||
import type { BrowseAlbumTrack } from "@otunes/convex/types"
|
||||
import { formatDuration, formatMetadata } from "@/lib/format"
|
||||
import { useAppNavigation } from "@/lib/app-navigation"
|
||||
import { longListProps } from "@/lib/list"
|
||||
import { albumDetailSongs, rememberSongs } from "@/lib/song-cache"
|
||||
import { albumCoverUrl } from "@/lib/urls"
|
||||
import { radius, spacing, useThemeColors } from "@/lib/theme"
|
||||
|
||||
@@ -41,7 +29,7 @@ export default function AlbumScreen() {
|
||||
const { push } = useAppNavigation()
|
||||
const colors = useThemeColors()
|
||||
const { config } = useServerConfig()
|
||||
const album = useCachedQuery(
|
||||
const album = useQuery(
|
||||
api.library.browseAlbumDetail,
|
||||
typeof id === "string" ? { id: id as Id<"albums"> } : "skip"
|
||||
)
|
||||
@@ -53,55 +41,15 @@ export default function AlbumScreen() {
|
||||
handleAlbumTrackAction,
|
||||
isAlbumFavorite: isAlbumFav,
|
||||
} = useMediaMenuActions()
|
||||
const isFocused = useIsFocused()
|
||||
const coverUri =
|
||||
config && typeof id === "string" ? albumCoverUrl(config.serverUrl, id) : ""
|
||||
const { palette, settled } = useCoverPalette(
|
||||
config && album ? albumCoverUrl(config.serverUrl, album.id) : ""
|
||||
const backgroundColor = useCoverBackgroundColor(
|
||||
coverUri,
|
||||
album ? album.cover != null : album === null ? false : undefined
|
||||
)
|
||||
const songIds = useMemo(
|
||||
() => album?.tracks.map((track) => track.id as Id<"songs">) ?? [],
|
||||
[album]
|
||||
album?.cover != null,
|
||||
colors.background
|
||||
)
|
||||
|
||||
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) {
|
||||
if (album === undefined || !config) {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
@@ -110,7 +58,7 @@ export default function AlbumScreen() {
|
||||
headerLargeTitle: false,
|
||||
}}
|
||||
/>
|
||||
<CollectionDetailSkeleton />
|
||||
<LoadingView />
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -133,19 +81,17 @@ export default function AlbumScreen() {
|
||||
)
|
||||
}
|
||||
|
||||
const songIds = album.tracks.map(
|
||||
(track: BrowseAlbumTrack) => track.id as Id<"songs">
|
||||
)
|
||||
const metadata = formatMetadata(album.genre, album.year)
|
||||
const favorited = isAlbumFavorite(album.id)
|
||||
|
||||
return (
|
||||
<>
|
||||
{isFocused ? (
|
||||
<StatusBar style={palette.isDark ? "light" : "dark"} />
|
||||
) : null}
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "",
|
||||
headerLargeTitle: false,
|
||||
headerTintColor: palette.foreground,
|
||||
headerRight: () => (
|
||||
<MediaActionMenu
|
||||
selectedCount={album.tracks.length}
|
||||
@@ -163,7 +109,7 @@ export default function AlbumScreen() {
|
||||
<Ionicons
|
||||
name="ellipsis-horizontal"
|
||||
size={22}
|
||||
color={palette.foreground}
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
</MediaActionMenu>
|
||||
@@ -171,201 +117,115 @@ export default function AlbumScreen() {
|
||||
}}
|
||||
/>
|
||||
<FlatList
|
||||
{...longListProps}
|
||||
data={listItems}
|
||||
keyExtractor={albumListItemKey}
|
||||
style={{ flex: 1, backgroundColor: palette.background }}
|
||||
data={album.tracks}
|
||||
keyExtractor={(track) => track.id}
|
||||
style={{ flex: 1, backgroundColor }}
|
||||
contentContainerStyle={{ paddingBottom: contentBottomInset }}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
indicatorStyle={palette.isDark ? "white" : "black"}
|
||||
ListHeaderComponent={
|
||||
<View>
|
||||
<View style={styles.hero}>
|
||||
<CoverImage
|
||||
uri={coverUri}
|
||||
hasCover={album.cover != null}
|
||||
style={styles.cover}
|
||||
/>
|
||||
<Text style={[styles.title, { color: palette.foreground }]}>
|
||||
{album.title}
|
||||
<View style={styles.hero}>
|
||||
<CoverImage
|
||||
uri={coverUri}
|
||||
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 onPress={() => push(`/artist/${album.artist.id}`)}>
|
||||
<Text style={[styles.artist, { color: palette.accentText }]}>
|
||||
{album.artist.name}
|
||||
</Text>
|
||||
</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>
|
||||
{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
|
||||
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>
|
||||
</Pressable>
|
||||
<Button
|
||||
title="Play"
|
||||
icon="play"
|
||||
onPress={() => void playAlbum(album.id)}
|
||||
style={styles.playButton}
|
||||
/>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Shuffle"
|
||||
hitSlop={8}
|
||||
onPress={() => void playAlbumShuffled(album.id)}
|
||||
style={[styles.iconAction, { backgroundColor: colors.muted }]}
|
||||
>
|
||||
<Ionicons name="shuffle" size={24} color={colors.foreground} />
|
||||
</Pressable>
|
||||
</View>
|
||||
<CollectionDivider color={palette.divider} />
|
||||
</View>
|
||||
}
|
||||
renderItem={renderItem}
|
||||
renderItem={({ item: track, index }) => (
|
||||
<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({
|
||||
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
|
||||
hero: {
|
||||
@@ -398,22 +258,13 @@ const styles = StyleSheet.create({
|
||||
trackRow: {
|
||||
flexDirection: "row",
|
||||
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,
|
||||
minHeight: 52,
|
||||
minHeight: 60,
|
||||
paddingHorizontal: spacing.lg,
|
||||
paddingVertical: 12,
|
||||
marginRight: collectionInset,
|
||||
borderBottomWidth: StyleSheet.hairlineWidth,
|
||||
},
|
||||
trackNumber: { width: 24, textAlign: "center" },
|
||||
trackMeta: { flex: 1, minWidth: 0 },
|
||||
trackTitle: { fontSize: 16, fontWeight: "500" },
|
||||
})
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useQuery } from "convex/react"
|
||||
import { Stack, useLocalSearchParams } from "expo-router"
|
||||
import { Pressable, StyleSheet, Text, View } from "react-native"
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
@@ -6,13 +7,11 @@ import { CoverImage } from "@/components/cover-image"
|
||||
|
||||
import { MediaGridList } from "@/components/media-cards"
|
||||
import { MediaActionMenu } from "@/components/media-actions-sheet"
|
||||
import { CollectionDetailSkeleton } from "@/components/skeletons"
|
||||
import { Button } from "@/components/ui/primitives"
|
||||
import { Button, LoadingView } from "@/components/ui/primitives"
|
||||
import { contentBottomInset } from "@/components/player"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlaybackActions } from "@/contexts/playback"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
@@ -23,7 +22,7 @@ export default function ArtistScreen() {
|
||||
const { id } = useLocalSearchParams<{ id: string }>()
|
||||
const colors = useThemeColors()
|
||||
const { config } = useServerConfig()
|
||||
const data = useCachedQuery(
|
||||
const data = useQuery(
|
||||
api.library.browseArtistDetail,
|
||||
typeof id === "string" ? { id: id as Id<"artists"> } : "skip"
|
||||
)
|
||||
@@ -41,7 +40,7 @@ export default function ArtistScreen() {
|
||||
headerLargeTitle: false,
|
||||
}}
|
||||
/>
|
||||
<CollectionDetailSkeleton round />
|
||||
<LoadingView />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import { usePaginatedQuery, useQuery } from "convex/react"
|
||||
import { Stack } from "expo-router"
|
||||
import { useCallback } from "react"
|
||||
|
||||
import { MediaGridList } from "@/components/media-cards"
|
||||
import { MediaGridSkeleton } from "@/components/skeletons"
|
||||
import { LoadingView } from "@/components/ui/primitives"
|
||||
import { contentBottomInset } from "@/components/player"
|
||||
import {
|
||||
useCachedPaginatedQuery,
|
||||
useCachedQuery,
|
||||
} from "@/hooks/use-cached-query"
|
||||
import { useDebouncedSearch } from "@/hooks/use-debounced-search"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
@@ -15,20 +12,16 @@ const PAGE_SIZE = 50
|
||||
|
||||
export default function AlbumsScreen() {
|
||||
const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch()
|
||||
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
|
||||
const { results, status, loadMore } = usePaginatedQuery(
|
||||
api.library.browseAlbumsPaginated,
|
||||
{},
|
||||
{ initialNumItems: PAGE_SIZE }
|
||||
)
|
||||
const searchResults = useCachedQuery(
|
||||
const searchResults = useQuery(
|
||||
api.library.searchLibrary,
|
||||
searchQuery ? { query: searchQuery } : "skip"
|
||||
)
|
||||
const albums = searchQuery
|
||||
? searchResults?.albums
|
||||
: status === "LoadingFirstPage" && !isCached
|
||||
? undefined
|
||||
: results
|
||||
const albums = searchQuery ? searchResults?.albums : results
|
||||
|
||||
const handleChangeText = useCallback(
|
||||
(event: { nativeEvent: { text: string } }) => {
|
||||
@@ -53,7 +46,7 @@ export default function AlbumsScreen() {
|
||||
return (
|
||||
<>
|
||||
{searchBar}
|
||||
<MediaGridSkeleton />
|
||||
<LoadingView />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,32 +1,19 @@
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
import { usePaginatedQuery, useQuery } from "convex/react"
|
||||
import { Stack } from "expo-router"
|
||||
import { memo, useCallback } from "react"
|
||||
import {
|
||||
FlatList,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
type ListRenderItemInfo,
|
||||
} from "react-native"
|
||||
import { useCallback } from "react"
|
||||
import { FlatList, Pressable, StyleSheet, Text } from "react-native"
|
||||
|
||||
import {
|
||||
MediaContextMenu,
|
||||
type MediaAction,
|
||||
} from "@/components/media-context-menu"
|
||||
import { MediaContextMenu } from "@/components/media-context-menu"
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
import { ArtistListSkeleton } from "@/components/skeletons"
|
||||
import { LoadingView } from "@/components/ui/primitives"
|
||||
import { contentBottomInset } from "@/components/player"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import {
|
||||
useCachedPaginatedQuery,
|
||||
useCachedQuery,
|
||||
} from "@/hooks/use-cached-query"
|
||||
import { useDebouncedSearch } from "@/hooks/use-debounced-search"
|
||||
import { useAppNavigation } from "@/lib/app-navigation"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { BrowseArtist } from "@otunes/convex/types"
|
||||
import { longListProps } from "@/lib/list"
|
||||
import { artistCoverUrl } from "@/lib/urls"
|
||||
import { spacing, useThemeColors } from "@/lib/theme"
|
||||
|
||||
@@ -37,39 +24,17 @@ export default function ArtistsScreen() {
|
||||
const colors = useThemeColors()
|
||||
const { config } = useServerConfig()
|
||||
const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch()
|
||||
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
|
||||
const { results, status, loadMore } = usePaginatedQuery(
|
||||
api.library.browseArtistsPaginated,
|
||||
{},
|
||||
{ initialNumItems: PAGE_SIZE }
|
||||
)
|
||||
const searchResults = useCachedQuery(
|
||||
const searchResults = useQuery(
|
||||
api.library.searchLibrary,
|
||||
searchQuery ? { query: searchQuery } : "skip"
|
||||
)
|
||||
const { handleArtistAction, isArtistFavorite } = useMediaMenuActions()
|
||||
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 artists = searchQuery ? searchResults?.artists : results
|
||||
|
||||
const handleChangeText = useCallback(
|
||||
(event: { nativeEvent: { text: string } }) => {
|
||||
@@ -94,7 +59,7 @@ export default function ArtistsScreen() {
|
||||
return (
|
||||
<>
|
||||
{searchBar}
|
||||
<ArtistListSkeleton />
|
||||
<LoadingView />
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -104,70 +69,46 @@ export default function ArtistsScreen() {
|
||||
{searchBar}
|
||||
|
||||
<FlatList
|
||||
{...longListProps}
|
||||
data={artists}
|
||||
keyExtractor={artistKey}
|
||||
renderItem={renderItem}
|
||||
keyExtractor={(artist) => artist.id}
|
||||
style={{ flex: 1, backgroundColor: colors.background }}
|
||||
contentContainerStyle={styles.listContent}
|
||||
contentContainerStyle={{ paddingBottom: contentBottomInset }}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
onEndReached={() => {
|
||||
if (!searchQuery && status === "CanLoadMore") loadMore(PAGE_SIZE)
|
||||
}}
|
||||
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({
|
||||
listContent: { paddingBottom: contentBottomInset },
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useQuery } from "convex/react"
|
||||
import { Pressable } from "react-native"
|
||||
|
||||
import { MediaGridList } from "@/components/media-cards"
|
||||
import { MediaGridSkeleton } from "@/components/skeletons"
|
||||
import { LoadingView } from "@/components/ui/primitives"
|
||||
import { tabContentBottomInset } from "@/components/player"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { useThemeColors } from "@/lib/theme"
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
@@ -13,7 +13,7 @@ import { useAddToPlaylist } from "@/contexts/add-to-playlist"
|
||||
|
||||
export default function PlaylistsTabScreen() {
|
||||
const colors = useThemeColors()
|
||||
const playlists = useCachedQuery(api.playlists.listAllPlaylists)
|
||||
const playlists = useQuery(api.playlists.listAllPlaylists)
|
||||
const { openCreatePlaylist } = useAddToPlaylist()
|
||||
|
||||
if (playlists === undefined) {
|
||||
@@ -38,7 +38,7 @@ export default function PlaylistsTabScreen() {
|
||||
),
|
||||
}}
|
||||
/>
|
||||
<MediaGridSkeleton />
|
||||
<LoadingView />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,21 +1,17 @@
|
||||
import { usePaginatedQuery, useQuery } from "convex/react"
|
||||
import { Stack } from "expo-router"
|
||||
import { useCallback, useState } from "react"
|
||||
import { FlatList, StyleSheet, type ListRenderItemInfo } from "react-native"
|
||||
import { FlatList, StyleSheet } from "react-native"
|
||||
|
||||
import type { MediaAction } from "@/components/media-context-menu"
|
||||
import { contentBottomInset, SongListRow } from "@/components/player"
|
||||
import { SongListSkeleton } from "@/components/skeletons"
|
||||
import { contentBottomInset, SongRow } from "@/components/player"
|
||||
import { LoadingView } from "@/components/ui/primitives"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlaybackActions } from "@/contexts/playback"
|
||||
import {
|
||||
useCachedPaginatedQuery,
|
||||
useCachedQuery,
|
||||
} from "@/hooks/use-cached-query"
|
||||
import { useDebouncedSearch } from "@/hooks/use-debounced-search"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
import { longListProps } from "@/lib/list"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { spacing } from "@/lib/theme"
|
||||
|
||||
const PAGE_SIZE = 50
|
||||
|
||||
@@ -27,42 +23,16 @@ export default function SongsScreen() {
|
||||
const [sortKey, setSortKey] = useState<"title" | "artist" | "album">("title")
|
||||
const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc")
|
||||
|
||||
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
|
||||
const { results, status, loadMore } = usePaginatedQuery(
|
||||
api.library.browseSongsPaginated,
|
||||
{ sortKey, sortDirection },
|
||||
{ initialNumItems: PAGE_SIZE }
|
||||
)
|
||||
const searchResults = useCachedQuery(
|
||||
const searchResults = useQuery(
|
||||
api.library.searchLibrary,
|
||||
searchQuery ? { query: searchQuery } : "skip"
|
||||
)
|
||||
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 songs = searchQuery ? searchResults?.songs : results
|
||||
|
||||
const handleChangeText = useCallback(
|
||||
(event: { nativeEvent: { text: string } }) => {
|
||||
@@ -87,7 +57,7 @@ export default function SongsScreen() {
|
||||
return (
|
||||
<>
|
||||
{searchBar}
|
||||
<SongListSkeleton />
|
||||
<LoadingView />
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -97,25 +67,49 @@ export default function SongsScreen() {
|
||||
{searchBar}
|
||||
|
||||
<FlatList
|
||||
{...longListProps}
|
||||
data={songs}
|
||||
keyExtractor={songKey}
|
||||
renderItem={renderItem}
|
||||
contentContainerStyle={styles.listContent}
|
||||
keyExtractor={(item) => item.id}
|
||||
contentContainerStyle={{ paddingBottom: contentBottomInset }}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
onEndReached={() => {
|
||||
if (!searchQuery && status === "CanLoadMore") loadMore(PAGE_SIZE)
|
||||
}}
|
||||
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({
|
||||
listContent: { paddingBottom: contentBottomInset },
|
||||
sortRow: {
|
||||
flexDirection: "row",
|
||||
justifyContent: "space-around",
|
||||
paddingVertical: spacing.sm,
|
||||
borderBottomWidth: StyleSheet.hairlineWidth,
|
||||
},
|
||||
sortButton: { padding: spacing.sm },
|
||||
})
|
||||
@@ -1,10 +1,10 @@
|
||||
import { memo } from "react"
|
||||
import { usePaginatedQuery } from "convex/react"
|
||||
import { memo, useRef } from "react"
|
||||
import { ScrollView, StyleSheet } from "react-native"
|
||||
|
||||
import { ContentCarousel } from "@/components/media-cards"
|
||||
import { HomeSkeleton } from "@/components/skeletons"
|
||||
import { LoadingView } from "@/components/ui/primitives"
|
||||
import { tabContentBottomInset } from "@/components/player"
|
||||
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { BrowseAlbum, PlaylistSummary } from "@otunes/convex/types"
|
||||
import { spacing, useThemeColors } from "@/lib/theme"
|
||||
@@ -38,26 +38,34 @@ const HomeCarousels = memo(function HomeCarousels({
|
||||
|
||||
export default function HomeScreen() {
|
||||
const colors = useThemeColors()
|
||||
const recentlyAdded = useCachedPaginatedQuery(
|
||||
const { results: recentlyAdded } = usePaginatedQuery(
|
||||
api.library.browseRecentlyAddedPaginated,
|
||||
{},
|
||||
{ initialNumItems: CAROUSEL_ITEM_LIMIT }
|
||||
)
|
||||
const recentlyPlayed = useCachedPaginatedQuery(
|
||||
const { results: recentlyPlayed } = usePaginatedQuery(
|
||||
api.library.browseRecentlyPlayedPaginated,
|
||||
{},
|
||||
{ initialNumItems: CAROUSEL_ITEM_LIMIT }
|
||||
)
|
||||
const cachedData = useRef<{
|
||||
recentlyAdded?: BrowseAlbum[]
|
||||
recentlyPlayed?: (BrowseAlbum | PlaylistSummary)[]
|
||||
}>({})
|
||||
|
||||
const isLoading = [recentlyAdded, recentlyPlayed].some(
|
||||
(result) => result.status === "LoadingFirstPage" && !result.isCached
|
||||
)
|
||||
if (isLoading) {
|
||||
return <HomeSkeleton />
|
||||
if (recentlyAdded !== undefined) {
|
||||
cachedData.current.recentlyAdded = recentlyAdded
|
||||
}
|
||||
if (recentlyPlayed !== undefined) {
|
||||
cachedData.current.recentlyPlayed = recentlyPlayed
|
||||
}
|
||||
|
||||
const added = recentlyAdded.results.slice(0, CAROUSEL_ITEM_LIMIT)
|
||||
const played = recentlyPlayed.results.slice(0, CAROUSEL_ITEM_LIMIT)
|
||||
const added = recentlyAdded ?? cachedData.current.recentlyAdded
|
||||
const played = recentlyPlayed ?? cachedData.current.recentlyPlayed
|
||||
|
||||
if (added === undefined || played === undefined) {
|
||||
return <LoadingView />
|
||||
}
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
|
||||
@@ -1,12 +1,24 @@
|
||||
import { useMutation } from "convex/react"
|
||||
import { memo, useCallback, useEffect, useMemo } from "react"
|
||||
import { useMutation, usePaginatedQuery, useQuery } from "convex/react"
|
||||
import {
|
||||
Stack,
|
||||
useIsFocused,
|
||||
useLocalSearchParams,
|
||||
useRouter,
|
||||
} from "expo-router"
|
||||
import { StatusBar } from "expo-status-bar"
|
||||
Button as SwiftUIButton,
|
||||
ContextMenu,
|
||||
Host,
|
||||
List,
|
||||
RNHostView,
|
||||
SwipeActions,
|
||||
} 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 {
|
||||
FlatList,
|
||||
Platform,
|
||||
@@ -14,63 +26,41 @@ import {
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
type ListRenderItemInfo,
|
||||
} from "react-native"
|
||||
import ReanimatedSwipeable from "react-native-gesture-handler/ReanimatedSwipeable"
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
|
||||
import { CollectionDivider } from "@/components/collection-list"
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
import {
|
||||
SwipeToRemoveRow,
|
||||
useSwipeRowGroup,
|
||||
type SwipeRowGroup,
|
||||
} from "@/components/ios-swipe-to-remove-row"
|
||||
|
||||
import {
|
||||
MediaActionMenu,
|
||||
type MediaAction,
|
||||
} from "@/components/media-actions-sheet"
|
||||
import { CollectionDetailSkeleton } from "@/components/skeletons"
|
||||
import { Button } from "@/components/ui/primitives"
|
||||
import { contentBottomInset, SongListRow } from "@/components/player"
|
||||
import { Button, LoadingView } from "@/components/ui/primitives"
|
||||
import { contentBottomInset, SongRow } from "@/components/player"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlaybackActions } from "@/contexts/playback"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import {
|
||||
useCachedPaginatedQuery,
|
||||
useCachedQuery,
|
||||
} from "@/hooks/use-cached-query"
|
||||
import { useCoverPalette } from "@/hooks/use-cover-palette"
|
||||
import { useCoverBackgroundColor } from "@/hooks/use-cover-background-color"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { BrowsePlaylistDetail, BrowseSong } from "@otunes/convex/types"
|
||||
import type { CoverPalette } from "@/lib/cover-palette"
|
||||
import { longListProps } from "@/lib/list"
|
||||
import { rememberSongs } from "@/lib/song-cache"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
import { shareMediaLink } from "@/lib/share-media-link"
|
||||
import { showError, showSuccess } from "@/lib/toast"
|
||||
import { playlistCoverUrl } from "@/lib/urls"
|
||||
import { radius, spacing, useThemeColors } from "@/lib/theme"
|
||||
|
||||
const PAGE_SIZE = 50
|
||||
const PLAYLIST_LABEL = "Add to Another Playlist"
|
||||
const OWNER_MENU_ACTIONS: MediaAction[] = [
|
||||
"share",
|
||||
"playlist",
|
||||
"play-next",
|
||||
"play-last",
|
||||
"shuffle",
|
||||
"favorite",
|
||||
"delete-playlist",
|
||||
]
|
||||
const NATIVE_LOAD_MORE_THRESHOLD = 10
|
||||
|
||||
export default function PlaylistScreen() {
|
||||
const { id } = useLocalSearchParams<{ id: string }>()
|
||||
const router = useRouter()
|
||||
const colors = useThemeColors()
|
||||
const { config } = useServerConfig()
|
||||
const playlistId = typeof id === "string" ? (id as Id<"playlists">) : null
|
||||
const playlist = useCachedQuery(
|
||||
const playlist = useQuery(
|
||||
api.playlists.browsePlaylistDetail,
|
||||
playlistId
|
||||
? {
|
||||
@@ -83,34 +73,38 @@ export default function PlaylistScreen() {
|
||||
results: songs,
|
||||
status,
|
||||
loadMore,
|
||||
isCached,
|
||||
} = useCachedPaginatedQuery(
|
||||
} = usePaginatedQuery(
|
||||
api.playlists.browsePlaylistSongsPaginated,
|
||||
playlistId ? { id: playlistId } : "skip",
|
||||
{ initialNumItems: PAGE_SIZE }
|
||||
)
|
||||
const allSongIds = useCachedQuery(
|
||||
const allSongIds = useQuery(
|
||||
api.playlists.getPlaylistSongIds,
|
||||
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 =
|
||||
config && playlistId
|
||||
? playlistCoverUrl(config.serverUrl, playlist?.id ?? playlistId)
|
||||
config && playlist
|
||||
? playlistCoverUrl(config.serverUrl, playlist.id ?? "favorites")
|
||||
: ""
|
||||
const { palette, settled } = useCoverPalette(
|
||||
const backgroundColor = useCoverBackgroundColor(
|
||||
coverUri,
|
||||
playlist ? playlist.cover != null : playlist === null ? false : undefined
|
||||
playlist?.cover != null,
|
||||
colors.background
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
rememberSongs(songs)
|
||||
}, [songs])
|
||||
|
||||
if (
|
||||
playlist === undefined ||
|
||||
(status === "LoadingFirstPage" && !isCached) ||
|
||||
!config ||
|
||||
!settled
|
||||
songs === undefined ||
|
||||
allSongIds === undefined ||
|
||||
!config
|
||||
) {
|
||||
return (
|
||||
<>
|
||||
@@ -120,7 +114,7 @@ export default function PlaylistScreen() {
|
||||
headerLargeTitle: false,
|
||||
}}
|
||||
/>
|
||||
<CollectionDetailSkeleton />
|
||||
<LoadingView />
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -143,99 +137,21 @@ export default function PlaylistScreen() {
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<PlaylistContent
|
||||
playlist={playlist}
|
||||
songs={songs}
|
||||
allSongIds={allSongIds}
|
||||
coverUri={coverUri}
|
||||
palette={palette}
|
||||
onEndReached={() => {
|
||||
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
const songIds = allSongIds
|
||||
const serverUrl = config.serverUrl
|
||||
|
||||
function PlaylistContent({
|
||||
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)
|
||||
function maybeLoadMore() {
|
||||
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
|
||||
}
|
||||
|
||||
const playlistId = playlist.id
|
||||
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
|
||||
async function handleSubscribeToggle() {
|
||||
if (!playlist?.id) return
|
||||
try {
|
||||
if (isSubscribed) {
|
||||
await unsubscribe({ playlistId })
|
||||
if (playlist.isSubscribed) {
|
||||
await unsubscribe({ playlistId: playlist.id })
|
||||
showSuccess("Unsubscribed")
|
||||
} else {
|
||||
await subscribe({ playlistId })
|
||||
await subscribe({ playlistId: playlist.id })
|
||||
showSuccess("Subscribed")
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -243,222 +159,318 @@ function PlaylistContent({
|
||||
error instanceof Error ? error.message : "Failed to update subscription"
|
||||
)
|
||||
}
|
||||
}, [isSubscribed, playlistId, subscribe, unsubscribe])
|
||||
}
|
||||
|
||||
const screenOptions = useMemo(() => {
|
||||
async function handleDelete() {
|
||||
if (!playlistId) return
|
||||
try {
|
||||
await deletePlaylist({ playlistId })
|
||||
showSuccess("Playlist deleted")
|
||||
router.back()
|
||||
} catch (error) {
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to delete playlist"
|
||||
)
|
||||
}
|
||||
async function handleDelete() {
|
||||
if (!playlist?.id) return
|
||||
try {
|
||||
await deletePlaylist({ playlistId: playlist.id })
|
||||
showSuccess("Playlist deleted")
|
||||
router.back()
|
||||
} catch (error) {
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to delete playlist"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function handlePlaylistMenuAction(action: MediaAction) {
|
||||
if (action === "delete-playlist") {
|
||||
void handleDelete()
|
||||
return
|
||||
}
|
||||
|
||||
function handlePlaylistMenuAction(action: MediaAction) {
|
||||
if (action === "delete-playlist") {
|
||||
void handleDelete()
|
||||
return
|
||||
}
|
||||
void handlePlaylistDetailAction(songIds, action)
|
||||
}
|
||||
|
||||
void handlePlaylistDetailAction(songIds, action)
|
||||
async function handleRemoveSong(songId: Id<"songs">) {
|
||||
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"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
title: "",
|
||||
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
|
||||
function renderSongRow(song: BrowseSong, includeContextMenu = true) {
|
||||
const row = (
|
||||
<SongRow
|
||||
song={song}
|
||||
favorited={isSongFavorite(song.id)}
|
||||
removable={canEdit}
|
||||
palette={palette}
|
||||
swipeGroup={swipeGroup}
|
||||
onPlay={handlePlaySong}
|
||||
onAction={handleSongMenuAction}
|
||||
onRemove={handleRemoveSong}
|
||||
onPress={() => void playFromSong(song.id, songIds)}
|
||||
contextMenu={
|
||||
includeContextMenu
|
||||
? {
|
||||
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),
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
),
|
||||
[
|
||||
canEdit,
|
||||
handlePlaySong,
|
||||
handleRemoveSong,
|
||||
handleSongMenuAction,
|
||||
isSongFavorite,
|
||||
palette,
|
||||
swipeGroup,
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
return row
|
||||
}
|
||||
|
||||
function renderNativeSongContextMenu(song: BrowseSong) {
|
||||
return (
|
||||
<ContextMenu.Items>
|
||||
<SwiftUIButton
|
||||
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 (
|
||||
<>
|
||||
{isFocused ? (
|
||||
<StatusBar style={palette.isDark ? "light" : "dark"} />
|
||||
) : null}
|
||||
<Stack.Screen options={screenOptions} />
|
||||
<FlatList
|
||||
{...longListProps}
|
||||
data={songs}
|
||||
keyExtractor={songKey}
|
||||
renderItem={renderItem}
|
||||
style={{ flex: 1, backgroundColor: palette.background }}
|
||||
indicatorStyle={palette.isDark ? "white" : "black"}
|
||||
contentContainerStyle={styles.listContent}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
onEndReached={onEndReached}
|
||||
onEndReachedThreshold={0.5}
|
||||
onScrollBeginDrag={swipeGroup.closeOpenRow}
|
||||
ListHeaderComponent={
|
||||
<PlaylistHero
|
||||
coverUri={coverUri}
|
||||
hasCover={playlist.cover != null}
|
||||
title={playlist.title}
|
||||
ownerName={playlist.owner.name}
|
||||
palette={palette}
|
||||
isSubscribed={isSubscribed}
|
||||
showSubscribe={!playlist.isOwner && playlistId !== null}
|
||||
onSubscribeToggle={handleSubscribeToggle}
|
||||
onPlay={handlePlay}
|
||||
onShuffle={handleShuffle}
|
||||
/>
|
||||
}
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "",
|
||||
headerLargeTitle: false,
|
||||
headerRight: () => (
|
||||
<MediaActionMenu
|
||||
selectedCount={songIds.length}
|
||||
playlistLabel="Add to Another Playlist"
|
||||
share={{
|
||||
type: "playlist",
|
||||
playlistId: playlist.id ?? "favorites",
|
||||
}}
|
||||
includeActions={
|
||||
playlist.isOwner && playlist.id
|
||||
? [
|
||||
"share",
|
||||
"playlist",
|
||||
"play-next",
|
||||
"play-last",
|
||||
"shuffle",
|
||||
"favorite",
|
||||
"delete-playlist",
|
||||
]
|
||||
: undefined
|
||||
}
|
||||
onAction={handlePlaylistMenuAction}
|
||||
>
|
||||
<Pressable hitSlop={8}>
|
||||
<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 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({
|
||||
function PlaylistHero({
|
||||
coverUri,
|
||||
hasCover,
|
||||
title,
|
||||
ownerName,
|
||||
palette,
|
||||
colors,
|
||||
isSubscribed,
|
||||
showSubscribe = false,
|
||||
onSubscribeToggle,
|
||||
@@ -469,7 +481,7 @@ const PlaylistHero = memo(function PlaylistHero({
|
||||
hasCover: boolean
|
||||
title: string
|
||||
ownerName: string
|
||||
palette: CoverPalette
|
||||
colors: ReturnType<typeof useThemeColors>
|
||||
isSubscribed?: boolean
|
||||
showSubscribe?: boolean
|
||||
onSubscribeToggle?: () => void
|
||||
@@ -477,68 +489,56 @@ const PlaylistHero = memo(function PlaylistHero({
|
||||
onShuffle: () => void
|
||||
}) {
|
||||
return (
|
||||
<View>
|
||||
<View style={styles.hero}>
|
||||
<CoverImage uri={coverUri} hasCover={hasCover} style={styles.cover} />
|
||||
<Text style={[styles.title, { color: palette.foreground }]}>
|
||||
{title}
|
||||
</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,
|
||||
}}
|
||||
/>
|
||||
<View style={styles.hero}>
|
||||
<CoverImage uri={coverUri} hasCover={hasCover} style={styles.cover} />
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>{title}</Text>
|
||||
<Text style={{ color: colors.mutedForeground }}>{ownerName}</Text>
|
||||
<View style={styles.actions}>
|
||||
{showSubscribe ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Shuffle"
|
||||
accessibilityLabel={isSubscribed ? "Subscribed" : "Subscribe"}
|
||||
accessibilityState={{ selected: isSubscribed }}
|
||||
hitSlop={8}
|
||||
onPress={onShuffle}
|
||||
style={[styles.iconAction, { backgroundColor: palette.surface }]}
|
||||
onPress={onSubscribeToggle}
|
||||
style={[
|
||||
styles.iconAction,
|
||||
{
|
||||
backgroundColor: isSubscribed ? colors.muted : colors.primary,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Ionicons name="shuffle" size={24} color={palette.foreground} />
|
||||
<Ionicons
|
||||
name={isSubscribed ? "checkmark" : "add"}
|
||||
size={24}
|
||||
color={
|
||||
isSubscribed ? colors.foreground : colors.primaryForeground
|
||||
}
|
||||
/>
|
||||
</Pressable>
|
||||
</View>
|
||||
) : null}
|
||||
<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>
|
||||
<CollectionDivider color={palette.divider} />
|
||||
</View>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
|
||||
listContent: { paddingBottom: contentBottomInset },
|
||||
hero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm },
|
||||
cover: {
|
||||
width: 200,
|
||||
@@ -561,6 +561,15 @@ const styles = StyleSheet.create({
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
iosSwipeListHost: {
|
||||
flex: 1,
|
||||
alignSelf: "stretch",
|
||||
width: "100%",
|
||||
},
|
||||
nativeSongRow: {
|
||||
height: 64,
|
||||
overflow: "hidden",
|
||||
},
|
||||
removeAction: {
|
||||
width: 96,
|
||||
alignItems: "center",
|
||||
|
||||
@@ -1,102 +1,36 @@
|
||||
import { memo, useCallback, useEffect, useMemo } from "react"
|
||||
import {
|
||||
FlatList,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
type ListRenderItemInfo,
|
||||
} from "react-native"
|
||||
import { useQuery } from "convex/react"
|
||||
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
|
||||
|
||||
import { CollectionDivider } from "@/components/collection-list"
|
||||
import { CollectionDetailSkeleton } from "@/components/skeletons"
|
||||
import { Button } from "@/components/ui/primitives"
|
||||
import { contentBottomInset, SongListRow } from "@/components/player"
|
||||
import { Button, LoadingView } from "@/components/ui/primitives"
|
||||
import { contentBottomInset, SongRow } from "@/components/player"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlaybackActions } from "@/contexts/playback"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import {
|
||||
useCachedPaginatedQuery,
|
||||
useCachedQuery,
|
||||
} from "@/hooks/use-cached-query"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { MediaAction } from "@/components/media-context-menu"
|
||||
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 { Ionicons } from "@expo/vector-icons"
|
||||
import { Stack } from "expo-router"
|
||||
|
||||
const PAGE_SIZE = 50
|
||||
const SCREEN_OPTIONS = { title: "", headerLargeTitle: false }
|
||||
|
||||
export default function FavoritesScreen() {
|
||||
const colors = useThemeColors()
|
||||
const { config } = useServerConfig()
|
||||
const favorites = useCachedQuery(api.favorites.browseFavoritesSummary)
|
||||
const {
|
||||
results: songs,
|
||||
status,
|
||||
loadMore,
|
||||
isCached,
|
||||
} = useCachedPaginatedQuery(
|
||||
api.favorites.browseFavoritesSongsPaginated,
|
||||
{},
|
||||
{ initialNumItems: PAGE_SIZE }
|
||||
)
|
||||
const favorites = useQuery(api.favorites.browseFavoritesPlaylistDetail)
|
||||
const { playInOrder, playShuffled, playFromSong } = usePlaybackActions()
|
||||
const { isSongFavorite } = useFavorites()
|
||||
const { handleSongAction } = useMediaMenuActions()
|
||||
const loadedSongIds = useMemo(() => songs.map((song) => song.id), [songs])
|
||||
const songIds = favorites?.songIds ?? loadedSongIds
|
||||
|
||||
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
|
||||
) {
|
||||
if (favorites === undefined || !config) {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen options={SCREEN_OPTIONS} />
|
||||
<CollectionDetailSkeleton />
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "",
|
||||
headerLargeTitle: false,
|
||||
}}
|
||||
/>
|
||||
<LoadingView />
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -104,7 +38,12 @@ export default function FavoritesScreen() {
|
||||
if (favorites === null) {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen options={SCREEN_OPTIONS} />
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "",
|
||||
headerLargeTitle: false,
|
||||
}}
|
||||
/>
|
||||
<View style={[styles.empty, { backgroundColor: colors.background }]}>
|
||||
<Text style={{ color: colors.mutedForeground }}>
|
||||
Sign in to view your favorites.
|
||||
@@ -114,100 +53,92 @@ export default function FavoritesScreen() {
|
||||
)
|
||||
}
|
||||
|
||||
const songIds = favorites.songs.map((song: BrowseSong) => song.id)
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen options={SCREEN_OPTIONS} />
|
||||
<FlatList
|
||||
{...longListProps}
|
||||
data={songs}
|
||||
keyExtractor={songKey}
|
||||
renderItem={renderItem}
|
||||
style={{ flex: 1, backgroundColor: colors.background }}
|
||||
contentContainerStyle={styles.listContent}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
onEndReached={() => {
|
||||
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "",
|
||||
headerLargeTitle: false,
|
||||
}}
|
||||
onEndReachedThreshold={0.5}
|
||||
/>
|
||||
<FlatList
|
||||
data={favorites.songs}
|
||||
keyExtractor={(song) => song.id}
|
||||
style={{ flex: 1, backgroundColor: colors.background }}
|
||||
contentContainerStyle={{ paddingBottom: contentBottomInset }}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
ListHeaderComponent={
|
||||
<FavoritesHero
|
||||
title={favorites.title}
|
||||
onPlay={handlePlay}
|
||||
onShuffle={handleShuffle}
|
||||
/>
|
||||
<View style={styles.hero}>
|
||||
<View
|
||||
style={[
|
||||
styles.cover,
|
||||
{
|
||||
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({
|
||||
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
|
||||
listContent: { paddingBottom: contentBottomInset },
|
||||
hero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm },
|
||||
cover: {
|
||||
width: 200,
|
||||
height: 200,
|
||||
borderRadius: radius.lg,
|
||||
},
|
||||
coverPlaceholder: {
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
overflow: "hidden",
|
||||
},
|
||||
title: { fontSize: 24, fontWeight: "800" },
|
||||
actions: {
|
||||
flexDirection: "row",
|
||||
|
||||
@@ -1,94 +1,60 @@
|
||||
import { usePaginatedQuery, useQuery } from "convex/react"
|
||||
import { Stack, useRouter } from "expo-router"
|
||||
import { memo, useCallback, useMemo } from "react"
|
||||
import { useState } from "react"
|
||||
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
|
||||
|
||||
import { Button } from "@/components/ui/primitives"
|
||||
import { Button, LoadingView } from "@/components/ui/primitives"
|
||||
import { contentBottomInset, SongRow } from "@/components/player"
|
||||
import { SongRowSkeleton } from "@/components/skeletons"
|
||||
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { longListProps } from "@/lib/list"
|
||||
import { useSong, useSongs } from "@/lib/song-cache"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
import { spacing, useThemeColors } from "@/lib/theme"
|
||||
import { showError } from "@/lib/toast"
|
||||
|
||||
/** `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>
|
||||
)
|
||||
})
|
||||
const PAGE_SIZE = 50
|
||||
|
||||
export default function QueueScreen() {
|
||||
const router = useRouter()
|
||||
const colors = useThemeColors()
|
||||
const { queueSongIds, queueHistorySongIds } = usePlaybackQueue()
|
||||
const { queueSongIds, currentSong } = usePlaybackQueue()
|
||||
const { skipToQueueIndex, clearQueue, reorderQueue } = usePlaybackActions()
|
||||
const historySongs = useSongs(queueHistorySongIds)
|
||||
const [reordering, setReordering] = useState(false)
|
||||
|
||||
const items = useMemo<QueueItem[]>(() => {
|
||||
const occurrences = new Map<string, number>()
|
||||
return queueSongIds.map((songId, queueIndex) => {
|
||||
const occurrence = occurrences.get(songId) ?? 0
|
||||
occurrences.set(songId, occurrence + 1)
|
||||
return { songId, queueIndex, key: `${songId}:${occurrence}` }
|
||||
})
|
||||
}, [queueSongIds])
|
||||
const queueVersion = queueSongIds.length
|
||||
? `${queueSongIds.length}:${queueSongIds[0]}:${queueSongIds[queueSongIds.length - 1]}`
|
||||
: "empty"
|
||||
|
||||
const moveSong = useCallback(
|
||||
(fromIndex: number, direction: -1 | 1) => {
|
||||
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)
|
||||
void reorderQueue(next)
|
||||
},
|
||||
[queueSongIds, reorderQueue]
|
||||
const {
|
||||
results: queueSongs,
|
||||
status,
|
||||
loadMore,
|
||||
} = usePaginatedQuery(
|
||||
api.playback.getQueuePaginated,
|
||||
queueSongIds.length > 0 ? { queueVersion } : "skip",
|
||||
{ initialNumItems: PAGE_SIZE }
|
||||
)
|
||||
|
||||
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() {
|
||||
if (router.canGoBack()) {
|
||||
router.back()
|
||||
@@ -101,6 +67,10 @@ export default function QueueScreen() {
|
||||
void clearQueue()
|
||||
}
|
||||
|
||||
if (queueSongIds.length > 0 && queueSongs === undefined) {
|
||||
return <LoadingView />
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
@@ -129,36 +99,51 @@ export default function QueueScreen() {
|
||||
) : null}
|
||||
</View>
|
||||
}
|
||||
{...longListProps}
|
||||
data={items}
|
||||
keyExtractor={queueItemKey}
|
||||
data={queueSongs ?? []}
|
||||
keyExtractor={(item) => `${item.id}-${item.queueIndex}`}
|
||||
contentContainerStyle={{ paddingBottom: contentBottomInset }}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
onEndReached={() => {
|
||||
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
|
||||
}}
|
||||
renderItem={({ item }) => (
|
||||
<QueueRow
|
||||
songId={item.songId}
|
||||
queueIndex={item.queueIndex}
|
||||
isLast={item.queueIndex === queueSongIds.length - 1}
|
||||
isCurrent={item.queueIndex === 0}
|
||||
onSkipTo={skipToQueueIndex}
|
||||
onMove={moveSong}
|
||||
/>
|
||||
<View>
|
||||
<SongRow
|
||||
song={item}
|
||||
onPress={() => void skipToQueueIndex(item.queueIndex)}
|
||||
/>
|
||||
<View style={styles.queueActions}>
|
||||
<Pressable
|
||||
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={
|
||||
queueHistorySongIds.length > 0 ? (
|
||||
historySongs && historySongs.length > 0 ? (
|
||||
<View style={styles.history}>
|
||||
<Text style={[styles.section, { color: colors.mutedForeground }]}>
|
||||
History
|
||||
</Text>
|
||||
{historySongs.map((song, index) =>
|
||||
song ? (
|
||||
<SongRow key={`${song.id}-${index}`} song={song} />
|
||||
) : (
|
||||
<SongRowSkeleton
|
||||
key={`${queueHistorySongIds[index]}-${index}`}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
{historySongs.map((song: BrowseSong) => (
|
||||
<SongRow key={song.id} song={song} />
|
||||
))}
|
||||
</View>
|
||||
) : null
|
||||
}
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
import { usePaginatedQuery } from "convex/react"
|
||||
|
||||
import { MediaGridList } from "@/components/media-cards"
|
||||
import { MediaGridSkeleton } from "@/components/skeletons"
|
||||
import { LoadingView } from "@/components/ui/primitives"
|
||||
import { contentBottomInset } from "@/components/player"
|
||||
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
const PAGE_SIZE = 16
|
||||
|
||||
export default function RecentlyAddedScreen() {
|
||||
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
|
||||
const { results, status, loadMore } = usePaginatedQuery(
|
||||
api.library.browseRecentlyAddedPaginated,
|
||||
{},
|
||||
{ initialNumItems: PAGE_SIZE }
|
||||
)
|
||||
|
||||
if (status === "LoadingFirstPage" && !isCached) {
|
||||
return <MediaGridSkeleton />
|
||||
if (results === undefined) {
|
||||
return <LoadingView />
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
import { usePaginatedQuery } from "convex/react"
|
||||
|
||||
import { MediaGridList } from "@/components/media-cards"
|
||||
import { MediaGridSkeleton } from "@/components/skeletons"
|
||||
import { LoadingView } from "@/components/ui/primitives"
|
||||
import { contentBottomInset } from "@/components/player"
|
||||
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
const PAGE_SIZE = 50
|
||||
|
||||
export default function RecentlyPlayedScreen() {
|
||||
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
|
||||
const { results, status, loadMore } = usePaginatedQuery(
|
||||
api.library.browseRecentlyPlayedPaginated,
|
||||
{},
|
||||
{ initialNumItems: PAGE_SIZE }
|
||||
)
|
||||
|
||||
if (status === "LoadingFirstPage" && !isCached) {
|
||||
return <MediaGridSkeleton />
|
||||
if (results === undefined) {
|
||||
return <LoadingView />
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -19,8 +19,7 @@ import { Button, Input, LoadingView } from "@/components/ui/primitives"
|
||||
import { useInvalidateAuthSession } from "@/contexts/convex-auth-session"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { initialsFromName } from "@/lib/format"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { clearLocalData, signOutToSignIn } from "@/lib/session"
|
||||
import { signOutToSignIn } from "@/lib/session"
|
||||
import { radius, spacing, useThemeColors } from "@/lib/theme"
|
||||
import { showError, showSuccess } from "@/lib/toast"
|
||||
import type { PlaybackQuality } from "@/lib/urls"
|
||||
@@ -74,7 +73,7 @@ const SECTIONS: SectionConfig[] = [
|
||||
export default function SettingsScreen() {
|
||||
const colors = useThemeColors()
|
||||
const router = useRouter()
|
||||
const user = useCachedQuery(api.auth.currentUser)
|
||||
const user = useQuery(api.auth.currentUser)
|
||||
const { invalidateSession } = useInvalidateAuthSession()
|
||||
const { clearServer } = useServerConfig()
|
||||
const [section, setSection] = useState<Section>("profile")
|
||||
@@ -96,7 +95,6 @@ export default function SettingsScreen() {
|
||||
|
||||
async function handleChangeServer() {
|
||||
await invalidateSession()
|
||||
await clearLocalData()
|
||||
await clearServer()
|
||||
router.replace("/server")
|
||||
}
|
||||
@@ -462,7 +460,7 @@ function UsersSection({
|
||||
<SettingsCard title="Sign Up">
|
||||
<SwitchRow
|
||||
title="Disable account creation"
|
||||
subtitle="Stop people from registering themselves. Admins can still create accounts from the web app."
|
||||
subtitle="Prevent new users from creating accounts."
|
||||
value={appSettings?.disableAccountCreation ?? false}
|
||||
onValueChange={(checked) =>
|
||||
void setDisableCreation({ disabled: checked }).catch(
|
||||
@@ -476,82 +474,77 @@ function UsersSection({
|
||||
title="People"
|
||||
subtitle="Manage who can access this server."
|
||||
>
|
||||
<View style={styles.userList}>
|
||||
{users.map((user, index) => (
|
||||
<View
|
||||
key={user._id}
|
||||
style={[
|
||||
styles.userBlock,
|
||||
index > 0
|
||||
? [styles.userBlockSpaced, { borderTopColor: colors.border }]
|
||||
: null,
|
||||
]}
|
||||
>
|
||||
<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>
|
||||
{users.map((user, index) => (
|
||||
<View key={user._id}>
|
||||
{index > 0 ? (
|
||||
<View
|
||||
style={[styles.divider, { backgroundColor: colors.border }]}
|
||||
/>
|
||||
) : null}
|
||||
<View style={styles.userRow}>
|
||||
<ProfileAvatar user={user} size={44} />
|
||||
<View style={styles.userCopy}>
|
||||
<View style={styles.userNameRow}>
|
||||
<Text
|
||||
style={{ color: colors.mutedForeground }}
|
||||
style={[styles.userName, { color: colors.foreground }]}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{user.email}
|
||||
{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
|
||||
style={{ color: colors.mutedForeground }}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{user.email}
|
||||
</Text>
|
||||
</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}>
|
||||
<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>
|
||||
</>
|
||||
)
|
||||
@@ -838,16 +831,6 @@ const styles = StyleSheet.create({
|
||||
alignItems: "center",
|
||||
gap: spacing.md,
|
||||
},
|
||||
userList: {
|
||||
gap: spacing.lg,
|
||||
},
|
||||
userBlock: {
|
||||
gap: spacing.md,
|
||||
},
|
||||
userBlockSpaced: {
|
||||
paddingTop: spacing.lg,
|
||||
borderTopWidth: StyleSheet.hairlineWidth,
|
||||
},
|
||||
userRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
@@ -870,6 +853,7 @@ const styles = StyleSheet.create({
|
||||
userActions: {
|
||||
flexDirection: "row",
|
||||
gap: spacing.sm,
|
||||
marginTop: spacing.md,
|
||||
},
|
||||
userActionButton: {
|
||||
flex: 1,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { usePaginatedQuery } from "convex/react"
|
||||
import { useMemo } from "react"
|
||||
import { Pressable, StyleSheet, Text, View } from "react-native"
|
||||
import { SymbolView } from "expo-symbols"
|
||||
@@ -6,8 +7,7 @@ import { Ionicons } from "@expo/vector-icons"
|
||||
|
||||
import { MediaGridList } from "@/components/media-cards"
|
||||
import { tabContentBottomInset } from "@/components/player"
|
||||
import { MediaGridSkeleton } from "@/components/skeletons"
|
||||
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
|
||||
import { LoadingView } from "@/components/ui/primitives"
|
||||
import { useAppNavigation } from "@/lib/app-navigation"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { appleMusic, spacing, useThemeColors } from "@/lib/theme"
|
||||
@@ -49,7 +49,7 @@ function LibraryIcon({ name }: { name: (typeof links)[number]["icon"] }) {
|
||||
export default function LibraryScreen() {
|
||||
const { push } = useAppNavigation()
|
||||
const colors = useThemeColors()
|
||||
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
|
||||
const { results, status, loadMore } = usePaginatedQuery(
|
||||
api.library.browseRecentlyAddedPaginated,
|
||||
{},
|
||||
{ initialNumItems: PAGE_SIZE }
|
||||
@@ -83,11 +83,11 @@ export default function LibraryScreen() {
|
||||
[colors.border, colors.foreground, colors.mutedForeground, push]
|
||||
)
|
||||
|
||||
if (status === "LoadingFirstPage" && !isCached) {
|
||||
if (results === undefined) {
|
||||
return (
|
||||
<View style={{ flex: 1, backgroundColor: colors.background }}>
|
||||
{listHeader}
|
||||
<MediaGridSkeleton contentInset={false} />
|
||||
<LoadingView />
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { useConvexAuth as useLocalConvexAuth } from "@convex-dev/auth/react"
|
||||
import {
|
||||
useConvexAuth as useServerConvexAuth,
|
||||
useConvexConnectionState,
|
||||
} from "convex/react"
|
||||
import { useConvexAuth as useServerConvexAuth } from "convex/react"
|
||||
import { Redirect, Stack } from "expo-router"
|
||||
import { Platform } from "react-native"
|
||||
import { useEffect } from "react"
|
||||
@@ -23,21 +20,14 @@ export default function AppLayout() {
|
||||
const { config } = useServerConfig()
|
||||
const localAuth = useLocalConvexAuth()
|
||||
const serverAuth = useServerConvexAuth()
|
||||
const { isWebSocketConnected } = useConvexConnectionState()
|
||||
const { invalidateSession } = useInvalidateAuthSession()
|
||||
const stackOptions = useStackScreenOptions()
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!localAuth?.isAuthenticated ||
|
||||
serverAuth?.isAuthenticated ||
|
||||
!isWebSocketConnected
|
||||
) {
|
||||
if (!localAuth?.isAuthenticated || serverAuth?.isAuthenticated) {
|
||||
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(() => {
|
||||
void invalidateSession()
|
||||
}, AUTH_HANDSHAKE_TIMEOUT_MS)
|
||||
@@ -45,7 +35,6 @@ export default function AppLayout() {
|
||||
return () => clearTimeout(timer)
|
||||
}, [
|
||||
invalidateSession,
|
||||
isWebSocketConnected,
|
||||
localAuth?.isAuthenticated,
|
||||
serverAuth?.isAuthenticated,
|
||||
])
|
||||
@@ -62,8 +51,13 @@ export default function AppLayout() {
|
||||
return <Redirect href="/signin" />
|
||||
}
|
||||
|
||||
// Convex holds queries until the stored token is confirmed, so the app can
|
||||
// render cached data while the server handshake is still in progress.
|
||||
if (!serverAuth || serverAuth.isLoading || serverAuth.isRefreshing) {
|
||||
return <LoadingView />
|
||||
}
|
||||
|
||||
if (!serverAuth.isAuthenticated) {
|
||||
return <LoadingView />
|
||||
}
|
||||
|
||||
return (
|
||||
<ConvexAuthRecovery onInvalidate={invalidateSession}>
|
||||
|
||||
@@ -52,10 +52,8 @@ export default function PlayerScreen() {
|
||||
skipPrevious,
|
||||
} = usePlayback()
|
||||
|
||||
const hasQueue = queueSongIds.length > 0
|
||||
|
||||
useEffect(() => {
|
||||
if (hasQueue) {
|
||||
if (currentSong) {
|
||||
hadSongRef.current = true
|
||||
return
|
||||
}
|
||||
@@ -63,7 +61,7 @@ export default function PlayerScreen() {
|
||||
if (hadSongRef.current) {
|
||||
router.back()
|
||||
}
|
||||
}, [hasQueue, router])
|
||||
}, [currentSong, router])
|
||||
|
||||
if (!currentSong || !config) {
|
||||
return null
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
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,10 +10,7 @@ import {
|
||||
} from "react"
|
||||
|
||||
import { LoadingView } from "@/components/ui/primitives"
|
||||
import {
|
||||
isConvexAuthError,
|
||||
shouldInvalidateAuthSession,
|
||||
} from "@/lib/auth-errors"
|
||||
import { shouldInvalidateAuthSession } from "@/lib/auth-errors"
|
||||
|
||||
type ConvexAuthRecoveryProps = {
|
||||
children: ReactNode
|
||||
@@ -46,22 +43,10 @@ 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() {
|
||||
const { error } = this.state
|
||||
if (error) {
|
||||
if (isConvexAuthError(error)) {
|
||||
if (shouldInvalidateAuthSession(error, this.props.sessionEstablished)) {
|
||||
return <LoadingView />
|
||||
}
|
||||
throw error
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
import { Image, type ImageContentFit, type ImageStyle } from "expo-image"
|
||||
import { memo, useMemo } from "react"
|
||||
import { memo } from "react"
|
||||
import {
|
||||
PixelRatio,
|
||||
StyleProp,
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
} from "@/lib/urls"
|
||||
|
||||
const DEFAULT_SOURCE_SIZE: CoverImageSize = 1024
|
||||
const PIXEL_RATIO = PixelRatio.get()
|
||||
|
||||
function sourceSize(style: ImageStyle): CoverImageSize {
|
||||
const layoutSizes = [
|
||||
@@ -29,7 +28,7 @@ function sourceSize(style: ImageStyle): CoverImageSize {
|
||||
|
||||
if (layoutSizes.length === 0) return DEFAULT_SOURCE_SIZE
|
||||
|
||||
const requiredPixels = Math.max(...layoutSizes) * PIXEL_RATIO
|
||||
const requiredPixels = Math.max(...layoutSizes) * PixelRatio.get()
|
||||
return (
|
||||
coverImageSizes.find((size) => size >= requiredPixels) ??
|
||||
DEFAULT_SOURCE_SIZE
|
||||
@@ -50,12 +49,6 @@ function placeholderIconSize(style: ImageStyle): number {
|
||||
return 48
|
||||
}
|
||||
|
||||
const placeholderBaseStyle: ViewStyle = {
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
overflow: "hidden",
|
||||
}
|
||||
|
||||
export const CoverImage = memo(function CoverImage({
|
||||
uri,
|
||||
hasCover,
|
||||
@@ -72,22 +65,18 @@ export const CoverImage = memo(function CoverImage({
|
||||
placeholderVariant?: "icon" | "solid"
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
const flatStyle = useMemo(() => StyleSheet.flatten(style) ?? {}, [style])
|
||||
const sourceUri = useMemo(
|
||||
() => (hasCover ? withCoverImageSize(uri, sourceSize(flatStyle)) : ""),
|
||||
[flatStyle, hasCover, uri]
|
||||
)
|
||||
const source = useMemo(() => ({ uri: sourceUri }), [sourceUri])
|
||||
const flatStyle = StyleSheet.flatten(style) ?? {}
|
||||
|
||||
if (!hasCover) {
|
||||
const placeholderStyle: ViewStyle = {
|
||||
backgroundColor: colors.coverPlaceholder,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
overflow: "hidden",
|
||||
}
|
||||
|
||||
return (
|
||||
<View
|
||||
style={[
|
||||
style,
|
||||
placeholderBaseStyle,
|
||||
{ backgroundColor: colors.coverPlaceholder },
|
||||
]}
|
||||
>
|
||||
<View style={[style, placeholderStyle]}>
|
||||
{placeholderVariant === "icon" ? (
|
||||
<Ionicons
|
||||
name="musical-note"
|
||||
@@ -99,9 +88,11 @@ export const CoverImage = memo(function CoverImage({
|
||||
)
|
||||
}
|
||||
|
||||
const sourceUri = withCoverImageSize(uri, sourceSize(flatStyle))
|
||||
|
||||
return (
|
||||
<Image
|
||||
source={source}
|
||||
source={{ uri: sourceUri }}
|
||||
style={[style, { backgroundColor: colors.coverPlaceholder }]}
|
||||
contentFit={contentFit}
|
||||
transition={150}
|
||||
|
||||
@@ -1,359 +0,0 @@
|
||||
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"),
|
||||
},
|
||||
})
|
||||
@@ -1,20 +1,12 @@
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
import { memo, useCallback, type ReactElement } from "react"
|
||||
import {
|
||||
FlatList,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
type ListRenderItemInfo,
|
||||
} from "react-native"
|
||||
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
|
||||
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
import { MediaContextMenu } from "@/components/media-context-menu"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { useAppNavigation } from "@/lib/app-navigation"
|
||||
import { longListProps } from "@/lib/list"
|
||||
import type {
|
||||
BrowseAlbum,
|
||||
BrowseArtist,
|
||||
@@ -31,8 +23,6 @@ import {
|
||||
|
||||
export type MediaItem = BrowseAlbum | BrowseArtist | PlaylistSummary
|
||||
|
||||
const GRID_INITIAL_ROWS = 5
|
||||
|
||||
export const AlbumCard = memo(function AlbumCard({
|
||||
album,
|
||||
width = carouselCardWidth,
|
||||
@@ -216,24 +206,12 @@ export function MediaGridList({
|
||||
}) {
|
||||
const cardWidth = useTwoColumnCardWidth()
|
||||
const colors = useThemeColors()
|
||||
const renderItem = useCallback(
|
||||
({ item }: ListRenderItemInfo<MediaItem>) => (
|
||||
<View style={{ width: cardWidth }}>
|
||||
<CarouselCard item={item} width={cardWidth} />
|
||||
</View>
|
||||
),
|
||||
[cardWidth]
|
||||
)
|
||||
|
||||
return (
|
||||
<FlatList
|
||||
data={content}
|
||||
keyExtractor={mediaItemKey}
|
||||
renderItem={renderItem}
|
||||
keyExtractor={(item) => item.id}
|
||||
numColumns={2}
|
||||
initialNumToRender={GRID_INITIAL_ROWS}
|
||||
maxToRenderPerBatch={GRID_INITIAL_ROWS}
|
||||
windowSize={longListProps.windowSize}
|
||||
style={{ flex: 1, backgroundColor: colors.background }}
|
||||
contentContainerStyle={[
|
||||
contentInset ? styles.gridListContent : styles.gridListContentInset,
|
||||
@@ -247,22 +225,15 @@ export function MediaGridList({
|
||||
ListHeaderComponent={ListHeaderComponent}
|
||||
onEndReached={onEndReached}
|
||||
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({
|
||||
title,
|
||||
href,
|
||||
@@ -300,11 +271,15 @@ function ContentCarouselBody({
|
||||
</Pressable>
|
||||
<FlatList
|
||||
data={content}
|
||||
keyExtractor={mediaItemKey}
|
||||
renderItem={renderCarouselItem}
|
||||
keyExtractor={(item) => item.id}
|
||||
horizontal
|
||||
showsHorizontalScrollIndicator={false}
|
||||
contentContainerStyle={styles.carouselContent}
|
||||
renderItem={({ item }) => (
|
||||
<View>
|
||||
<CarouselCard item={item} width={carouselCardWidth} />
|
||||
</View>
|
||||
)}
|
||||
/>
|
||||
</View>
|
||||
)
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
import { MenuView, type MenuAction } from "@expo/ui/community/menu"
|
||||
import { requireNativeView } from "expo"
|
||||
import type { ComponentType, ReactNode } from "react"
|
||||
import {
|
||||
Platform,
|
||||
type StyleProp,
|
||||
type ViewProps,
|
||||
type ViewStyle,
|
||||
} from "react-native"
|
||||
import type { ReactNode } from "react"
|
||||
import type { StyleProp, ViewStyle } from "react-native"
|
||||
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import type { MediaShareContext } from "@/lib/media-links"
|
||||
@@ -196,69 +190,7 @@ 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) {
|
||||
if (Platform.OS === "ios") {
|
||||
return <NativeMediaContextMenu {...props} />
|
||||
}
|
||||
return <MediaMenuBase {...props} shouldOpenOnLongPress />
|
||||
}
|
||||
|
||||
|
||||
@@ -1,27 +1,26 @@
|
||||
import { collectionInset } from "@/components/collection-list"
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
import type { CoverPalette } from "@/lib/cover-palette"
|
||||
import { formatDuration } from "@/lib/format"
|
||||
import { albumCoverUrl } from "@/lib/urls"
|
||||
import { miniPlayerHeight, spacing, useThemeColors } from "@/lib/theme"
|
||||
import { memo, useCallback } from "react"
|
||||
import {
|
||||
miniPlayerHeight,
|
||||
spacing,
|
||||
tabBarHeight,
|
||||
useThemeColors,
|
||||
} from "@/lib/theme"
|
||||
import { Pressable, StyleSheet, Text, View } from "react-native"
|
||||
|
||||
import {
|
||||
MediaContextMenu,
|
||||
type MediaAction,
|
||||
type MediaMenuConfig,
|
||||
} from "@/components/media-context-menu"
|
||||
|
||||
export const SongRow = memo(function SongRow({
|
||||
export function SongRow({
|
||||
song,
|
||||
onPress,
|
||||
contextMenu,
|
||||
trailing,
|
||||
palette,
|
||||
inset = false,
|
||||
}: {
|
||||
song: BrowseSong
|
||||
onPress?: () => void
|
||||
@@ -29,41 +28,14 @@ export const SongRow = memo(function SongRow({
|
||||
onAction: MediaMenuConfig["onAction"]
|
||||
}
|
||||
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 colors = useThemeColors()
|
||||
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 = (
|
||||
<Pressable
|
||||
style={
|
||||
inset ? styles.insetRow : [styles.row, { borderBottomColor: divider }]
|
||||
}
|
||||
style={[styles.row, { borderBottomColor: colors.border }]}
|
||||
onPress={onPress}
|
||||
>
|
||||
<CoverImage
|
||||
@@ -71,13 +43,18 @@ export const SongRow = memo(function SongRow({
|
||||
hasCover={song.album.cover != null}
|
||||
style={styles.rowArtwork}
|
||||
/>
|
||||
{inset ? (
|
||||
<View style={[styles.insetContent, { borderBottomColor: divider }]}>
|
||||
{content}
|
||||
</View>
|
||||
) : (
|
||||
content
|
||||
)}
|
||||
<View style={styles.rowMeta}>
|
||||
<Text style={[styles.rowTitle, { color: colors.foreground }]} numberOfLines={1}>
|
||||
{song.title}
|
||||
</Text>
|
||||
<Text style={[styles.rowSubtitle, { color: colors.mutedForeground }]} numberOfLines={1}>
|
||||
{song.artist.name} · {song.album.title}
|
||||
</Text>
|
||||
</View>
|
||||
<Text style={[styles.duration, { color: colors.mutedForeground }]}>
|
||||
{formatDuration(song.durationSeconds)}
|
||||
</Text>
|
||||
{trailing}
|
||||
</Pressable>
|
||||
)
|
||||
|
||||
@@ -90,55 +67,7 @@ export const SongRow = memo(function SongRow({
|
||||
{row}
|
||||
</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 contentBottomInset = miniPlayerHeight + spacing.lg
|
||||
@@ -153,24 +82,6 @@ const styles = StyleSheet.create({
|
||||
paddingHorizontal: spacing.lg,
|
||||
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: {
|
||||
width: 44,
|
||||
height: 44,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useQuery } from "convex/react"
|
||||
import { Image } from "expo-image"
|
||||
import { useRouter } from "expo-router"
|
||||
import { Pressable, StyleSheet, Text, View } from "react-native"
|
||||
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { initialsFromName } from "@/lib/format"
|
||||
import { radius, useThemeColors } from "@/lib/theme"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
@@ -10,7 +10,7 @@ import { api } from "@otunes/convex/_generated/api"
|
||||
export function ProfileHeaderButton() {
|
||||
const router = useRouter()
|
||||
const colors = useThemeColors()
|
||||
const user = useCachedQuery(api.auth.currentUser)
|
||||
const user = useQuery(api.auth.currentUser)
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
|
||||
@@ -1,19 +1,12 @@
|
||||
import { memo, useCallback, useMemo } from "react"
|
||||
import {
|
||||
FlatList,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
type ListRenderItemInfo,
|
||||
} from "react-native"
|
||||
import { useQuery } from "convex/react"
|
||||
import { memo, useMemo } from "react"
|
||||
import { FlatList, StyleSheet, Text, View } from "react-native"
|
||||
|
||||
import { ContentCarousel } from "@/components/media-cards"
|
||||
import type { MediaAction } from "@/components/media-context-menu"
|
||||
import { tabContentBottomInset, SongListRow } from "@/components/player"
|
||||
import { SongListSkeleton } from "@/components/skeletons"
|
||||
import { tabContentBottomInset, SongRow } from "@/components/player"
|
||||
import { LoadingView } from "@/components/ui/primitives"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlaybackActions } from "@/contexts/playback"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
@@ -26,11 +19,11 @@ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
|
||||
const { handleSongAction } = useMediaMenuActions()
|
||||
const hasQuery = searchQuery.length > 0
|
||||
|
||||
const results = useCachedQuery(
|
||||
const results = useQuery(
|
||||
api.library.searchLibrary,
|
||||
hasQuery ? { query: searchQuery } : "skip"
|
||||
)
|
||||
const playlistResults = useCachedQuery(
|
||||
const playlistResults = useQuery(
|
||||
api.playlists.searchPlaylists,
|
||||
hasQuery ? { query: searchQuery } : "skip"
|
||||
)
|
||||
@@ -54,29 +47,9 @@ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
|
||||
() => results?.songs.map((song) => song.id) ?? [],
|
||||
[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) {
|
||||
return <SongListSkeleton />
|
||||
return <LoadingView />
|
||||
}
|
||||
|
||||
if (!hasQuery) {
|
||||
@@ -116,7 +89,25 @@ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
|
||||
) : null}
|
||||
</>
|
||||
}
|
||||
renderItem={renderItem}
|
||||
renderItem={({ item: song }: { item: BrowseSong }) => (
|
||||
<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={
|
||||
playlistResults && playlistResults.length > 0 ? (
|
||||
<View style={styles.section}>
|
||||
|
||||
@@ -1,257 +0,0 @@
|
||||
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 },
|
||||
})
|
||||
@@ -20,8 +20,6 @@ type ButtonProps = Omit<PressableProps, "style"> & {
|
||||
loading?: boolean
|
||||
icon?: React.ComponentProps<typeof Ionicons>["name"]
|
||||
style?: StyleProp<ViewStyle>
|
||||
/** Overrides the variant's colors, e.g. on screens tinted by cover art. */
|
||||
tint?: { background: string; foreground: string }
|
||||
}
|
||||
|
||||
export function Button({
|
||||
@@ -31,15 +29,13 @@ export function Button({
|
||||
disabled,
|
||||
icon,
|
||||
style,
|
||||
tint,
|
||||
...props
|
||||
}: ButtonProps) {
|
||||
const colors = useThemeColors()
|
||||
const isDisabled = disabled || loading
|
||||
|
||||
const backgroundColor = tint
|
||||
? tint.background
|
||||
: variant === "primary"
|
||||
const backgroundColor =
|
||||
variant === "primary"
|
||||
? colors.primary
|
||||
: variant === "secondary"
|
||||
? colors.muted
|
||||
@@ -47,9 +43,8 @@ export function Button({
|
||||
? colors.destructive
|
||||
: "transparent"
|
||||
|
||||
const textColor = tint
|
||||
? tint.foreground
|
||||
: variant === "primary"
|
||||
const textColor =
|
||||
variant === "primary"
|
||||
? colors.primaryForeground
|
||||
: variant === "destructive"
|
||||
? "#fff"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useConvex, useMutation } from "convex/react"
|
||||
import { useConvex, useMutation, useQuery } from "convex/react"
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
@@ -19,9 +19,6 @@ import {
|
||||
} from "react-native"
|
||||
|
||||
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 type { OwnedPlaylistForAdd } from "@otunes/convex/types"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
@@ -53,7 +50,6 @@ export function useAddToPlaylist() {
|
||||
|
||||
export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
|
||||
const convex = useConvex()
|
||||
const cacheScope = useCacheScope()
|
||||
const { push } = useAppNavigation()
|
||||
const colors = useThemeColors()
|
||||
const addSongs = useMutation(api.playlists.addSongsToPlaylist)
|
||||
@@ -67,7 +63,7 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
|
||||
const [addingToPlaylistId, setAddingToPlaylistId] =
|
||||
useState<Id<"playlists"> | null>(null)
|
||||
const selectionRequestIdRef = useRef(0)
|
||||
const ownedPlaylists = useCachedQuery(
|
||||
const ownedPlaylists = useQuery(
|
||||
api.playlists.listOwnedPlaylists,
|
||||
open ? {} : "skip"
|
||||
)
|
||||
@@ -96,12 +92,9 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
|
||||
async (albumId: Id<"albums">) => {
|
||||
const requestId = ++selectionRequestIdRef.current
|
||||
try {
|
||||
const songIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getAlbumSongIds,
|
||||
{ albumId }
|
||||
)
|
||||
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
||||
albumId,
|
||||
})
|
||||
if (selectionRequestIdRef.current !== requestId) return
|
||||
setPendingSongIds(songIds)
|
||||
setOpen(true)
|
||||
@@ -112,19 +105,16 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
}
|
||||
},
|
||||
[convex, cacheScope]
|
||||
[convex]
|
||||
)
|
||||
|
||||
const openAddPlaylistToPlaylist = useCallback(
|
||||
async (playlistId: Id<"playlists">) => {
|
||||
const requestId = ++selectionRequestIdRef.current
|
||||
try {
|
||||
const songIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getPlaylistSongIds,
|
||||
{ playlistId }
|
||||
)
|
||||
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
|
||||
playlistId,
|
||||
})
|
||||
if (selectionRequestIdRef.current !== requestId) return
|
||||
setPendingSongIds(songIds)
|
||||
setOpen(true)
|
||||
@@ -135,16 +125,14 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
}
|
||||
},
|
||||
[convex, cacheScope]
|
||||
[convex]
|
||||
)
|
||||
|
||||
const openAddArtistToPlaylist = useCallback(
|
||||
async (artistId: Id<"artists">) => {
|
||||
const requestId = ++selectionRequestIdRef.current
|
||||
try {
|
||||
const songIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
const songIds = await convex.query(
|
||||
api.playlists.getOrderedArtistSongIds,
|
||||
{ artistId }
|
||||
)
|
||||
@@ -158,7 +146,7 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
}
|
||||
},
|
||||
[convex, cacheScope]
|
||||
[convex]
|
||||
)
|
||||
|
||||
const openCreatePlaylist = useCallback(() => {
|
||||
|
||||
@@ -3,7 +3,6 @@ import { ConvexReactClient } from "convex/react"
|
||||
import { useCallback, useMemo, useState, type ReactNode } from "react"
|
||||
|
||||
import { ConvexAuthSessionProvider } from "@/contexts/convex-auth-session"
|
||||
import { PersistentCacheProvider } from "@/contexts/persistent-cache"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { clearStoredAuthTokens, secureStorage } from "@/lib/auth-storage"
|
||||
|
||||
@@ -36,9 +35,7 @@ export function ConvexAppProvider({ children }: { children: ReactNode }) {
|
||||
storage={secureStorage}
|
||||
storageNamespace={config.convexUrl}
|
||||
>
|
||||
<PersistentCacheProvider serverUrl={config.serverUrl}>
|
||||
{children}
|
||||
</PersistentCacheProvider>
|
||||
{children}
|
||||
</ConvexAuthProvider>
|
||||
</ConvexAuthSessionProvider>
|
||||
)
|
||||
|
||||
+104
-134
@@ -1,33 +1,16 @@
|
||||
import type { OptimisticUpdate } from "convex/browser"
|
||||
import { useMutation, type ReactMutation } from "convex/react"
|
||||
import type { FunctionArgs, FunctionReference } from "convex/server"
|
||||
import { useMutation, useQuery } from "convex/react"
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useMemo,
|
||||
useRef,
|
||||
type ReactNode,
|
||||
} from "react"
|
||||
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
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 = {
|
||||
isSongFavorite: (songId: string) => boolean
|
||||
isAlbumFavorite: (albumId: string) => boolean
|
||||
@@ -49,114 +32,103 @@ export function useFavorites() {
|
||||
}
|
||||
|
||||
export function FavoritesProvider({ children }: { children: ReactNode }) {
|
||||
const favorites = useCachedQuery(api.favorites.getUserFavorites)
|
||||
const favoriteSong = useOptimisticMutation(
|
||||
api.favorites.favoriteSong,
|
||||
(store, { songId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current || current.favoriteSongs.includes(songId)) return
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...current,
|
||||
favoriteSongs: [...current.favoriteSongs, songId],
|
||||
}
|
||||
)
|
||||
}
|
||||
)
|
||||
const unfavoriteSong = useOptimisticMutation(
|
||||
api.favorites.unfavoriteSong,
|
||||
(store, { songId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current) return
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...current,
|
||||
favoriteSongs: current.favoriteSongs.filter((id) => id !== songId),
|
||||
}
|
||||
)
|
||||
}
|
||||
)
|
||||
const favoriteAlbum = useOptimisticMutation(
|
||||
api.favorites.favoriteAlbum,
|
||||
(store, { albumId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current || current.favoriteAlbums.includes(albumId)) return
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...current,
|
||||
favoriteAlbums: [...current.favoriteAlbums, albumId],
|
||||
}
|
||||
)
|
||||
}
|
||||
)
|
||||
const unfavoriteAlbum = useOptimisticMutation(
|
||||
api.favorites.unfavoriteAlbum,
|
||||
(store, { albumId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current) return
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...current,
|
||||
favoriteAlbums: current.favoriteAlbums.filter((id) => id !== albumId),
|
||||
}
|
||||
)
|
||||
}
|
||||
)
|
||||
const favoriteArtist = useOptimisticMutation(
|
||||
api.favorites.favoriteArtist,
|
||||
(store, { artistId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current || current.favoriteArtists.includes(artistId)) return
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...current,
|
||||
favoriteArtists: [...current.favoriteArtists, artistId],
|
||||
}
|
||||
)
|
||||
}
|
||||
)
|
||||
const unfavoriteArtist = useOptimisticMutation(
|
||||
api.favorites.unfavoriteArtist,
|
||||
(store, { artistId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current) return
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...current,
|
||||
favoriteArtists: current.favoriteArtists.filter(
|
||||
(id) => id !== artistId
|
||||
),
|
||||
}
|
||||
)
|
||||
}
|
||||
)
|
||||
const favoriteSongsMutation = useOptimisticMutation(
|
||||
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 favorites = useQuery(api.favorites.getUserFavorites)
|
||||
const favoriteSong = useMutation(
|
||||
api.favorites.favoriteSong
|
||||
).withOptimisticUpdate((store, { songId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current || current.favoriteSongs.includes(songId)) return
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...current,
|
||||
favoriteSongs: [...current.favoriteSongs, songId],
|
||||
}
|
||||
)
|
||||
})
|
||||
const unfavoriteSong = useMutation(
|
||||
api.favorites.unfavoriteSong
|
||||
).withOptimisticUpdate((store, { songId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current) return
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...current,
|
||||
favoriteSongs: current.favoriteSongs.filter((id) => id !== songId),
|
||||
}
|
||||
)
|
||||
})
|
||||
const favoriteAlbum = useMutation(
|
||||
api.favorites.favoriteAlbum
|
||||
).withOptimisticUpdate((store, { albumId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current || current.favoriteAlbums.includes(albumId)) return
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...current,
|
||||
favoriteAlbums: [...current.favoriteAlbums, albumId],
|
||||
}
|
||||
)
|
||||
})
|
||||
const unfavoriteAlbum = useMutation(
|
||||
api.favorites.unfavoriteAlbum
|
||||
).withOptimisticUpdate((store, { albumId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current) return
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...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
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...current,
|
||||
favoriteArtists: [...current.favoriteArtists, artistId],
|
||||
}
|
||||
)
|
||||
})
|
||||
const unfavoriteArtist = useMutation(
|
||||
api.favorites.unfavoriteArtist
|
||||
).withOptimisticUpdate((store, { artistId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current) return
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...current,
|
||||
favoriteArtists: current.favoriteArtists.filter(
|
||||
(id) => id !== artistId
|
||||
),
|
||||
}
|
||||
)
|
||||
})
|
||||
const favoriteSongsMutation = useMutation(
|
||||
api.favorites.favoriteSongs
|
||||
).withOptimisticUpdate((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(
|
||||
() => new Set(favorites?.favoriteSongs.map(String) ?? []),
|
||||
@@ -170,13 +142,11 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
|
||||
() => new Set(favorites?.favoriteArtists.map(String) ?? []),
|
||||
[favorites?.favoriteArtists]
|
||||
)
|
||||
const idsRef = useRef({ songIds, albumIds, artistIds })
|
||||
idsRef.current = { songIds, albumIds, artistIds }
|
||||
|
||||
const toggleSongFavorite = useCallback(
|
||||
async (songId: Id<"songs">) => {
|
||||
try {
|
||||
if (idsRef.current.songIds.has(songId)) {
|
||||
if (songIds.has(songId)) {
|
||||
await unfavoriteSong({ songId })
|
||||
showSuccess("Removed from favorites")
|
||||
} else {
|
||||
@@ -189,13 +159,13 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
}
|
||||
},
|
||||
[favoriteSong, unfavoriteSong]
|
||||
[songIds, favoriteSong, unfavoriteSong]
|
||||
)
|
||||
|
||||
const toggleAlbumFavorite = useCallback(
|
||||
async (albumId: Id<"albums">) => {
|
||||
try {
|
||||
if (idsRef.current.albumIds.has(albumId)) {
|
||||
if (albumIds.has(albumId)) {
|
||||
await unfavoriteAlbum({ albumId })
|
||||
showSuccess("Removed from favorites")
|
||||
} else {
|
||||
@@ -208,13 +178,13 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
}
|
||||
},
|
||||
[favoriteAlbum, unfavoriteAlbum]
|
||||
[albumIds, favoriteAlbum, unfavoriteAlbum]
|
||||
)
|
||||
|
||||
const toggleArtistFavorite = useCallback(
|
||||
async (artistId: Id<"artists">) => {
|
||||
try {
|
||||
if (idsRef.current.artistIds.has(artistId)) {
|
||||
if (artistIds.has(artistId)) {
|
||||
await unfavoriteArtist({ artistId })
|
||||
showSuccess("Removed from favorites")
|
||||
} else {
|
||||
@@ -227,7 +197,7 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
}
|
||||
},
|
||||
[favoriteArtist, unfavoriteArtist]
|
||||
[artistIds, favoriteArtist, unfavoriteArtist]
|
||||
)
|
||||
|
||||
const favoriteSongs = useCallback(
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
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)
|
||||
}
|
||||
+349
-347
File diff suppressed because it is too large.
Load diff
@@ -1,88 +0,0 @@
|
||||
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 }
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
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
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -3,13 +3,11 @@ import { useCallback } from "react"
|
||||
|
||||
import type { MediaAction } from "@/components/media-context-menu"
|
||||
import { useAddToPlaylist } from "@/contexts/add-to-playlist"
|
||||
import { useCacheScope } from "@/contexts/persistent-cache"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlaybackActions } from "@/contexts/playback"
|
||||
import { useAppNavigation } from "@/lib/app-navigation"
|
||||
import { showError, showSuccess } from "@/lib/toast"
|
||||
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 {
|
||||
BrowseAlbum,
|
||||
@@ -30,7 +28,6 @@ async function runMediaAction(action: () => Promise<void>) {
|
||||
|
||||
export function useMediaMenuActions() {
|
||||
const convex = useConvex()
|
||||
const cacheScope = useCacheScope()
|
||||
const { push } = useAppNavigation()
|
||||
const {
|
||||
openAddToPlaylist,
|
||||
@@ -113,12 +110,9 @@ export function useMediaMenuActions() {
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle": {
|
||||
const songIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getAlbumSongIds,
|
||||
{ albumId: album.id as Id<"albums"> }
|
||||
)
|
||||
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
||||
albumId: album.id as Id<"albums">,
|
||||
})
|
||||
await runQueueAction(action, songIds)
|
||||
break
|
||||
}
|
||||
@@ -130,14 +124,7 @@ export function useMediaMenuActions() {
|
||||
}
|
||||
})
|
||||
},
|
||||
[
|
||||
convex,
|
||||
cacheScope,
|
||||
openAddAlbumToPlaylist,
|
||||
push,
|
||||
runQueueAction,
|
||||
toggleAlbumFavorite,
|
||||
]
|
||||
[convex, openAddAlbumToPlaylist, push, runQueueAction, toggleAlbumFavorite]
|
||||
)
|
||||
|
||||
const handleArtistAction = useCallback(
|
||||
@@ -153,9 +140,7 @@ export function useMediaMenuActions() {
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle": {
|
||||
const songIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
const songIds = await convex.query(
|
||||
api.playlists.getOrderedArtistSongIds,
|
||||
{ artistId: artist.id as Id<"artists"> }
|
||||
)
|
||||
@@ -167,13 +152,7 @@ export function useMediaMenuActions() {
|
||||
}
|
||||
})
|
||||
},
|
||||
[
|
||||
convex,
|
||||
cacheScope,
|
||||
openAddArtistToPlaylist,
|
||||
runQueueAction,
|
||||
toggleArtistFavorite,
|
||||
]
|
||||
[convex, openAddArtistToPlaylist, runQueueAction, toggleArtistFavorite]
|
||||
)
|
||||
|
||||
const handlePlaylistAction = useCallback(
|
||||
@@ -186,9 +165,7 @@ export function useMediaMenuActions() {
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle": {
|
||||
const songIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
const songIds = await convex.query(
|
||||
api.playlists.getPlaylistSongIds,
|
||||
{
|
||||
playlistId: playlist.id as Id<"playlists">,
|
||||
@@ -202,7 +179,7 @@ export function useMediaMenuActions() {
|
||||
}
|
||||
})
|
||||
},
|
||||
[convex, cacheScope, openAddPlaylistToPlaylist, runQueueAction]
|
||||
[convex, openAddPlaylistToPlaylist, runQueueAction]
|
||||
)
|
||||
|
||||
const handleAlbumDetailAction = useCallback(
|
||||
|
||||
@@ -1,296 +0,0 @@
|
||||
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("")}`
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
/**
|
||||
* `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
|
||||
@@ -1,67 +0,0 @@
|
||||
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 },
|
||||
})
|
||||
@@ -1,48 +0,0 @@
|
||||
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
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
import { buildConvexUrl, isLocalHost } from "@otunes/convex/server-url"
|
||||
|
||||
export type ServerConfig = {
|
||||
/** Raw hostname the user entered, e.g. `music.example.com` or `192.168.86.25:3000` */
|
||||
hostname: string
|
||||
@@ -11,6 +9,30 @@ export type ServerConfig = {
|
||||
|
||||
const SERVER_CONFIG_KEY = "otunes.server-config"
|
||||
const LEGACY_SERVER_CONFIG_KEY = "otunes:server-config"
|
||||
const LOCAL_CONVEX_PORT = "3210"
|
||||
|
||||
function parseHostPort(hostname: string): { host: string; port?: string } {
|
||||
const colonIndex = hostname.lastIndexOf(":")
|
||||
if (colonIndex === -1) {
|
||||
return { host: hostname }
|
||||
}
|
||||
const host = hostname.slice(0, colonIndex)
|
||||
const port = hostname.slice(colonIndex + 1)
|
||||
if (!/^\d+$/.test(port)) {
|
||||
return { host: hostname }
|
||||
}
|
||||
return { host, port }
|
||||
}
|
||||
|
||||
function isLocalHost(hostname: string): boolean {
|
||||
const host = parseHostPort(hostname).host.toLowerCase()
|
||||
return (
|
||||
host === "localhost" ||
|
||||
host === "127.0.0.1" ||
|
||||
host.endsWith(".local") ||
|
||||
/^\d{1,3}(\.\d{1,3}){3}$/.test(host)
|
||||
)
|
||||
}
|
||||
|
||||
function normalizeHostnameInput(input: string): string {
|
||||
return input.trim().replace(/^https?:\/\//i, "").replace(/\/+$/, "")
|
||||
@@ -21,6 +43,16 @@ function buildServerUrl(hostname: string): string {
|
||||
return `${protocol}://${hostname}`
|
||||
}
|
||||
|
||||
function buildConvexUrl(hostname: string): string {
|
||||
const { host, port } = parseHostPort(hostname)
|
||||
const protocol = isLocalHost(hostname) ? "http" : "https"
|
||||
if (isLocalHost(hostname)) {
|
||||
return `${protocol}://${host}:${LOCAL_CONVEX_PORT}`
|
||||
}
|
||||
const convexHost = `convex.${host}`
|
||||
return port ? `${protocol}://${convexHost}:${port}` : `${protocol}://${convexHost}`
|
||||
}
|
||||
|
||||
export function parseServerHostname(input: string): ServerConfig | null {
|
||||
const hostname = normalizeHostnameInput(input)
|
||||
if (!hostname) return null
|
||||
|
||||
@@ -1,21 +1,11 @@
|
||||
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>
|
||||
|
||||
/** Forgets this device's cached library and playback state. */
|
||||
export async function clearLocalData() {
|
||||
resetPlaybackStores()
|
||||
await clearPersistentCache()
|
||||
}
|
||||
|
||||
export async function signOutToSignIn(
|
||||
router: Pick<AppRouter, "replace">,
|
||||
invalidateSession: () => Promise<void>
|
||||
) {
|
||||
await invalidateSession()
|
||||
await clearLocalData()
|
||||
router.replace("/signin")
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -7,9 +7,6 @@ export const coverImageSizes = [64, 128, 192, 256, 384, 512, 768, 1024] as const
|
||||
export type CoverImageSize = (typeof coverImageSizes)[number]
|
||||
|
||||
export function withCoverImageSize(uri: string, size: CoverImageSize) {
|
||||
if (!uri.includes("?") && !uri.includes("#")) {
|
||||
return `${uri}?size=${size}`
|
||||
}
|
||||
const url = new URL(uri)
|
||||
url.searchParams.set("size", String(size))
|
||||
return url.toString()
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
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;
|
||||
@@ -1,125 +0,0 @@
|
||||
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;
|
||||
@@ -1,10 +0,0 @@
|
||||
import { HomeSkeleton, PageHeader } from "@/components/library-skeletons"
|
||||
|
||||
export default function Loading() {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<PageHeader title="Home" />
|
||||
<HomeSkeleton />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { ContentCarousel } from "@/components/content-carousel"
|
||||
import { HomeSkeleton, PageHeader } from "@/components/library-skeletons"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
export default function Page() {
|
||||
const recentlyAdded = useCachedQuery(api.library.browseRecentlyAdded, {
|
||||
limit: 9,
|
||||
})
|
||||
const recentlyPlayed = useCachedQuery(api.library.browseRecentlyPlayed, {
|
||||
limit: 9,
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<PageHeader title="Home" />
|
||||
|
||||
{recentlyAdded === undefined || recentlyPlayed === undefined ? (
|
||||
<HomeSkeleton />
|
||||
) : (
|
||||
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
||||
<div className="flex flex-col gap-10">
|
||||
{recentlyPlayed.length > 0 ? (
|
||||
<ContentCarousel
|
||||
title="Recently Played"
|
||||
href="/recently-played"
|
||||
content={recentlyPlayed}
|
||||
/>
|
||||
) : null}
|
||||
<ContentCarousel
|
||||
title="Recently Added"
|
||||
href="/recently-added"
|
||||
content={recentlyAdded}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
import { CollectionDetailSkeleton } from "@/components/library-skeletons"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
|
||||
export default function Loading() {
|
||||
return <CollectionDetailSkeleton />
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<LibraryLoading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { AlbumPage } from "@/components/album-page"
|
||||
import { AlbumView } from "@/components/album-view"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import { convexServerOptions } from "@/lib/convex-server"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { Metadata } from "next"
|
||||
import { cache } from "react"
|
||||
@@ -12,7 +12,7 @@ interface PageProps {
|
||||
}
|
||||
|
||||
const fetchAlbumDetail = cache((id: Id<"albums">) =>
|
||||
fetchQuery(api.library.browseAlbumDetail, { id }, convexServerOptions())
|
||||
fetchQuery(api.library.browseAlbumDetail, { id })
|
||||
)
|
||||
|
||||
export async function generateMetadata({
|
||||
@@ -48,15 +48,29 @@ export async function generateMetadata({
|
||||
}
|
||||
|
||||
export default async function Page({ params, searchParams }: PageProps) {
|
||||
const [{ id }, { s: highlightedSongId }] = await Promise.all([
|
||||
params,
|
||||
const { id } = await params
|
||||
const [{ s: highlightedSongId }, album] = await Promise.all([
|
||||
searchParams,
|
||||
fetchAlbumDetail(id as Id<"albums">),
|
||||
])
|
||||
|
||||
return (
|
||||
<AlbumPage
|
||||
albumId={id as Id<"albums">}
|
||||
highlightedSongId={highlightedSongId}
|
||||
/>
|
||||
)
|
||||
if (album === undefined) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<LibraryLoading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (album === null) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<div className="flex flex-1 items-center justify-center pb-28">
|
||||
<p className="text-sm text-muted-foreground">Album not found.</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return <AlbumView album={album} highlightedSongId={highlightedSongId} />
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
import { ArtistDetailSkeleton } from "@/components/library-skeletons"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
|
||||
export default function Loading() {
|
||||
return <ArtistDetailSkeleton />
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<LibraryLoading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import { convexServerOptions } from "@/lib/convex-server"
|
||||
import { ArtistPage } from "@/components/artist-page"
|
||||
import { ArtistView } from "@/components/artist-view"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { Metadata } from "next"
|
||||
@@ -11,7 +11,7 @@ interface PageProps {
|
||||
}
|
||||
|
||||
const fetchArtistDetail = cache((id: Id<"artists">) =>
|
||||
fetchQuery(api.library.browseArtistDetail, { id }, convexServerOptions())
|
||||
fetchQuery(api.library.browseArtistDetail, { id })
|
||||
)
|
||||
|
||||
export async function generateMetadata({
|
||||
@@ -38,5 +38,25 @@ export async function generateMetadata({
|
||||
|
||||
export default async function Page({ params }: PageProps) {
|
||||
const { id } = await params
|
||||
return <ArtistPage artistId={id as Id<"artists">} />
|
||||
const data = await fetchArtistDetail(id as Id<"artists">)
|
||||
|
||||
if (data === undefined) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<LibraryLoading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (data === null) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<div className="flex flex-1 items-center justify-center pb-28">
|
||||
<p className="text-sm text-muted-foreground">Artist not found.</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return <ArtistView artist={data.artist} albums={data.albums} />
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import { CardGridSkeleton, PageHeader } from "@/components/library-skeletons"
|
||||
|
||||
export default function Loading() {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<PageHeader title="Albums" />
|
||||
<CardGridSkeleton />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,23 +1,25 @@
|
||||
"use client"
|
||||
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { AlbumCard } from "@/components/album-card"
|
||||
import { CardGridSkeleton, PageHeader } from "@/components/library-skeletons"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { albumGridClassName } from "@/lib/album-grid-classes"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
export default function Page() {
|
||||
const albums = useCachedQuery(api.library.browseAlbums)
|
||||
const albums = useQuery(api.library.browseAlbums)
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<PageHeader title="Albums" />
|
||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
||||
<h1 className="text-lg font-semibold">Albums</h1>
|
||||
</header>
|
||||
|
||||
{albums === undefined ? (
|
||||
<CardGridSkeleton />
|
||||
<LibraryLoading />
|
||||
) : (
|
||||
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
||||
<div className={albumGridClassName}>
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-8 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
||||
{albums.map((album) => (
|
||||
<AlbumCard key={album.id} album={album} />
|
||||
))}
|
||||
|
||||
@@ -1,21 +1,20 @@
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import { convexServerOptions } from "@/lib/convex-server"
|
||||
import { ArtistsView } from "@/components/artists-view"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { Metadata } from "next"
|
||||
import { cache } from "react"
|
||||
|
||||
interface PageProps {
|
||||
params: Promise<{ id: string }>
|
||||
}
|
||||
|
||||
const fetchArtists = cache(() => fetchQuery(api.library.browseArtists))
|
||||
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
}: PageProps): Promise<Metadata> {
|
||||
const { id } = await params
|
||||
const artists = await fetchQuery(
|
||||
api.library.browseArtists,
|
||||
{},
|
||||
convexServerOptions()
|
||||
)
|
||||
const artists = await fetchArtists()
|
||||
const selectedArtist = artists.find((artist) => artist.id === id)
|
||||
|
||||
return {
|
||||
@@ -34,6 +33,19 @@ export async function generateMetadata({
|
||||
}
|
||||
}
|
||||
|
||||
export default function Page() {
|
||||
return null
|
||||
export default async function Page({ params }: PageProps) {
|
||||
const { id } = await params
|
||||
const [artists, albums] = await Promise.all([
|
||||
fetchArtists(),
|
||||
fetchQuery(api.library.browseAlbums),
|
||||
])
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
||||
<h1 className="text-lg font-semibold">Artists</h1>
|
||||
</header>
|
||||
<ArtistsView artists={artists} albums={albums} artistId={id} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
import { ArtistsPage } from "@/components/artists-page"
|
||||
|
||||
export default function ArtistsLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode
|
||||
}>) {
|
||||
return (
|
||||
<>
|
||||
<ArtistsPage />
|
||||
{children}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
/**
|
||||
* The artists UI lives in the layout and renders from the client cache, so
|
||||
* navigations only need this (empty) boundary to commit.
|
||||
*/
|
||||
export default function Loading() {
|
||||
return null
|
||||
}
|
||||
@@ -1,3 +1,25 @@
|
||||
export default function Page() {
|
||||
return null
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import { ArtistsView } from "@/components/artists-view"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
export default async function Page() {
|
||||
const [artists, albums] = await Promise.all([
|
||||
fetchQuery(api.library.browseArtists),
|
||||
fetchQuery(api.library.browseAlbums),
|
||||
])
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
||||
<h1 className="text-lg font-semibold">Artists</h1>
|
||||
</header>
|
||||
|
||||
{artists === undefined || albums === undefined ? (
|
||||
<LibraryLoading />
|
||||
) : (
|
||||
<ArtistsView artists={artists} albums={albums} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import { PageHeader, SongListSkeleton } from "@/components/library-skeletons"
|
||||
|
||||
export default function Loading() {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<PageHeader title="Songs" />
|
||||
<SongListSkeleton />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
"use client"
|
||||
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { ContentCarousel } from "@/components/content-carousel"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
export default function Page() {
|
||||
const recentlyAdded = useQuery(api.library.browseRecentlyAdded, { limit: 9 })
|
||||
const recentlyPlayed = useQuery(api.library.browseRecentlyPlayed, {
|
||||
limit: 9,
|
||||
})
|
||||
|
||||
if (recentlyAdded === undefined || recentlyPlayed === undefined) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
||||
<h1 className="text-lg font-semibold">Home</h1>
|
||||
</header>
|
||||
<LibraryLoading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
||||
<h1 className="text-lg font-semibold">Home</h1>
|
||||
</header>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
||||
<div className="flex flex-col gap-10">
|
||||
{recentlyPlayed.length > 0 ? (
|
||||
<ContentCarousel
|
||||
title="Recently Played"
|
||||
href="/recently-played"
|
||||
content={recentlyPlayed}
|
||||
/>
|
||||
) : null}
|
||||
<ContentCarousel
|
||||
title="Recently Added"
|
||||
href="/recently-added"
|
||||
content={recentlyAdded}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { CollectionDetailSkeleton } from "@/components/library-skeletons"
|
||||
|
||||
export default function Loading() {
|
||||
return <CollectionDetailSkeleton />
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import { PlaylistPage } from "@/components/playlist-page"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { PlaylistView } from "@/components/playlist-view"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server"
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import { convexServerOptions } from "@/lib/convex-server"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { Metadata } from "next"
|
||||
import { cache } from "react"
|
||||
@@ -16,7 +16,7 @@ const fetchPlaylistDetail = cache(async (id: Id<"playlists">) => {
|
||||
return fetchQuery(
|
||||
api.playlists.browsePlaylistDetail,
|
||||
{ id },
|
||||
convexServerOptions(token)
|
||||
{ token }
|
||||
)
|
||||
})
|
||||
|
||||
@@ -40,5 +40,25 @@ export async function generateMetadata({
|
||||
|
||||
export default async function Page({ params }: PageProps) {
|
||||
const { id } = await params
|
||||
return <PlaylistPage playlistId={id as Id<"playlists">} />
|
||||
const playlist = await fetchPlaylistDetail(id as Id<"playlists">)
|
||||
|
||||
if (playlist === undefined) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<LibraryLoading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (playlist === null) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<div className="flex flex-1 items-center justify-center pb-28">
|
||||
<p className="text-sm text-muted-foreground">Playlist not found.</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return <PlaylistView key={playlist.id} playlist={playlist} />
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { CollectionDetailSkeleton } from "@/components/library-skeletons"
|
||||
|
||||
export default function Loading() {
|
||||
return <CollectionDetailSkeleton />
|
||||
}
|
||||
@@ -1,7 +1,33 @@
|
||||
"use client"
|
||||
|
||||
import { FavoritesPlaylistPage } from "@/components/playlist-page"
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { PlaylistView } from "@/components/playlist-view"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
export default function Page() {
|
||||
return <FavoritesPlaylistPage />
|
||||
const favorites = useQuery(api.favorites.browseFavoritesPlaylistDetail)
|
||||
|
||||
if (favorites === undefined) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<LibraryLoading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (favorites === null) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<div className="flex flex-1 items-center justify-center pb-28">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Sign in to view your favorites.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return <PlaylistView playlist={favorites} />
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import { CardGridSkeleton, PageHeader } from "@/components/library-skeletons"
|
||||
|
||||
export default function Loading() {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<PageHeader title="Playlists" />
|
||||
<CardGridSkeleton />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,17 +1,16 @@
|
||||
"use client"
|
||||
|
||||
import { useQuery } from "convex/react"
|
||||
import { Plus } from "lucide-react"
|
||||
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { CardGridSkeleton } from "@/components/library-skeletons"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { PlaylistCard } from "@/components/playlist-card"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { albumGridClassName } from "@/lib/album-grid-classes"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
export default function Page() {
|
||||
const playlists = useCachedQuery(api.playlists.listAllPlaylists)
|
||||
const playlists = useQuery(api.playlists.listAllPlaylists)
|
||||
const { openCreatePlaylist } = useAddToPlaylist()
|
||||
|
||||
return (
|
||||
@@ -30,10 +29,10 @@ export default function Page() {
|
||||
</header>
|
||||
|
||||
{playlists === undefined ? (
|
||||
<CardGridSkeleton />
|
||||
<LibraryLoading />
|
||||
) : (
|
||||
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
||||
<div className={albumGridClassName}>
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-8 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
||||
{playlists.map((playlist) => (
|
||||
<PlaylistCard key={playlist.id} playlist={playlist} />
|
||||
))}
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
import { CardGridSkeleton, PageHeader } from "@/components/library-skeletons"
|
||||
|
||||
export default function Loading() {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<PageHeader title="Recently Added" />
|
||||
<CardGridSkeleton />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,23 +1,25 @@
|
||||
"use client"
|
||||
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { AlbumCard } from "@/components/album-card"
|
||||
import { CardGridSkeleton, PageHeader } from "@/components/library-skeletons"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { albumGridClassName } from "@/lib/album-grid-classes"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
export default function Page() {
|
||||
const albums = useCachedQuery(api.library.browseRecentlyAdded, {})
|
||||
const albums = useQuery(api.library.browseRecentlyAdded, {})
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<PageHeader title="Recently Added" />
|
||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
||||
<h1 className="text-lg font-semibold">Recently Added</h1>
|
||||
</header>
|
||||
|
||||
{albums === undefined ? (
|
||||
<CardGridSkeleton />
|
||||
<LibraryLoading />
|
||||
) : (
|
||||
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
||||
<div className={albumGridClassName}>
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-8 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
||||
{albums.map((album) => (
|
||||
<AlbumCard key={album.id} album={album} />
|
||||
))}
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
import { CardGridSkeleton, PageHeader } from "@/components/library-skeletons"
|
||||
|
||||
export default function Loading() {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<PageHeader title="Recently Played" />
|
||||
<CardGridSkeleton />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
"use client"
|
||||
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { AlbumCard } from "@/components/album-card"
|
||||
import { CardGridSkeleton, PageHeader } from "@/components/library-skeletons"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { PlaylistCard } from "@/components/playlist-card"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { albumGridClassName } from "@/lib/album-grid-classes"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { BrowseAlbum, PlaylistSummary } from "@otunes/convex/types"
|
||||
|
||||
@@ -20,14 +20,16 @@ function RecentlyPlayedCard({
|
||||
}
|
||||
|
||||
export default function Page() {
|
||||
const recentlyPlayed = useCachedQuery(api.library.browseRecentlyPlayed, {})
|
||||
const recentlyPlayed = useQuery(api.library.browseRecentlyPlayed, {})
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<PageHeader title="Recently Played" />
|
||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
||||
<h1 className="text-lg font-semibold">Recently Played</h1>
|
||||
</header>
|
||||
|
||||
{recentlyPlayed === undefined ? (
|
||||
<CardGridSkeleton />
|
||||
<LibraryLoading />
|
||||
) : recentlyPlayed.length === 0 ? (
|
||||
<div className="flex flex-1 items-center justify-center p-6 pb-28">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
@@ -36,7 +38,7 @@ export default function Page() {
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
||||
<div className={albumGridClassName}>
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-8 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
||||
{recentlyPlayed.map((item) => (
|
||||
<RecentlyPlayedCard key={item.id} item={item} />
|
||||
))}
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useSearchParams } from "next/navigation"
|
||||
|
||||
import { SearchResultsSkeleton } from "@/components/library-skeletons"
|
||||
import { SearchPrompt } from "@/components/search-prompt"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
|
||||
export default function Loading() {
|
||||
const hasQuery = Boolean(useSearchParams().get("q")?.trim())
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<header className="flex items-center justify-center border-b px-4 py-3">
|
||||
<Skeleton className="h-10 w-full max-w-xl rounded-full" />
|
||||
</header>
|
||||
{hasQuery ? <SearchResultsSkeleton /> : <SearchPrompt />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,15 +1,14 @@
|
||||
"use client"
|
||||
|
||||
import { Suspense, useCallback, useEffect, useRef, useState } from "react"
|
||||
import { useQuery } from "convex/react"
|
||||
import { SearchIcon } from "lucide-react"
|
||||
import { usePathname, useSearchParams } from "next/navigation"
|
||||
|
||||
import { ContentCarousel } from "@/components/content-carousel"
|
||||
import { SearchResultsSkeleton } from "@/components/library-skeletons"
|
||||
import { SearchPrompt } from "@/components/search-prompt"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { SearchSongItem } from "@/components/search-song-item"
|
||||
import { SearchTopResultCard, type TopResult } from "@/components/search-top-result-card"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
const SEARCH_DEBOUNCE_MS = 300
|
||||
@@ -31,11 +30,11 @@ function readUrlQuery() {
|
||||
function SearchResults({ query }: { query: string }) {
|
||||
const hasQuery = query.length > 0
|
||||
|
||||
const results = useCachedQuery(
|
||||
const results = useQuery(
|
||||
api.library.searchLibrary,
|
||||
hasQuery ? { query } : "skip"
|
||||
)
|
||||
const playlistResults = useCachedQuery(
|
||||
const playlistResults = useQuery(
|
||||
api.playlists.searchPlaylists,
|
||||
hasQuery ? { query } : "skip"
|
||||
)
|
||||
@@ -52,11 +51,17 @@ function SearchResults({ query }: { query: string }) {
|
||||
const showResults = hasQuery && results !== undefined
|
||||
|
||||
if (isSearching) {
|
||||
return <SearchResultsSkeleton />
|
||||
return <LibraryLoading />
|
||||
}
|
||||
|
||||
if (!hasQuery) {
|
||||
return <SearchPrompt />
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center px-6 pb-28">
|
||||
<p className="text-center text-muted-foreground">
|
||||
Search for songs, albums, artists, and playlists in your library.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!showResults) {
|
||||
@@ -234,7 +239,7 @@ function SearchPageContent() {
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<Suspense fallback={<SearchResultsSkeleton />}>
|
||||
<Suspense fallback={<LibraryLoading />}>
|
||||
<SearchPageContent />
|
||||
</Suspense>
|
||||
)
|
||||
|
||||
@@ -1,18 +1,7 @@
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import { connection } from "next/server"
|
||||
"use client"
|
||||
|
||||
import { AuthForm } from "@/components/auth-form"
|
||||
import { convexServerOptions } from "@/lib/convex-server"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
export default async function SignInPage() {
|
||||
await connection()
|
||||
const { disableAccountCreation } = await fetchQuery(
|
||||
api.users.getAppSettings,
|
||||
{},
|
||||
convexServerOptions()
|
||||
)
|
||||
|
||||
return (
|
||||
<AuthForm flow="signIn" accountCreationDisabled={disableAccountCreation} />
|
||||
)
|
||||
export default function SignInPage() {
|
||||
return <AuthForm flow="signIn" />
|
||||
}
|
||||
@@ -1,18 +1,7 @@
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import { connection } from "next/server"
|
||||
"use client"
|
||||
|
||||
import { AuthForm } from "@/components/auth-form"
|
||||
import { convexServerOptions } from "@/lib/convex-server"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
export default async function SignUpPage() {
|
||||
await connection()
|
||||
const { disableAccountCreation } = await fetchQuery(
|
||||
api.users.getAppSettings,
|
||||
{},
|
||||
convexServerOptions()
|
||||
)
|
||||
|
||||
return (
|
||||
<AuthForm flow="signUp" accountCreationDisabled={disableAccountCreation} />
|
||||
)
|
||||
export default function SignUpPage() {
|
||||
return <AuthForm flow="signUp" />
|
||||
}
|
||||
+22
-48
@@ -7,7 +7,6 @@ import { ThemeProvider } from "@/components/theme-provider"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Toaster } from "@/components/ui/sonner"
|
||||
import type { Metadata } from "next"
|
||||
import { headers } from "next/headers"
|
||||
|
||||
const inter = Inter({ subsets: ["latin"], variable: "--font-sans" })
|
||||
|
||||
@@ -16,53 +15,28 @@ const fontMono = Geist_Mono({
|
||||
variable: "--font-mono",
|
||||
})
|
||||
|
||||
async function hostedUrl() {
|
||||
if (process.env.HOSTED_URL) {
|
||||
return new URL(process.env.HOSTED_URL)
|
||||
}
|
||||
|
||||
const requestHeaders = await headers()
|
||||
const host = (
|
||||
requestHeaders.get("x-forwarded-host") ?? requestHeaders.get("host")
|
||||
)
|
||||
?.split(",")[0]
|
||||
.trim()
|
||||
const protocol =
|
||||
requestHeaders.get("x-forwarded-proto")?.split(",")[0].trim() ?? "http"
|
||||
|
||||
try {
|
||||
return new URL(`${protocol}://${host}`)
|
||||
} catch {
|
||||
return new URL("http://localhost:3000")
|
||||
}
|
||||
}
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const url = await hostedUrl()
|
||||
|
||||
return {
|
||||
export const metadata: Metadata = {
|
||||
title: "oTunes",
|
||||
description: "Our Music",
|
||||
appleWebApp: {
|
||||
capable: true,
|
||||
title: "oTunes",
|
||||
startupImage: "/logo-dark.png",
|
||||
statusBarStyle: "default",
|
||||
},
|
||||
openGraph: {
|
||||
type: "website",
|
||||
url: process.env.HOSTED_URL || "http://localhost:3000",
|
||||
title: "oTunes",
|
||||
description: "Our Music",
|
||||
appleWebApp: {
|
||||
capable: true,
|
||||
title: "oTunes",
|
||||
startupImage: "/logo-dark.png",
|
||||
statusBarStyle: "default",
|
||||
},
|
||||
openGraph: {
|
||||
type: "website",
|
||||
url,
|
||||
title: "oTunes",
|
||||
description: "Our Music",
|
||||
siteName: "oTunes",
|
||||
images: [
|
||||
{
|
||||
url: "/logo-dark.png",
|
||||
},
|
||||
],
|
||||
},
|
||||
metadataBase: url,
|
||||
}
|
||||
siteName: "oTunes",
|
||||
images: [
|
||||
{
|
||||
url: "/logo-dark.png",
|
||||
},
|
||||
],
|
||||
},
|
||||
metadataBase: new URL(process.env.HOSTED_URL || "http://localhost:3000"),
|
||||
}
|
||||
|
||||
export default function RootLayout({
|
||||
@@ -82,8 +56,8 @@ export default function RootLayout({
|
||||
)}
|
||||
>
|
||||
<body className={"overflow-x-hidden"}>
|
||||
<ConvexAuthNextjsServerProvider storageNamespace="otunes">
|
||||
<ConvexClientProvider convexUrl={process.env.PUBLIC_CONVEX_URL}>
|
||||
<ConvexAuthNextjsServerProvider>
|
||||
<ConvexClientProvider>
|
||||
<ThemeProvider>
|
||||
{children}
|
||||
<Toaster />
|
||||
|
||||
@@ -6,7 +6,6 @@ import { useRouter } from "next/navigation"
|
||||
import { ListMusic, Plus } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useCacheScope } from "@/components/persistent-cache-provider"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
@@ -20,7 +19,6 @@ import { Input } from "@/components/ui/input"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
|
||||
|
||||
function countSongsToAdd(
|
||||
playlistSongIds: Id<"songs">[],
|
||||
@@ -82,7 +80,6 @@ export function AddToPlaylistProvider({
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const convex = useConvex()
|
||||
const cacheScope = useCacheScope()
|
||||
const router = useRouter()
|
||||
const addSongs = useMutation(api.playlists.addSongsToPlaylist)
|
||||
const createPlaylist = useMutation(api.playlists.createPlaylist)
|
||||
@@ -120,14 +117,9 @@ export function AddToPlaylistProvider({
|
||||
async (albumId: Id<"albums">) => {
|
||||
const requestId = ++selectionRequestRef.current
|
||||
try {
|
||||
const songIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getAlbumSongIds,
|
||||
{
|
||||
albumId,
|
||||
}
|
||||
)
|
||||
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
||||
albumId,
|
||||
})
|
||||
if (requestId === selectionRequestRef.current) {
|
||||
showAddToPlaylist(songIds)
|
||||
}
|
||||
@@ -139,21 +131,16 @@ export function AddToPlaylistProvider({
|
||||
}
|
||||
}
|
||||
},
|
||||
[convex, cacheScope, showAddToPlaylist]
|
||||
[convex, showAddToPlaylist]
|
||||
)
|
||||
|
||||
const openAddPlaylistToPlaylist = React.useCallback(
|
||||
async (playlistId: Id<"playlists">) => {
|
||||
const requestId = ++selectionRequestRef.current
|
||||
try {
|
||||
const songIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getPlaylistSongIds,
|
||||
{
|
||||
playlistId,
|
||||
}
|
||||
)
|
||||
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
|
||||
playlistId,
|
||||
})
|
||||
if (requestId === selectionRequestRef.current) {
|
||||
showAddToPlaylist(songIds)
|
||||
}
|
||||
@@ -165,21 +152,16 @@ export function AddToPlaylistProvider({
|
||||
}
|
||||
}
|
||||
},
|
||||
[convex, cacheScope, showAddToPlaylist]
|
||||
[convex, showAddToPlaylist]
|
||||
)
|
||||
|
||||
const openAddArtistToPlaylist = React.useCallback(
|
||||
async (artistId: Id<"artists">) => {
|
||||
const requestId = ++selectionRequestRef.current
|
||||
try {
|
||||
const songIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getArtistSongIds,
|
||||
{
|
||||
artistId,
|
||||
}
|
||||
)
|
||||
const songIds = await convex.query(api.playlists.getArtistSongIds, {
|
||||
artistId,
|
||||
})
|
||||
if (requestId === selectionRequestRef.current) {
|
||||
showAddToPlaylist(songIds)
|
||||
}
|
||||
@@ -191,7 +173,7 @@ export function AddToPlaylistProvider({
|
||||
}
|
||||
}
|
||||
},
|
||||
[convex, cacheScope, showAddToPlaylist]
|
||||
[convex, showAddToPlaylist]
|
||||
)
|
||||
|
||||
const openCreatePlaylist = React.useCallback(() => {
|
||||
|
||||
@@ -6,7 +6,6 @@ import Link from "next/link"
|
||||
import { MoreHorizontal, Play } from "lucide-react"
|
||||
import { useConvex } from "convex/react"
|
||||
|
||||
import { useCacheScope } from "@/components/persistent-cache-provider"
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import {
|
||||
@@ -26,7 +25,6 @@ import type { BrowseAlbum } from "@otunes/convex/types"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { albumCoverUrl } from "@/lib/cover-urls"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
|
||||
|
||||
let activeAlbumCardMenuClose: (() => void) | null = null
|
||||
|
||||
@@ -45,7 +43,6 @@ function closeExclusiveAlbumCardMenu(closeMenu: () => void) {
|
||||
|
||||
export function AlbumCard({ album }: { album: BrowseAlbum }) {
|
||||
const convex = useConvex()
|
||||
const cacheScope = useCacheScope()
|
||||
const { openAddAlbumToPlaylist } = useAddToPlaylist()
|
||||
const { isAlbumFavorite, toggleAlbumFavorite } = useFavorites()
|
||||
const { playAlbum } = usePlayback()
|
||||
@@ -80,14 +77,9 @@ export function AlbumCard({ album }: { album: BrowseAlbum }) {
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle": {
|
||||
const songIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getAlbumSongIds,
|
||||
{
|
||||
albumId: album.id as Id<"albums">,
|
||||
}
|
||||
)
|
||||
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
||||
albumId: album.id as Id<"albums">,
|
||||
})
|
||||
void runQueueAction(action, songIds)
|
||||
break
|
||||
}
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { AlbumView } from "@/components/album-view"
|
||||
import { CollectionDetailSkeleton } from "@/components/library-skeletons"
|
||||
import { PageMessage } from "@/components/page-message"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
|
||||
export function AlbumPage({
|
||||
albumId,
|
||||
highlightedSongId,
|
||||
}: {
|
||||
albumId: Id<"albums">
|
||||
highlightedSongId?: string
|
||||
}) {
|
||||
const album = useCachedQuery(api.library.browseAlbumDetail, { id: albumId })
|
||||
|
||||
if (album === undefined) {
|
||||
return <CollectionDetailSkeleton />
|
||||
}
|
||||
|
||||
if (album === null) {
|
||||
return <PageMessage>Album not found.</PageMessage>
|
||||
}
|
||||
|
||||
return (
|
||||
<AlbumView
|
||||
key={album.id}
|
||||
album={album}
|
||||
highlightedSongId={highlightedSongId}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -39,7 +39,6 @@ import {
|
||||
} from "@/lib/selection-range-styles"
|
||||
import { albumCoverUrl } from "@/lib/cover-urls"
|
||||
import { sumDurationSeconds } from "@/lib/media-summary"
|
||||
import { albumDetailSongs, rememberSongs } from "@/lib/song-cache"
|
||||
|
||||
function formatDuration(seconds: number): string {
|
||||
const minutes = Math.floor(seconds / 60)
|
||||
@@ -270,11 +269,6 @@ export function AlbumView({
|
||||
() => album.tracks.map((track) => track.id as Id<"songs">),
|
||||
[album.tracks]
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
rememberSongs(albumDetailSongs(album))
|
||||
}, [album])
|
||||
|
||||
const metadata = formatMetadata(album.genre, album.year)
|
||||
const [activeTrackId, setActiveTrackId] = React.useState("")
|
||||
const validHighlightedSongId = React.useMemo(() => {
|
||||
@@ -404,21 +398,14 @@ export function AlbumView({
|
||||
size="icon"
|
||||
className="rounded-full"
|
||||
aria-label="Shuffle album"
|
||||
onClick={() =>
|
||||
void playAlbumShuffled(
|
||||
album.id as Id<"albums">,
|
||||
albumSongIds
|
||||
)
|
||||
}
|
||||
onClick={() => void playAlbumShuffled(album.id as Id<"albums">)}
|
||||
>
|
||||
<Shuffle />
|
||||
</Button>
|
||||
<Button
|
||||
className="h-10 gap-2 rounded-full bg-foreground px-6 text-background hover:bg-foreground/90"
|
||||
aria-label={`Play ${album.title}`}
|
||||
onClick={() =>
|
||||
void playAlbum(album.id as Id<"albums">, albumSongIds)
|
||||
}
|
||||
onClick={() => void playAlbum(album.id as Id<"albums">)}
|
||||
>
|
||||
<Play className="fill-current" />
|
||||
Play
|
||||
|
||||
@@ -41,11 +41,9 @@ import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
import { useTheme } from "next-themes"
|
||||
import * as React from "react"
|
||||
import { useQuery } from "convex/react"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useMounted } from "@/hooks/use-mounted"
|
||||
import { clearPersistentCache } from "@/lib/persistent-cache"
|
||||
import { resetPlaybackStores } from "@otunes/convex/client/playback-store"
|
||||
|
||||
const OptionsModal = dynamic(() =>
|
||||
import("@/components/options-modal").then((module) => module.OptionsModal)
|
||||
@@ -66,8 +64,8 @@ export function AppSidebar() {
|
||||
const pathname = usePathname()
|
||||
const router = useRouter()
|
||||
const { signOut } = useAuthActions()
|
||||
const user = useCachedQuery(api.auth.currentUser)
|
||||
const sidebarPlaylists = useCachedQuery(api.playlists.listSidebarPlaylists)
|
||||
const user = useQuery(api.auth.currentUser)
|
||||
const sidebarPlaylists = useQuery(api.playlists.listSidebarPlaylists)
|
||||
const fallbackLetters = user?.name?.match(/\b(\w)/g)?.join("") || "NA"
|
||||
|
||||
const { resolvedTheme } = useTheme()
|
||||
@@ -76,8 +74,6 @@ export function AppSidebar() {
|
||||
|
||||
async function handleSignOut() {
|
||||
await signOut()
|
||||
resetPlaybackStores()
|
||||
await clearPersistentCache()
|
||||
router.push("/signin")
|
||||
}
|
||||
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { ArtistView } from "@/components/artist-view"
|
||||
import { ArtistDetailSkeleton } from "@/components/library-skeletons"
|
||||
import { PageMessage } from "@/components/page-message"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
|
||||
export function ArtistPage({ artistId }: { artistId: Id<"artists"> }) {
|
||||
const data = useCachedQuery(api.library.browseArtistDetail, { id: artistId })
|
||||
|
||||
if (data === undefined) {
|
||||
return <ArtistDetailSkeleton />
|
||||
}
|
||||
|
||||
if (data === null) {
|
||||
return <PageMessage>Artist not found.</PageMessage>
|
||||
}
|
||||
|
||||
return <ArtistView artist={data.artist} albums={data.albums} />
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import Image from "next/image"
|
||||
import { Play, Shuffle } from "lucide-react"
|
||||
import { useConvex } from "convex/react"
|
||||
|
||||
import { useCacheScope } from "@/components/persistent-cache-provider"
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
@@ -23,7 +22,6 @@ import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types"
|
||||
import { albumGridClassName } from "@/lib/album-grid-classes"
|
||||
import { artistCoverUrl } from "@/lib/cover-urls"
|
||||
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
|
||||
|
||||
export function ArtistView({
|
||||
artist,
|
||||
@@ -37,7 +35,6 @@ export function ArtistView({
|
||||
const { playArtist, playArtistShuffled } = usePlayback()
|
||||
const { runQueueAction } = useQueueMediaActions()
|
||||
const convex = useConvex()
|
||||
const cacheScope = useCacheScope()
|
||||
|
||||
async function handleMediaAction(action: MediaContextAction) {
|
||||
switch (action) {
|
||||
@@ -50,9 +47,7 @@ export function ArtistView({
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle": {
|
||||
const songIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
const songIds = await convex.query(
|
||||
api.playlists.getOrderedArtistSongIds,
|
||||
{ artistId: artist.id as Id<"artists"> }
|
||||
)
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { usePathname } from "next/navigation"
|
||||
import { useCallback } from "react"
|
||||
|
||||
import { ArtistsView } from "@/components/artists-view"
|
||||
import { ArtistsSkeleton, PageHeader } from "@/components/library-skeletons"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
const ARTISTS_PATH = "/library/artists"
|
||||
|
||||
function artistIdFromPathname(pathname: string) {
|
||||
const [, id] = pathname.slice(ARTISTS_PATH.length).split("/")
|
||||
return id ? decodeURIComponent(id) : undefined
|
||||
}
|
||||
|
||||
export function ArtistsPage() {
|
||||
const pathname = usePathname()
|
||||
const artists = useCachedQuery(api.library.browseArtists)
|
||||
const albums = useCachedQuery(api.library.browseAlbums)
|
||||
|
||||
const selectArtist = useCallback((artistId: string) => {
|
||||
window.history.pushState(null, "", `${ARTISTS_PATH}/${artistId}`)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<PageHeader title="Artists" />
|
||||
|
||||
{artists === undefined || albums === undefined ? (
|
||||
<ArtistsSkeleton />
|
||||
) : (
|
||||
<ArtistsView
|
||||
artists={artists}
|
||||
albums={albums}
|
||||
artistId={artistIdFromPathname(pathname)}
|
||||
onSelectArtist={selectArtist}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -3,10 +3,10 @@
|
||||
import * as React from "react"
|
||||
import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { ChevronRightIcon, Play, Shuffle } from "lucide-react"
|
||||
import { useConvex } from "convex/react"
|
||||
|
||||
import { useCacheScope } from "@/components/persistent-cache-provider"
|
||||
import { AlbumCard } from "@/components/album-card"
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { FavoriteMediaButton } from "@/components/favorite-media-button"
|
||||
@@ -24,7 +24,6 @@ import { cn } from "@/lib/utils"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types"
|
||||
import { artistCoverUrl } from "@/lib/cover-urls"
|
||||
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
|
||||
|
||||
function ArtistAvatar({ artist }: { artist: BrowseArtist }) {
|
||||
return (
|
||||
@@ -92,13 +91,12 @@ export function ArtistsView({
|
||||
artists,
|
||||
albums,
|
||||
artistId,
|
||||
onSelectArtist,
|
||||
}: {
|
||||
artists: BrowseArtist[]
|
||||
albums: BrowseAlbum[]
|
||||
artistId?: string
|
||||
onSelectArtist: (artistId: string) => void
|
||||
}) {
|
||||
const router = useRouter()
|
||||
const sortedArtists = React.useMemo(
|
||||
() => [...artists].sort((a, b) => a.name.localeCompare(b.name)),
|
||||
[artists]
|
||||
@@ -111,7 +109,6 @@ export function ArtistsView({
|
||||
return sortedArtists[0]?.id ?? ""
|
||||
}, [artistId, sortedArtists])
|
||||
const convex = useConvex()
|
||||
const cacheScope = useCacheScope()
|
||||
const { openAddArtistToPlaylist } = useAddToPlaylist()
|
||||
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
|
||||
const { playArtist, playArtistShuffled } = usePlayback()
|
||||
@@ -144,9 +141,7 @@ export function ArtistsView({
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle": {
|
||||
const songIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
const songIds = await convex.query(
|
||||
api.playlists.getOrderedArtistSongIds,
|
||||
{ artistId: artistId as Id<"artists"> }
|
||||
)
|
||||
@@ -167,7 +162,7 @@ export function ArtistsView({
|
||||
albumCount={albumCountByArtistId.get(artist.id) ?? 0}
|
||||
isSelected={artist.id === selectedId}
|
||||
isFavorite={isArtistFavorite(artist.id)}
|
||||
onSelect={() => onSelectArtist(artist.id)}
|
||||
onSelect={() => router.push(`/library/artists/${artist.id}`)}
|
||||
onMediaAction={(action) =>
|
||||
void handleMediaAction(artist.id, action)
|
||||
}
|
||||
|
||||
@@ -4,8 +4,10 @@ import { useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import Link from "next/link"
|
||||
import { useAuthActions } from "@convex-dev/auth/react"
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
@@ -48,19 +50,15 @@ const copy: Record<
|
||||
},
|
||||
}
|
||||
|
||||
export function AuthForm({
|
||||
flow,
|
||||
accountCreationDisabled,
|
||||
}: {
|
||||
flow: AuthFlow
|
||||
accountCreationDisabled: boolean
|
||||
}) {
|
||||
export function AuthForm({ flow }: { flow: AuthFlow }) {
|
||||
const { signIn } = useAuthActions()
|
||||
const router = useRouter()
|
||||
const appSettings = useQuery(api.users.getAppSettings)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
const text = copy[flow]
|
||||
const accountCreationDisabled = appSettings?.disableAccountCreation ?? false
|
||||
const signupsDisabled = flow === "signUp" && accountCreationDisabled
|
||||
const hideSignUpLink = flow === "signIn" && accountCreationDisabled
|
||||
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
CarouselItem,
|
||||
CarouselNext,
|
||||
CarouselPrevious,
|
||||
useCarousel,
|
||||
} from "@/components/ui/carousel"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { ArtistCard } from "./artist-card"
|
||||
@@ -35,34 +34,6 @@ function CarouselCard({
|
||||
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({
|
||||
title,
|
||||
href,
|
||||
@@ -80,36 +51,40 @@ export function ContentCarousel({
|
||||
}) {
|
||||
return (
|
||||
<section className={cn("flex min-w-0 flex-col gap-4", className)}>
|
||||
<div className="px-8">
|
||||
{href ? (
|
||||
<Link
|
||||
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" />
|
||||
</Link>
|
||||
) : (
|
||||
<h2 className="text-xl font-bold tracking-tight">{title}</h2>
|
||||
)}
|
||||
</div>
|
||||
{href ? (
|
||||
<Link
|
||||
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" />
|
||||
</Link>
|
||||
) : (
|
||||
<h2 className="text-xl font-bold tracking-tight">{title}</h2>
|
||||
)}
|
||||
|
||||
<Carousel
|
||||
opts={{
|
||||
align: "start",
|
||||
dragFree: true,
|
||||
slidesToScroll: "auto",
|
||||
containScroll: false,
|
||||
slidesToScroll: 5,
|
||||
}}
|
||||
className="group/carousel relative min-w-0 px-8"
|
||||
className="relative min-w-0"
|
||||
>
|
||||
<CarouselContent className={cn("w-full", carouselContentClassName)}>
|
||||
<CarouselContent
|
||||
className={cn("w-full", carouselContentClassName)}
|
||||
>
|
||||
{content.map((item) => (
|
||||
<CarouselItem key={item.id} className={slideClassName}>
|
||||
<CarouselCard item={item} />
|
||||
</CarouselItem>
|
||||
))}
|
||||
</CarouselContent>
|
||||
<CarouselControls />
|
||||
<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">
|
||||
<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>
|
||||
</section>
|
||||
)
|
||||
|
||||
@@ -1,44 +1,15 @@
|
||||
"use client"
|
||||
|
||||
import { ConvexAuthNextjsProvider } from "@convex-dev/auth/nextjs"
|
||||
import { buildConvexUrl } from "@otunes/convex/server-url"
|
||||
import { ConvexReactClient } from "convex/react"
|
||||
import { ReactNode } from "react"
|
||||
|
||||
import { PersistentCacheProvider } from "@/components/persistent-cache-provider"
|
||||
const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!)
|
||||
|
||||
// Server rendering never runs Convex queries, so this URL is never contacted.
|
||||
const SSR_CONVEX_URL = "http://127.0.0.1:3210"
|
||||
|
||||
let client: ConvexReactClient | undefined
|
||||
|
||||
function browserConvexUrl() {
|
||||
const { host, protocol } = window.location
|
||||
return buildConvexUrl(host, protocol === "https:" ? "https" : "http")
|
||||
}
|
||||
|
||||
function getConvexClient(convexUrl: string | undefined) {
|
||||
if (!client) {
|
||||
client = new ConvexReactClient(
|
||||
typeof window === "undefined"
|
||||
? SSR_CONVEX_URL
|
||||
: (convexUrl ??
|
||||
process.env.NEXT_PUBLIC_CONVEX_URL ??
|
||||
browserConvexUrl())
|
||||
)
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
export function ConvexClientProvider({
|
||||
convexUrl,
|
||||
children,
|
||||
}: {
|
||||
convexUrl?: string
|
||||
children: ReactNode
|
||||
}) {
|
||||
export function ConvexClientProvider({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<ConvexAuthNextjsProvider client={getConvexClient(convexUrl)}>
|
||||
<PersistentCacheProvider>{children}</PersistentCacheProvider> </ConvexAuthNextjsProvider>
|
||||
<ConvexAuthNextjsProvider client={convex}>
|
||||
{children}
|
||||
</ConvexAuthNextjsProvider>
|
||||
)
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { useMutation } from "convex/react"
|
||||
import { useMutation, useQuery } from "convex/react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
|
||||
@@ -33,7 +32,7 @@ export function useFavorites() {
|
||||
}
|
||||
|
||||
export function FavoritesProvider({ children }: { children: React.ReactNode }) {
|
||||
const favorites = useCachedQuery(api.favorites.getUserFavorites)
|
||||
const favorites = useQuery(api.favorites.getUserFavorites)
|
||||
const favoriteSong = useMutation(api.favorites.favoriteSong).withOptimisticUpdate(
|
||||
(store, { songId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Spinner } from "@/components/ui/spinner"
|
||||
|
||||
export function LibraryLoading() {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center p-6 pb-28">
|
||||
<Spinner className="size-6 text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,245 +0,0 @@
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import { albumGridClassName } from "@/lib/album-grid-classes"
|
||||
import { TRACK_LIST_CONTAINER } from "@/lib/selection-range-styles"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function LoadingRegion({
|
||||
className,
|
||||
children,
|
||||
}: {
|
||||
className?: string
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<div role="status" aria-busy className={className}>
|
||||
<span className="sr-only">Loading</span>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function PageHeader({ title }: { title: string }) {
|
||||
return (
|
||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
||||
<h1 className="text-lg font-semibold">{title}</h1>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
|
||||
function CardSkeleton({ round = false }: { round?: boolean }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Skeleton
|
||||
className={cn(
|
||||
"aspect-square w-full",
|
||||
round ? "rounded-full" : "rounded-lg"
|
||||
)}
|
||||
/>
|
||||
<div className={cn("flex flex-col gap-1.5", round && "items-center")}>
|
||||
<Skeleton className="h-3.5 w-3/4" />
|
||||
{round ? null : <Skeleton className="h-3 w-1/2" />}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CardGrid({ count }: { count: number }) {
|
||||
return (
|
||||
<div className={albumGridClassName}>
|
||||
{Array.from({ length: count }, (_, index) => (
|
||||
<CardSkeleton key={index} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function CardGridSkeleton({ count = 18 }: { count?: number }) {
|
||||
return (
|
||||
<LoadingRegion className="flex-1 overflow-hidden p-6 pb-28">
|
||||
<CardGrid count={count} />
|
||||
</LoadingRegion>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselRowSkeleton() {
|
||||
return (
|
||||
<section className="flex min-w-0 flex-col gap-4">
|
||||
<Skeleton className="h-7 w-44" />
|
||||
<div className="-ml-4 flex overflow-hidden">
|
||||
{Array.from({ length: 6 }, (_, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="min-w-0 shrink-0 grow-0 basis-1/2 pl-4 sm:basis-1/3 md:basis-1/4 lg:basis-1/5 xl:basis-1/6"
|
||||
>
|
||||
<CardSkeleton />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
export function HomeSkeleton() {
|
||||
return (
|
||||
<LoadingRegion className="flex flex-1 flex-col gap-10 overflow-hidden p-6 pb-28">
|
||||
<CarouselRowSkeleton />
|
||||
<CarouselRowSkeleton />
|
||||
</LoadingRegion>
|
||||
)
|
||||
}
|
||||
|
||||
function TrackRowSkeleton({ showCover = false }: { showCover?: boolean }) {
|
||||
return (
|
||||
<div className="flex items-center gap-4 py-2.5 pr-10 pl-8">
|
||||
{showCover ? (
|
||||
<Skeleton className="size-9 shrink-0 rounded" />
|
||||
) : (
|
||||
<Skeleton className="h-3.5 w-5 shrink-0" />
|
||||
)}
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-1.5">
|
||||
<Skeleton className="h-3.5 w-2/5 max-w-72" />
|
||||
<Skeleton className="h-3 w-1/4 max-w-40" />
|
||||
</div>
|
||||
<Skeleton className="h-3 w-9 shrink-0" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function TrackListSkeleton({
|
||||
count = 12,
|
||||
showCover = false,
|
||||
}: {
|
||||
count?: number
|
||||
showCover?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
{Array.from({ length: count }, (_, index) => (
|
||||
<TrackRowSkeleton key={index} showCover={showCover} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function SongListSkeleton() {
|
||||
return (
|
||||
<LoadingRegion className="flex-1 overflow-hidden pt-9 pb-28">
|
||||
<TrackListSkeleton count={16} showCover />
|
||||
</LoadingRegion>
|
||||
)
|
||||
}
|
||||
|
||||
/** Matches the header + track list layout of album and playlist pages. */
|
||||
export function CollectionDetailSkeleton() {
|
||||
return (
|
||||
<LoadingRegion className="flex h-svh flex-col overflow-hidden pb-28">
|
||||
<div className="mx-auto w-full max-w-9/10 min-w-0">
|
||||
<div className="flex flex-col gap-8 px-6 pt-6 pb-8 sm:flex-row sm:items-end">
|
||||
<Skeleton className="mx-auto aspect-square w-full max-w-60 shrink-0 rounded-lg sm:mx-0" />
|
||||
<div className="flex min-w-0 flex-1 flex-col items-center gap-4 sm:items-start">
|
||||
<div className="flex w-full flex-col items-center gap-2 sm:items-start">
|
||||
<Skeleton className="h-3 w-14" />
|
||||
<Skeleton className="h-9 w-2/3 max-w-96" />
|
||||
<Skeleton className="h-5 w-40" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="size-9 rounded-full" />
|
||||
<Skeleton className="h-10 w-28 rounded-full" />
|
||||
<Skeleton className="size-9 rounded-full" />
|
||||
<Skeleton className="size-9 rounded-full" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className={TRACK_LIST_CONTAINER}>
|
||||
<TrackListSkeleton />
|
||||
</div>
|
||||
</LoadingRegion>
|
||||
)
|
||||
}
|
||||
|
||||
export function ArtistDetailSkeleton() {
|
||||
return (
|
||||
<LoadingRegion className="flex h-svh flex-col overflow-hidden pb-28">
|
||||
<div className="flex min-w-0 items-center gap-4 px-6 pt-6 pb-8 sm:gap-6">
|
||||
<Skeleton className="size-32 shrink-0 rounded-full sm:size-40" />
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-4">
|
||||
<Skeleton className="h-10 w-1/2 max-w-80" />
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="size-11 rounded-full" />
|
||||
<Skeleton className="size-11 rounded-full" />
|
||||
<Skeleton className="size-11 rounded-full" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-4 px-6">
|
||||
<Skeleton className="h-7 w-24" />
|
||||
<CardGrid count={6} />
|
||||
</div>
|
||||
</LoadingRegion>
|
||||
)
|
||||
}
|
||||
|
||||
function ArtistListSkeleton() {
|
||||
return (
|
||||
<div className="w-72 shrink-0 overflow-hidden border-r pb-28">
|
||||
{Array.from({ length: 14 }, (_, index) => (
|
||||
<div key={index} className="flex items-center gap-3 px-4 py-2.5">
|
||||
<Skeleton className="size-8 shrink-0 rounded-full" />
|
||||
<Skeleton className="h-3.5 flex-1" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function ArtistsSkeleton() {
|
||||
return (
|
||||
<LoadingRegion className="flex min-h-0 flex-1">
|
||||
<ArtistListSkeleton />
|
||||
<div className="min-w-0 flex-1 overflow-hidden">
|
||||
<div className="flex items-center justify-between gap-4 border-b px-6 py-4">
|
||||
<Skeleton className="h-7 w-48" />
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="size-9 rounded-full" />
|
||||
<Skeleton className="size-9 rounded-full" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-6">
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-8 sm:grid-cols-3 lg:grid-cols-4">
|
||||
{Array.from({ length: 8 }, (_, index) => (
|
||||
<CardSkeleton key={index} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</LoadingRegion>
|
||||
)
|
||||
}
|
||||
|
||||
export function SearchResultsSkeleton() {
|
||||
return (
|
||||
<LoadingRegion className="flex-1 overflow-hidden p-6 pb-28">
|
||||
<div className="mx-auto flex max-w-6xl flex-col gap-10">
|
||||
<section className="flex flex-col gap-4">
|
||||
<Skeleton className="h-7 w-36" />
|
||||
<div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-3">
|
||||
{Array.from({ length: 3 }, (_, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center gap-4 rounded-lg p-3"
|
||||
>
|
||||
<Skeleton className="size-16 shrink-0 rounded-md" />
|
||||
<div className="flex flex-1 flex-col gap-2">
|
||||
<Skeleton className="h-4 w-2/3" />
|
||||
<Skeleton className="h-3 w-1/3" />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<CarouselRowSkeleton />
|
||||
</div>
|
||||
</LoadingRegion>
|
||||
)
|
||||
}
|
||||
@@ -848,15 +848,9 @@ function UsersSection({
|
||||
.catch((error: Error) => toast.error(error.message))
|
||||
}}
|
||||
/>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="disable-signups" className="font-normal">
|
||||
Disable account creation
|
||||
</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Stops people from registering themselves. You can still create
|
||||
accounts.
|
||||
</p>
|
||||
</div>
|
||||
<Label htmlFor="disable-signups" className="font-normal">
|
||||
Disable account creation
|
||||
</Label>
|
||||
</div>
|
||||
<Button type="button" size="sm" onClick={() => setCreateOpen(true)}>
|
||||
<UserPlus />
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
export function PageMessage({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<div className="flex flex-1 items-center justify-center pb-28">
|
||||
<p className="text-sm text-muted-foreground">{children}</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useAuthToken } from "@convex-dev/auth/react"
|
||||
import { createContext, ReactNode, useContext, useEffect, useMemo } from "react"
|
||||
|
||||
import { loadPersistentCache } from "@/lib/persistent-cache"
|
||||
|
||||
export const ANONYMOUS_CACHE_SCOPE = "anon"
|
||||
|
||||
const CacheScopeContext = createContext(ANONYMOUS_CACHE_SCOPE)
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
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 the signed-in user. */
|
||||
export function PersistentCacheProvider({ children }: { children: ReactNode }) {
|
||||
const token = useAuthToken()
|
||||
const scope = useMemo(
|
||||
() => userIdFromToken(token) ?? ANONYMOUS_CACHE_SCOPE,
|
||||
[token]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
void loadPersistentCache()
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<CacheScopeContext.Provider value={scope}>
|
||||
{children}
|
||||
</CacheScopeContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useCacheScope() {
|
||||
return useContext(CacheScopeContext)
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
useSyncExternalStore,
|
||||
useMemo,
|
||||
} from "react"
|
||||
import { useConvex, useMutation, useQuery } from "convex/react"
|
||||
import { useMutation, useQuery } from "convex/react"
|
||||
import type Hls from "hls.js"
|
||||
import { toast } from "sonner"
|
||||
|
||||
@@ -20,26 +20,13 @@ import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
import { playbackStreamPlan } from "@otunes/convex/playback-stream"
|
||||
import {
|
||||
ANONYMOUS_CACHE_SCOPE,
|
||||
useCacheScope,
|
||||
} from "@/components/persistent-cache-provider"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useMediaSession } from "@/hooks/use-media-session"
|
||||
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
|
||||
import { supportsDolbyAtmosPlayback } from "@/lib/dolby-atmos-support"
|
||||
import { flushPersistentCache } from "@/lib/persistent-cache"
|
||||
import * as playbackQueue from "@otunes/convex/client/playback-queue"
|
||||
import type { RepeatMode } from "@otunes/convex/client/playback-queue"
|
||||
import {
|
||||
getPlaybackStore,
|
||||
getServerPlaybackSnapshot,
|
||||
} from "@otunes/convex/client/playback-store"
|
||||
import { rememberSongs, useSong } from "@/lib/song-cache"
|
||||
import { songHlsPlaylistUrl, songPlayUrl } from "@/lib/song-play-url"
|
||||
|
||||
type RepeatMode = "none" | "once" | "always"
|
||||
|
||||
const PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS = 5
|
||||
const PROGRESS_SAVE_INTERVAL_MS = 5000
|
||||
|
||||
type PlaybackContextValue = {
|
||||
queueSongIds: Id<"songs">[]
|
||||
@@ -66,23 +53,12 @@ type PlaybackContextValue = {
|
||||
sortDirection: "asc" | "desc"
|
||||
}
|
||||
) => Promise<void>
|
||||
/** Pass `songIds` when the caller already has the album's tracks. */
|
||||
playAlbum: (albumId: Id<"albums">, songIds?: Id<"songs">[]) => Promise<void>
|
||||
playAlbumShuffled: (
|
||||
albumId: Id<"albums">,
|
||||
songIds?: Id<"songs">[]
|
||||
) => Promise<void>
|
||||
playAlbum: (albumId: Id<"albums">) => Promise<void>
|
||||
playAlbumShuffled: (albumId: Id<"albums">) => Promise<void>
|
||||
playArtist: (artistId: Id<"artists">) => Promise<void>
|
||||
playArtistShuffled: (artistId: Id<"artists">) => Promise<void>
|
||||
/** Pass `songIds` when the caller already has the playlist's songs. */
|
||||
playPlaylist: (
|
||||
playlistId: Id<"playlists">,
|
||||
songIds?: Id<"songs">[]
|
||||
) => Promise<void>
|
||||
playPlaylistShuffled: (
|
||||
playlistId: Id<"playlists">,
|
||||
songIds?: Id<"songs">[]
|
||||
) => Promise<void>
|
||||
playPlaylist: (playlistId: Id<"playlists">) => Promise<void>
|
||||
playPlaylistShuffled: (playlistId: Id<"playlists">) => Promise<void>
|
||||
toggleShuffle: () => Promise<void>
|
||||
cycleRepeat: () => Promise<void>
|
||||
clearQueue: () => Promise<void>
|
||||
@@ -303,62 +279,8 @@ export function usePlaybackProgress() {
|
||||
}
|
||||
|
||||
export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
const convex = useConvex()
|
||||
const cacheScope = useCacheScope()
|
||||
const isSignedIn = cacheScope !== ANONYMOUS_CACHE_SCOPE
|
||||
const store = useMemo(
|
||||
() => getPlaybackStore(isSignedIn ? cacheScope : null),
|
||||
[cacheScope, isSignedIn]
|
||||
)
|
||||
const playback = useSyncExternalStore(
|
||||
store.subscribe,
|
||||
store.getSnapshot,
|
||||
getServerPlaybackSnapshot
|
||||
)
|
||||
const user = useCachedQuery(api.auth.currentUser)
|
||||
const serverPlayback = useQuery(
|
||||
api.playback.getPlaybackState,
|
||||
isSignedIn ? {} : "skip"
|
||||
)
|
||||
const syncPlaybackStateMutation = useMutation(
|
||||
api.playback.syncPlaybackState
|
||||
)
|
||||
const recordPlayMutation = useMutation(api.playback.recordPlay)
|
||||
const updateSongProgressMutation = useMutation(api.playback.updateSongProgress)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSignedIn) {
|
||||
return
|
||||
}
|
||||
store.setTransport((state) =>
|
||||
syncPlaybackStateMutation({
|
||||
songQueue: state.queue,
|
||||
queueHistory: state.history,
|
||||
shuffleEnabled: state.shuffleEnabled,
|
||||
repeatEnabled: state.repeatEnabled,
|
||||
currentSongProgress: state.progressSeconds,
|
||||
})
|
||||
)
|
||||
return () => store.setTransport(null)
|
||||
}, [store, isSignedIn, syncPlaybackStateMutation])
|
||||
|
||||
useEffect(() => {
|
||||
if (!serverPlayback) {
|
||||
return
|
||||
}
|
||||
if (serverPlayback.currentSong) {
|
||||
rememberSongs([serverPlayback.currentSong])
|
||||
}
|
||||
store.receiveServerState(serverPlayback)
|
||||
}, [store, serverPlayback])
|
||||
|
||||
const recordPlay = useCallback(
|
||||
(args: { songId?: Id<"songs">; playlistId?: Id<"playlists"> }) => {
|
||||
void recordPlayMutation(args).catch(() => {})
|
||||
},
|
||||
[recordPlayMutation]
|
||||
)
|
||||
|
||||
const user = useQuery(api.auth.currentUser)
|
||||
const playback = useQuery(api.playback.getPlaybackState)
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null)
|
||||
const hlsRef = useRef<Hls | null>(null)
|
||||
const preloadAudioRef = useRef<HTMLAudioElement | null>(null)
|
||||
@@ -370,6 +292,56 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
const autoPlayNextRef = useRef(false)
|
||||
const intentionalLoadRef = useRef(false)
|
||||
const ignoreAudioSyncRef = useRef(false)
|
||||
const playInOrderMutation = useMutation(api.playback.playInOrder)
|
||||
const playShuffledMutation = useMutation(api.playback.playShuffled)
|
||||
const addToQueueNextMutation = useMutation(api.playback.addToQueueNext)
|
||||
const addToQueueLastMutation = useMutation(api.playback.addToQueueLast)
|
||||
const playFromSongMutation = useMutation(api.playback.playFromSong)
|
||||
const playFromLibrarySongMutation = useMutation(
|
||||
api.playback.playFromLibrarySong
|
||||
)
|
||||
const playAlbumMutation = useMutation(api.playback.playAlbum)
|
||||
const playAlbumShuffledMutation = useMutation(api.playback.playAlbumShuffled)
|
||||
const playArtistMutation = useMutation(api.playback.playArtist)
|
||||
const playArtistShuffledMutation = useMutation(
|
||||
api.playback.playArtistShuffled
|
||||
)
|
||||
const playPlaylistMutation = useMutation(api.playback.playPlaylist)
|
||||
const playPlaylistShuffledMutation = useMutation(
|
||||
api.playback.playPlaylistShuffled
|
||||
)
|
||||
const toggleShuffleMutation = useMutation(
|
||||
api.playback.toggleShuffle
|
||||
).withOptimisticUpdate((store) => {
|
||||
const current = store.getQuery(api.playback.getPlaybackState, {})
|
||||
if (!current) return
|
||||
store.setQuery(api.playback.getPlaybackState, {}, {
|
||||
...current,
|
||||
shuffleEnabled: !current.shuffleEnabled,
|
||||
})
|
||||
})
|
||||
const cycleRepeatMutation = useMutation(
|
||||
api.playback.cycleRepeat
|
||||
).withOptimisticUpdate((store) => {
|
||||
const current = store.getQuery(api.playback.getPlaybackState, {})
|
||||
if (!current) return
|
||||
const next =
|
||||
current.repeatEnabled === "none"
|
||||
? "once"
|
||||
: current.repeatEnabled === "once"
|
||||
? "always"
|
||||
: "none"
|
||||
store.setQuery(api.playback.getPlaybackState, {}, {
|
||||
...current,
|
||||
repeatEnabled: next,
|
||||
})
|
||||
})
|
||||
const clearQueueMutation = useMutation(api.playback.clearQueue)
|
||||
const reorderQueueMutation = useMutation(api.playback.reorderQueue)
|
||||
const skipToQueueIndexMutation = useMutation(api.playback.skipToQueueIndex)
|
||||
const skipNextMutation = useMutation(api.playback.skipNext)
|
||||
const skipPreviousMutation = useMutation(api.playback.skipPrevious)
|
||||
const updateSongProgressMutation = useMutation(api.playback.updateSongProgress)
|
||||
|
||||
const progressRestoredForSongRef = useRef<Id<"songs"> | null>(null)
|
||||
const lastSavedProgressRef = useRef(-1)
|
||||
@@ -409,29 +381,29 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
}, [])
|
||||
|
||||
const queueSongIds = playback.queue
|
||||
const currentSongId = queueSongIds[0] ?? null
|
||||
const currentSong = useSong(currentSongId)
|
||||
const currentSong = playback?.currentSong ?? null
|
||||
const currentSongId = currentSong?.id ?? null
|
||||
const playbackQuality = user?.playbackQuality
|
||||
const preferAtmos = user?.preferAtmos
|
||||
const duration =
|
||||
currentSongId && measuredDuration?.songId === currentSongId
|
||||
currentSong && measuredDuration?.songId === currentSong.id
|
||||
? measuredDuration.seconds
|
||||
: (currentSong?.durationSeconds ?? 0)
|
||||
|
||||
useEffect(() => {
|
||||
durationRef.current = duration
|
||||
}, [duration])
|
||||
const currentSongDoc = useCachedQuery(
|
||||
const currentSongDoc = useQuery(
|
||||
api.library.getSongPlaybackInfo,
|
||||
currentSongId ? { id: currentSongId } : "skip"
|
||||
currentSong ? { id: currentSong.id } : "skip"
|
||||
)
|
||||
const isPlaybackActive = Boolean(currentSongId && isPlaying)
|
||||
const repeatEnabled = playback.repeatEnabled
|
||||
const queueLength = queueSongIds.length
|
||||
const isPlaybackActive = Boolean(currentSong && isPlaying)
|
||||
const repeatEnabled = playback?.repeatEnabled ?? "none"
|
||||
const queueLength = playback?.queueSongIds.length ?? 0
|
||||
const queueSongIds = playback?.queueSongIds ?? []
|
||||
const nextQueueSongId =
|
||||
queueSongIds.length > 1 ? queueSongIds[1] : null
|
||||
const nextQueueSongDoc = useCachedQuery(
|
||||
const nextQueueSongDoc = useQuery(
|
||||
api.library.getSongPlaybackInfo,
|
||||
nextQueueSongId ? { id: nextQueueSongId } : "skip"
|
||||
)
|
||||
@@ -467,19 +439,16 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
|
||||
lastSavedProgressRef.current = progressSeconds
|
||||
store.setProgress(currentSongId, progressSeconds)
|
||||
if (isSignedIn) {
|
||||
void updateSongProgressMutation({
|
||||
songId: currentSongId,
|
||||
progressSeconds,
|
||||
}).catch(() => {})
|
||||
}
|
||||
void updateSongProgressMutation({
|
||||
songId: currentSongId,
|
||||
progressSeconds,
|
||||
})
|
||||
},
|
||||
[currentSongId, store, isSignedIn, updateSongProgressMutation]
|
||||
[currentSongId, updateSongProgressMutation]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!currentSongId) {
|
||||
if (!currentSongId || !playback) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -489,8 +458,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
progressRestoredForSongRef.current = currentSongId
|
||||
lastSavedProgressRef.current = -1
|
||||
setProgressToRestore(store.getState().progressSeconds)
|
||||
}, [currentSongId, store])
|
||||
setProgressToRestore(playback.currentSongProgress ?? 0)
|
||||
}, [currentSongId, playback])
|
||||
|
||||
useEffect(() => {
|
||||
if (progressToRestore === null || progressToRestore <= 0) {
|
||||
@@ -551,36 +520,13 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
|
||||
saveProgress(audio.currentTime)
|
||||
}, PROGRESS_SAVE_INTERVAL_MS)
|
||||
}, 5000)
|
||||
|
||||
return () => {
|
||||
window.clearInterval(interval)
|
||||
}
|
||||
}, [isPlaying, currentSongId, saveProgress])
|
||||
|
||||
useEffect(() => {
|
||||
const persistNow = () => {
|
||||
const audio = audioRef.current
|
||||
const restorePending = progressToRestore !== null && progressToRestore > 0
|
||||
if (audio && currentSongId && !restorePending) {
|
||||
saveProgress(audio.currentTime)
|
||||
}
|
||||
flushPersistentCache()
|
||||
}
|
||||
const onVisibilityChange = () => {
|
||||
if (document.visibilityState === "hidden") {
|
||||
persistNow()
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("pagehide", persistNow)
|
||||
document.addEventListener("visibilitychange", onVisibilityChange)
|
||||
return () => {
|
||||
window.removeEventListener("pagehide", persistNow)
|
||||
document.removeEventListener("visibilitychange", onVisibilityChange)
|
||||
}
|
||||
}, [currentSongId, progressToRestore, saveProgress])
|
||||
|
||||
useEffect(() => {
|
||||
isPlayingRef.current = isPlaying
|
||||
}, [isPlaying])
|
||||
@@ -851,7 +797,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
useEffect(() => {
|
||||
const audio = audioRef.current
|
||||
if (!audio || !currentSongId) {
|
||||
if (!audio || !currentSong) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -881,7 +827,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
return () => {
|
||||
audio.removeEventListener("canplay", onCanPlay)
|
||||
}
|
||||
}, [isPlaying, currentSongId, attemptPlayback])
|
||||
}, [isPlaying, currentSong, attemptPlayback])
|
||||
|
||||
useEffect(() => {
|
||||
const audio = audioRef.current
|
||||
@@ -890,8 +836,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
|
||||
const handleEnded = () => {
|
||||
const loopsSingleSong = repeatEnabled === "always" && queueLength === 1
|
||||
if (repeatEnabled === "once" || loopsSingleSong) {
|
||||
if (repeatEnabled === "once") {
|
||||
audio.currentTime = 0
|
||||
void audio.play()
|
||||
return
|
||||
@@ -940,23 +885,34 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
}
|
||||
|
||||
store.update(playbackQueue.skipNext)
|
||||
void skipNextMutation()
|
||||
.then(() => {
|
||||
if (shouldContinuePlaying) {
|
||||
autoPlayNextRef.current = true
|
||||
isPlayingRef.current = true
|
||||
setIsPlaying(true)
|
||||
return
|
||||
}
|
||||
|
||||
if (!shouldContinuePlaying) {
|
||||
autoPlayNextRef.current = false
|
||||
isPlayingRef.current = false
|
||||
audio.currentTime = 0
|
||||
currentTimeRef.current = 0
|
||||
setCurrentTime(0)
|
||||
setIsPlaying(false)
|
||||
}
|
||||
autoPlayNextRef.current = false
|
||||
isPlayingRef.current = false
|
||||
audio.currentTime = 0
|
||||
currentTimeRef.current = 0
|
||||
setCurrentTime(0)
|
||||
setIsPlaying(false)
|
||||
})
|
||||
.catch(() => {
|
||||
autoPlayNextRef.current = false
|
||||
isPlayingRef.current = false
|
||||
setIsPlaying(false)
|
||||
})
|
||||
}
|
||||
|
||||
const handleError = () => {
|
||||
if (intentionalLoadRef.current) {
|
||||
return
|
||||
}
|
||||
if (!currentSongId || playbackErrorHandledRef.current) {
|
||||
if (!currentSong || playbackErrorHandledRef.current) {
|
||||
return
|
||||
}
|
||||
playbackErrorHandledRef.current = true
|
||||
@@ -980,7 +936,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
toast.error("Playback error", {
|
||||
description: "Could not play this track. The queue has been cleared.",
|
||||
})
|
||||
store.update(playbackQueue.clearQueue)
|
||||
void clearQueueMutation()
|
||||
}
|
||||
|
||||
audio.addEventListener("ended", handleEnded)
|
||||
@@ -992,13 +948,14 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
}, [
|
||||
repeatEnabled,
|
||||
currentSongId,
|
||||
currentSong,
|
||||
queueLength,
|
||||
nextQueueSongId,
|
||||
nextQueueSongDoc,
|
||||
user,
|
||||
dolbyAtmosSupported,
|
||||
store,
|
||||
skipNextMutation,
|
||||
clearQueueMutation,
|
||||
destroyHls,
|
||||
runWithoutAudioSync,
|
||||
attemptPlayback,
|
||||
@@ -1011,17 +968,16 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
|
||||
const syncDuration = () => {
|
||||
if (!currentSongId) {
|
||||
return
|
||||
}
|
||||
if (Number.isFinite(audio.duration) && audio.duration > 0) {
|
||||
setMeasuredDuration({
|
||||
songId: currentSongId,
|
||||
seconds: audio.duration,
|
||||
})
|
||||
if (currentSong) {
|
||||
setMeasuredDuration({
|
||||
songId: currentSong.id,
|
||||
seconds: audio.duration,
|
||||
})
|
||||
}
|
||||
} else if (currentSong) {
|
||||
setMeasuredDuration({
|
||||
songId: currentSongId,
|
||||
songId: currentSong.id,
|
||||
seconds: currentSong.durationSeconds,
|
||||
})
|
||||
}
|
||||
@@ -1043,72 +999,17 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
audio.removeEventListener("loadedmetadata", syncDuration)
|
||||
audio.removeEventListener("seeked", syncTime)
|
||||
}
|
||||
}, [currentSongId, currentSong])
|
||||
|
||||
const playRequestRef = useRef(0)
|
||||
|
||||
const startPlayback = useCallback(
|
||||
(
|
||||
recipe: (
|
||||
state: playbackQueue.PlaybackQueueState
|
||||
) => playbackQueue.PlaybackQueueState,
|
||||
recorded: { playlistId?: Id<"playlists"> } = {}
|
||||
) => {
|
||||
playRequestRef.current += 1
|
||||
const previousSongId = store.getState().queue[0]
|
||||
store.update(recipe)
|
||||
const firstSongId = store.getState().queue[0]
|
||||
if (!firstSongId) {
|
||||
return
|
||||
}
|
||||
|
||||
if (firstSongId === previousSongId) {
|
||||
seekTo(0)
|
||||
}
|
||||
setIsPlaying(true)
|
||||
recordPlay(
|
||||
recorded.playlistId
|
||||
? { playlistId: recorded.playlistId }
|
||||
: { songId: firstSongId }
|
||||
)
|
||||
},
|
||||
[store, seekTo, recordPlay]
|
||||
)
|
||||
|
||||
const playCollection = useCallback(
|
||||
async (
|
||||
songIds: Id<"songs">[] | Promise<Id<"songs">[]>,
|
||||
shuffled: boolean,
|
||||
recorded: { playlistId?: Id<"playlists"> } = {}
|
||||
) => {
|
||||
const request = ++playRequestRef.current
|
||||
let resolvedSongIds: Id<"songs">[]
|
||||
try {
|
||||
resolvedSongIds = await songIds
|
||||
} catch {
|
||||
toast.error("Could not load songs to play")
|
||||
return
|
||||
}
|
||||
|
||||
if (request !== playRequestRef.current || resolvedSongIds.length === 0) {
|
||||
return
|
||||
}
|
||||
startPlayback(
|
||||
(state) => playbackQueue.startQueue(state, resolvedSongIds, shuffled),
|
||||
recorded
|
||||
)
|
||||
},
|
||||
[startPlayback]
|
||||
)
|
||||
}, [currentSong])
|
||||
|
||||
const playInOrder = useCallback(
|
||||
async (songIds: Id<"songs">[]) => {
|
||||
if (songIds.length === 0) {
|
||||
return
|
||||
}
|
||||
startPlayback((state) => playbackQueue.startQueue(state, songIds, false))
|
||||
await playInOrderMutation({ songIds })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[startPlayback]
|
||||
[playInOrderMutation]
|
||||
)
|
||||
|
||||
const playShuffled = useCallback(
|
||||
@@ -1116,9 +1017,10 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
if (songIds.length === 0) {
|
||||
return
|
||||
}
|
||||
startPlayback((state) => playbackQueue.startQueue(state, songIds, true))
|
||||
await playShuffledMutation({ songIds })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[startPlayback]
|
||||
[playShuffledMutation]
|
||||
)
|
||||
|
||||
const addToQueueNext = useCallback(
|
||||
@@ -1126,10 +1028,10 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
if (songIds.length === 0) {
|
||||
return
|
||||
}
|
||||
store.update((state) => playbackQueue.addToQueue(state, songIds, "next"))
|
||||
await addToQueueNextMutation({ songIds })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[store]
|
||||
[addToQueueNextMutation]
|
||||
)
|
||||
|
||||
const addToQueueLast = useCallback(
|
||||
@@ -1137,19 +1039,18 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
if (songIds.length === 0) {
|
||||
return
|
||||
}
|
||||
store.update((state) => playbackQueue.addToQueue(state, songIds, "last"))
|
||||
await addToQueueLastMutation({ songIds })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[store]
|
||||
[addToQueueLastMutation]
|
||||
)
|
||||
|
||||
const playFromSong = useCallback(
|
||||
async (songId: Id<"songs">, songIds: Id<"songs">[]) => {
|
||||
startPlayback((state) =>
|
||||
playbackQueue.startQueueFromSong(state, songId, songIds)
|
||||
)
|
||||
await playFromSongMutation({ songId, songIds })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[startPlayback]
|
||||
[playFromSongMutation]
|
||||
)
|
||||
|
||||
const playFromLibrarySong = useCallback(
|
||||
@@ -1160,155 +1061,84 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
sortDirection: "asc" | "desc"
|
||||
}
|
||||
) => {
|
||||
startPlayback((state) =>
|
||||
playbackQueue.startQueueFromSong(state, songId, [songId])
|
||||
)
|
||||
const request = playRequestRef.current
|
||||
|
||||
let songIds: Id<"songs">[]
|
||||
try {
|
||||
songIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.library.browseSortedSongIds,
|
||||
sort
|
||||
)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
if (request === playRequestRef.current) {
|
||||
store.update((state) =>
|
||||
playbackQueue.extendQueueFromSong(state, songId, songIds)
|
||||
)
|
||||
}
|
||||
await playFromLibrarySongMutation({ songId, ...sort })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[convex, cacheScope, store, startPlayback]
|
||||
)
|
||||
|
||||
const loadAlbumSongIds = useCallback(
|
||||
(albumId: Id<"albums">, songIds?: Id<"songs">[]) =>
|
||||
songIds ??
|
||||
fetchCachedQuery(convex, cacheScope, api.playlists.getAlbumSongIds, {
|
||||
albumId,
|
||||
}),
|
||||
[convex, cacheScope]
|
||||
)
|
||||
|
||||
const loadArtistSongIds = useCallback(
|
||||
(artistId: Id<"artists">) =>
|
||||
fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getOrderedArtistSongIds,
|
||||
{ artistId }
|
||||
),
|
||||
[convex, cacheScope]
|
||||
)
|
||||
|
||||
const loadPlaylistSongIds = useCallback(
|
||||
(playlistId: Id<"playlists">, songIds?: Id<"songs">[]) =>
|
||||
songIds ??
|
||||
fetchCachedQuery(convex, cacheScope, api.playlists.getPlaylistSongIds, {
|
||||
playlistId,
|
||||
}),
|
||||
[convex, cacheScope]
|
||||
[playFromLibrarySongMutation]
|
||||
)
|
||||
|
||||
const playAlbum = useCallback(
|
||||
(albumId: Id<"albums">, songIds?: Id<"songs">[]) =>
|
||||
playCollection(loadAlbumSongIds(albumId, songIds), false),
|
||||
[playCollection, loadAlbumSongIds]
|
||||
async (albumId: Id<"albums">) => {
|
||||
await playAlbumMutation({ albumId })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[playAlbumMutation]
|
||||
)
|
||||
|
||||
const playAlbumShuffled = useCallback(
|
||||
(albumId: Id<"albums">, songIds?: Id<"songs">[]) =>
|
||||
playCollection(loadAlbumSongIds(albumId, songIds), true),
|
||||
[playCollection, loadAlbumSongIds]
|
||||
async (albumId: Id<"albums">) => {
|
||||
await playAlbumShuffledMutation({ albumId })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[playAlbumShuffledMutation]
|
||||
)
|
||||
|
||||
const playArtist = useCallback(
|
||||
(artistId: Id<"artists">) =>
|
||||
playCollection(loadArtistSongIds(artistId), false),
|
||||
[playCollection, loadArtistSongIds]
|
||||
async (artistId: Id<"artists">) => {
|
||||
await playArtistMutation({ artistId })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[playArtistMutation]
|
||||
)
|
||||
|
||||
const playArtistShuffled = useCallback(
|
||||
(artistId: Id<"artists">) =>
|
||||
playCollection(loadArtistSongIds(artistId), true),
|
||||
[playCollection, loadArtistSongIds]
|
||||
async (artistId: Id<"artists">) => {
|
||||
await playArtistShuffledMutation({ artistId })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[playArtistShuffledMutation]
|
||||
)
|
||||
|
||||
const playPlaylist = useCallback(
|
||||
(playlistId: Id<"playlists">, songIds?: Id<"songs">[]) =>
|
||||
playCollection(loadPlaylistSongIds(playlistId, songIds), false, {
|
||||
playlistId,
|
||||
}),
|
||||
[playCollection, loadPlaylistSongIds]
|
||||
async (playlistId: Id<"playlists">) => {
|
||||
await playPlaylistMutation({ playlistId })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[playPlaylistMutation]
|
||||
)
|
||||
|
||||
const playPlaylistShuffled = useCallback(
|
||||
(playlistId: Id<"playlists">, songIds?: Id<"songs">[]) =>
|
||||
playCollection(loadPlaylistSongIds(playlistId, songIds), true, {
|
||||
playlistId,
|
||||
}),
|
||||
[playCollection, loadPlaylistSongIds]
|
||||
async (playlistId: Id<"playlists">) => {
|
||||
await playPlaylistShuffledMutation({ playlistId })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[playPlaylistShuffledMutation]
|
||||
)
|
||||
|
||||
const toggleQueueOpen = useCallback(() => {
|
||||
setQueueOpen((open) => !open)
|
||||
}, [])
|
||||
|
||||
const toggleShuffle = useCallback(async () => {
|
||||
store.update(playbackQueue.toggleShuffle)
|
||||
}, [store])
|
||||
|
||||
const cycleRepeat = useCallback(async () => {
|
||||
store.update(playbackQueue.cycleRepeat)
|
||||
}, [store])
|
||||
|
||||
const clearQueue = useCallback(async () => {
|
||||
playRequestRef.current += 1
|
||||
store.update(playbackQueue.clearQueue)
|
||||
setIsPlaying(false)
|
||||
}, [store])
|
||||
|
||||
const reorderQueue = useCallback(
|
||||
async (songIds: Id<"songs">[]) => {
|
||||
store.update((state) => playbackQueue.reorderQueue(state, songIds))
|
||||
},
|
||||
[store]
|
||||
)
|
||||
|
||||
const skipToQueueIndex = useCallback(
|
||||
async (index: number) => {
|
||||
store.update((state) => playbackQueue.skipToQueueIndex(state, index))
|
||||
},
|
||||
[store]
|
||||
)
|
||||
|
||||
const skipNext = useCallback(async () => {
|
||||
const before = store.getState()
|
||||
if (before.repeatEnabled === "none" && before.queue.length <= 1) {
|
||||
const isFinishingQueue =
|
||||
repeatEnabled === "none" && queueSongIds.length <= 1
|
||||
if (isFinishingQueue) {
|
||||
setIsPlaying(false)
|
||||
}
|
||||
store.update(playbackQueue.skipNext)
|
||||
if (store.getState().queue[0] === before.queue[0]) {
|
||||
seekTo(0)
|
||||
}
|
||||
}, [store, seekTo])
|
||||
await skipNextMutation()
|
||||
if (isFinishingQueue) {
|
||||
seekTo(0)
|
||||
}
|
||||
}, [repeatEnabled, queueSongIds.length, seekTo, skipNextMutation])
|
||||
|
||||
const skipPrevious = useCallback(async () => {
|
||||
if (currentTimeRef.current > PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS) {
|
||||
seekTo(0)
|
||||
return
|
||||
}
|
||||
const previousSongId = store.getState().queue[0]
|
||||
store.update(playbackQueue.skipPrevious)
|
||||
if (store.getState().queue[0] === previousSongId) {
|
||||
seekTo(0)
|
||||
}
|
||||
}, [store, seekTo])
|
||||
await skipPreviousMutation()
|
||||
}, [seekTo, skipPreviousMutation])
|
||||
|
||||
useMediaSession({
|
||||
song: currentSong,
|
||||
@@ -1323,11 +1153,11 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
const value = useMemo<PlaybackContextValue>(
|
||||
() => ({
|
||||
queueSongIds: playback.queue,
|
||||
queueHistorySongIds: playback.history,
|
||||
currentSong,
|
||||
shuffleEnabled: playback.shuffleEnabled,
|
||||
repeatEnabled: playback.repeatEnabled,
|
||||
queueSongIds: playback?.queueSongIds ?? [],
|
||||
queueHistorySongIds: playback?.queueHistorySongIds ?? [],
|
||||
currentSong: playback?.currentSong ?? null,
|
||||
shuffleEnabled: playback?.shuffleEnabled ?? false,
|
||||
repeatEnabled: playback?.repeatEnabled ?? "none",
|
||||
queueOpen,
|
||||
isPlaying: isPlaybackActive,
|
||||
volume,
|
||||
@@ -1347,18 +1177,28 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
playArtistShuffled,
|
||||
playPlaylist,
|
||||
playPlaylistShuffled,
|
||||
toggleShuffle,
|
||||
cycleRepeat,
|
||||
clearQueue,
|
||||
reorderQueue,
|
||||
skipToQueueIndex,
|
||||
toggleShuffle: async () => {
|
||||
await toggleShuffleMutation()
|
||||
},
|
||||
cycleRepeat: async () => {
|
||||
await cycleRepeatMutation()
|
||||
},
|
||||
clearQueue: async () => {
|
||||
await clearQueueMutation()
|
||||
setIsPlaying(false)
|
||||
},
|
||||
reorderQueue: async (songIds) => {
|
||||
await reorderQueueMutation({ songIds })
|
||||
},
|
||||
skipToQueueIndex: async (index) => {
|
||||
await skipToQueueIndexMutation({ index })
|
||||
},
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
dolbyAtmosSupported,
|
||||
}),
|
||||
[
|
||||
playback,
|
||||
currentSong,
|
||||
queueOpen,
|
||||
isPlaybackActive,
|
||||
volume,
|
||||
@@ -1376,11 +1216,11 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
playArtistShuffled,
|
||||
playPlaylist,
|
||||
playPlaylistShuffled,
|
||||
toggleShuffle,
|
||||
cycleRepeat,
|
||||
clearQueue,
|
||||
reorderQueue,
|
||||
skipToQueueIndex,
|
||||
toggleShuffleMutation,
|
||||
cycleRepeatMutation,
|
||||
clearQueueMutation,
|
||||
reorderQueueMutation,
|
||||
skipToQueueIndexMutation,
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
dolbyAtmosSupported,
|
||||
|
||||
@@ -9,7 +9,6 @@ import { playlistCoverUrl } from "@/lib/cover-urls"
|
||||
import { useConvex } from "convex/react"
|
||||
import { MoreHorizontal, Play } from "lucide-react"
|
||||
|
||||
import { useCacheScope } from "@/components/persistent-cache-provider"
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import {
|
||||
MediaContextMenuItems,
|
||||
@@ -24,11 +23,9 @@ import {
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
|
||||
|
||||
export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
|
||||
const convex = useConvex()
|
||||
const cacheScope = useCacheScope()
|
||||
const { openAddPlaylistToPlaylist } = useAddToPlaylist()
|
||||
const { playPlaylist } = usePlayback()
|
||||
const { runQueueAction } = useQueueMediaActions()
|
||||
@@ -41,14 +38,9 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle": {
|
||||
const songIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getPlaylistSongIds,
|
||||
{
|
||||
playlistId: playlist.id as Id<"playlists">,
|
||||
}
|
||||
)
|
||||
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
|
||||
playlistId: playlist.id as Id<"playlists">,
|
||||
})
|
||||
void runQueueAction(action, songIds)
|
||||
break
|
||||
}
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { CollectionDetailSkeleton } from "@/components/library-skeletons"
|
||||
import { PageMessage } from "@/components/page-message"
|
||||
import { PlaylistView } from "@/components/playlist-view"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
|
||||
export function PlaylistPage({ playlistId }: { playlistId: Id<"playlists"> }) {
|
||||
const playlist = useCachedQuery(api.playlists.browsePlaylistDetail, {
|
||||
id: playlistId,
|
||||
})
|
||||
|
||||
if (playlist === undefined) {
|
||||
return <CollectionDetailSkeleton />
|
||||
}
|
||||
|
||||
if (playlist === null) {
|
||||
return <PageMessage>Playlist not found.</PageMessage>
|
||||
}
|
||||
|
||||
return <PlaylistView key={playlist.id} playlist={playlist} />
|
||||
}
|
||||
|
||||
export function FavoritesPlaylistPage() {
|
||||
const favorites = useCachedQuery(api.favorites.browseFavoritesPlaylistDetail)
|
||||
|
||||
if (favorites === undefined) {
|
||||
return <CollectionDetailSkeleton />
|
||||
}
|
||||
|
||||
if (favorites === null) {
|
||||
return <PageMessage>Sign in to view your favorites.</PageMessage>
|
||||
}
|
||||
|
||||
return <PlaylistView playlist={favorites} />
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
import * as React from "react"
|
||||
import Image from "next/image"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useMutation } from "convex/react"
|
||||
import { useMutation, useQuery } from "convex/react"
|
||||
import { Play, Share2, Shuffle, Star, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
@@ -22,7 +22,6 @@ import {
|
||||
DropdownMenuSeparator,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||
import { useTrackSelection } from "@/hooks/use-track-selection"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
@@ -31,7 +30,6 @@ import type { BrowsePlaylistDetail, BrowseSong } from "@otunes/convex/types"
|
||||
import { albumCoverUrl, playlistCoverUrl } from "@/lib/cover-urls"
|
||||
import { copyPlaylistLink } from "@/lib/media-links"
|
||||
import { sumDurationSeconds } from "@/lib/media-summary"
|
||||
import { rememberSongs } from "@/lib/song-cache"
|
||||
import { cn } from "@/lib/utils"
|
||||
import {
|
||||
getSelectionRangePositions,
|
||||
@@ -265,7 +263,7 @@ function PlaylistSongRow({
|
||||
export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
const router = useRouter()
|
||||
const isFavorites = playlist.isFavorites === true
|
||||
const currentUser = useCachedQuery(api.auth.currentUser)
|
||||
const currentUser = useQuery(api.auth.currentUser)
|
||||
const isOwner =
|
||||
currentUser === undefined
|
||||
? playlist.isOwner
|
||||
@@ -279,8 +277,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
} = useFavorites()
|
||||
const {
|
||||
currentSong,
|
||||
playInOrder,
|
||||
playShuffled,
|
||||
playPlaylist,
|
||||
playPlaylistShuffled,
|
||||
playFromSong,
|
||||
@@ -293,7 +289,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
const unsubscribe = useMutation(api.playlists.unsubscribeFromPlaylist)
|
||||
|
||||
const [playlistSongs, setPlaylistSongs] = React.useState(playlist.songs)
|
||||
const [syncedPlaylist, setSyncedPlaylist] = React.useState(playlist)
|
||||
const [hiddenFavoriteIds, setHiddenFavoriteIds] = React.useState(
|
||||
() => new Set<string>()
|
||||
)
|
||||
@@ -309,12 +304,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
const [isSubscribed, setIsSubscribed] = React.useState(playlist.isSubscribed)
|
||||
const [subscriptionPending, setSubscriptionPending] = React.useState(false)
|
||||
|
||||
if (syncedPlaylist !== playlist) {
|
||||
setSyncedPlaylist(playlist)
|
||||
setPlaylistSongs(playlist.songs)
|
||||
setIsSubscribed(playlist.isSubscribed)
|
||||
}
|
||||
|
||||
const {
|
||||
selectedIds,
|
||||
selectedCount,
|
||||
@@ -333,19 +322,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
[songs]
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
rememberSongs(playlist.songs)
|
||||
}, [playlist.songs])
|
||||
|
||||
function playAll(shuffled: boolean) {
|
||||
if (playlist.id) {
|
||||
const play = shuffled ? playPlaylistShuffled : playPlaylist
|
||||
void play(playlist.id, playlistSongIds)
|
||||
} else {
|
||||
void (shuffled ? playShuffled : playInOrder)(playlistSongIds)
|
||||
}
|
||||
}
|
||||
|
||||
function resolveTargetIds(fallbackSongId?: string) {
|
||||
return selectedIds.size > 0
|
||||
? Array.from(selectedIds)
|
||||
@@ -544,7 +520,9 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
size="icon"
|
||||
className="rounded-full"
|
||||
aria-label="Shuffle playlist"
|
||||
onClick={() => playAll(true)}
|
||||
onClick={() =>
|
||||
void playPlaylistShuffled(playlist.id as Id<"playlists">)
|
||||
}
|
||||
disabled={playlistSongIds.length === 0}
|
||||
>
|
||||
<Shuffle />
|
||||
@@ -552,7 +530,9 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
<Button
|
||||
className="h-10 gap-2 rounded-full bg-foreground px-6 text-background hover:bg-foreground/90"
|
||||
aria-label={`Play ${playlist.title}`}
|
||||
onClick={() => playAll(false)}
|
||||
onClick={() =>
|
||||
void playPlaylist(playlist.id as Id<"playlists">)
|
||||
}
|
||||
disabled={playlistSongIds.length === 0}
|
||||
>
|
||||
<Play className="fill-current" />
|
||||
|
||||
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user