Compare commits

..
371 changed files with 36251 additions and 17703 deletions

No files matched your search

+12 -4
View File
@@ -3,8 +3,12 @@
# Keeps Docker builds fast, lean, and free of development files.
############################################################
# Dependencies (installed inside Docker, never copied)
node_modules/
# Dependencies (installed inside Docker, never copied).
# Use **/ so nested workspace installs (apps/web/node_modules, etc.) are
# excluded — a bare "node_modules/" only matches the repo root and would
# let host symlinks overwrite the image install during COPY.
**/node_modules
**/node_modules/**
.pnpm-store/
npm-debug.log*
yarn-debug.log*
@@ -13,7 +17,8 @@ pnpm-debug.log*
lerna-debug.log*
# Next.js build outputs (always generated during `next build`)
.next/
**/.next
**/.next/**
out/
dist/
build/
@@ -131,4 +136,7 @@ AGENTS.md
*.claude*
*.gemini*
*.openai*
*.anthropic*
*.anthropic*
# Expo mobile app (not needed in web Docker image)
apps/mobile/
+15 -12
View File
@@ -1,19 +1,20 @@
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
node_modules/
# testing
/coverage
# next.js
/.next/
/out/
apps/web/.next/
apps/web/out/
# expo
apps/mobile/.expo/
apps/mobile/dist/
apps/mobile/web-build/
apps/mobile/expo-env.d.ts
apps/mobile/ios/
apps/mobile/android/
# production
/build
@@ -33,9 +34,11 @@ pnpm-debug.log*
# typescript
*.tsbuildinfo
next-env.d.ts
apps/web/next-env.d.ts
/.idea
/.convex
/.cursor
/.cursor
/database
docker-compose.yml
+2
View File
@@ -0,0 +1,2 @@
auto-install-peers=true
strict-peer-dependencies=false
+1 -1
View File
@@ -6,6 +6,6 @@
"trailingComma": "es5",
"printWidth": 80,
"plugins": ["prettier-plugin-tailwindcss"],
"tailwindStylesheet": "app/globals.css",
"tailwindStylesheet": "apps/web/app/globals.css",
"tailwindFunctions": ["cn", "cva"]
}
+3 -1
View File
@@ -1,5 +1,7 @@
<!-- BEGIN:nextjs-agent-rules -->
# This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `apps/web/node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
The Next.js web app lives in `apps/web`.
<!-- END:nextjs-agent-rules -->
+174 -71
View File
@@ -1,3 +1,5 @@
# syntax=docker/dockerfile:1
# ============================================
# Stage 1: Dependencies Installation Stage
# ============================================
@@ -7,108 +9,209 @@
# 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
# Audio-only static ffmpeg. The distro package links video filters that pull
# in LLVM and Mesa (~420MB) for codecs this app never uses.
ARG FFMPEG_VERSION=7.1.5
ARG FFMPEG_SHA256=de668509caf9e35e3cd162473441fdb29538c6d96ed080292b3cf9e6fc5d558f
FROM node:${NODE_VERSION} AS node
FROM node:${NODE_VERSION} AS dependencies
# Set working directory
WORKDIR /app
# Copy package-related files first to leverage Docker's caching mechanism
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* .npmrc* ./
# Only manifests needed for @otunes/web and its workspace dependency (@otunes/convex).
# Mobile is intentionally omitted so its deps are never installed.
COPY package.json pnpm-lock.yaml .npmrc ./
COPY apps/web/package.json ./apps/web/
COPY packages/convex/package.json ./packages/convex/
# Install project dependencies with frozen lockfile for reproducible builds
RUN --mount=type=cache,target=/root/.npm \
--mount=type=cache,target=/usr/local/share/.cache/yarn \
--mount=type=cache,target=/root/.local/share/pnpm/store \
if [ -f package-lock.json ]; then \
npm ci --no-audit --no-fund; \
elif [ -f yarn.lock ]; then \
corepack enable yarn && yarn install --frozen-lockfile --production=false; \
elif [ -f pnpm-lock.yaml ]; then \
corepack enable pnpm && pnpm install --frozen-lockfile; \
else \
echo "No lockfile found." && exit 1; \
fi
# Explicit workspace — do not use apps/* so mobile cannot be discovered.
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
RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
corepack enable pnpm && \
pnpm install --frozen-lockfile --filter @otunes/web...
# ============================================
# Stage 2: Build Next.js application in standalone mode
# ============================================
FROM node:${NODE_VERSION} AS builder
# Reuse the installed workspace. Copying node_modules into a new layer retars
# hundreds of thousands of files on every source change.
FROM dependencies AS builder
# Set working directory
WORKDIR /app
# Copy project dependencies from dependencies stage
COPY --from=dependencies /app/node_modules ./node_modules
COPY apps/web /tmp/src/apps/web
COPY packages/convex /tmp/src/packages/convex
# Copy application source code
COPY . .
# 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
ENV NODE_ENV=production
# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry during the build.
# ENV NEXT_TELEMETRY_DISABLED=1
WORKDIR /app/apps/web
# Build Next.js application
# If you want to speed up Docker rebuilds, you can cache the build artifacts
# by adding: --mount=type=cache,target=/app/.next/cache
# This caches the .next/cache directory across builds, but it also prevents
# .next/cache/fetch-cache from being included in the final image, meaning
# cached fetch responses from the build won't be available at runtime.
RUN if [ -f package-lock.json ]; then \
npm run build; \
elif [ -f yarn.lock ]; then \
corepack enable yarn && yarn build; \
elif [ -f pnpm-lock.yaml ]; then \
corepack enable pnpm && pnpm build; \
else \
echo "No lockfile found." && exit 1; \
fi
RUN --mount=type=cache,target=/app/apps/web/.next/cache \
corepack enable pnpm && pnpm build
# ============================================
# Stage 3: Run Next.js application
# Stage 3: Convex functions, deployed to the bundled backend on boot
# ============================================
FROM node:${NODE_VERSION} AS runner
FROM node:${NODE_VERSION} AS convex-functions
# Set working directory
WORKDIR /app
# Set production environment variables
ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
COPY package.json pnpm-lock.yaml .npmrc ./
COPY packages/convex/package.json ./packages/convex/
# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry during the run time.
# ENV NEXT_TELEMETRY_DISABLED=1
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 production assets
COPY --from=builder --chown=node:node /app/public ./public
COPY packages/convex ./packages/convex
# Set the correct permission for prerender cache
RUN mkdir .next
RUN chown node:node .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
# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --chown=node:node /app/.next/standalone ./
COPY --from=builder --chown=node:node /app/.next/static ./.next/static
# ============================================
# Stage 4: Audio-only ffmpeg
# ============================================
# If you want to persist the fetch cache generated during the build so that
# cached responses are available immediately on startup, uncomment this line:
# COPY --from=builder --chown=node:node /app/.next/cache ./.next/cache
FROM ubuntu:24.04 AS ffmpeg
# Switch to non-root user for security best practices
USER node
ARG FFMPEG_VERSION
ARG FFMPEG_SHA256
# Expose port 3000 to allow HTTP traffic
EXPOSE 3000
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/*
# Start Next.js standalone server
CMD ["node", "server.js"]
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 []
+74 -38
View File
@@ -2,58 +2,94 @@
Your music, my music, _**our**_ music. Self-hosted music streaming app and server.
## Monorepo
This project uses [pnpm workspaces](https://pnpm.io/workspaces):
| Package | Path | Description |
| --- | --- | --- |
| `@otunes/web` | `apps/web` | Next.js web app |
| `@otunes/mobile` | `apps/mobile` | Expo React Native mobile app |
| `@otunes/convex` | `packages/convex` | Shared Convex backend and client types |
### Development
Install dependencies from the repository root:
```bash
pnpm install
```
Run the web app:
```bash
pnpm dev
# or
pnpm dev:web
```
Run the mobile app:
```bash
pnpm dev:mobile
```
Run the Convex backend (from the shared package):
```bash
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
pnpm build # build web app
pnpm lint # lint all packages
pnpm typecheck # typecheck all packages
pnpm format # format with Prettier
```
## Hosting with Docker
Here's an example `docker-compose.yml` file to get you started:
The image runs both the web app and its Convex backend, so there is nothing to configure. Here's an example `docker-compose.yml`:
```yaml
name: music
services:
otunes:
ports:
- "3000:3000"
volumes:
- /SomeAttachedStorage/Music:/data
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: git.abunchofknowitalls.com/joshuafhiggins/otunes:latest
backend:
stop_grace_period: 10s
stop_signal: SIGINT
restart: unless-stopped
ports:
- "3210:3210"
- "3211:3211"
- "3000:3000" # web app
- "3210:3210" # Convex
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
- ./otunes-data:/convex/data
- /SomeAttachedStorage/Music:/data
stop_grace_period: 10s
restart: unless-stopped
```
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.
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.
`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.
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.
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.
### 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.
## Downloads
-9
View File
@@ -1,9 +0,0 @@
import { LibraryLoading } from "@/components/library-loading"
export default function Loading() {
return (
<div className="flex h-svh flex-col">
<LibraryLoading />
</div>
)
}
-37
View File
@@ -1,37 +0,0 @@
"use client"
import { useParams } from "next/navigation"
import { useQuery } from "convex/react"
import { AlbumView } from "@/components/album-view"
import { LibraryLoading } from "@/components/library-loading"
import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
import type { BrowseAlbumDetail } from "@/convex/library"
export default function Page() {
const { id } = useParams<{ id: string }>()
const album = useQuery(api.library.browseAlbumDetail, {
id: id as Id<"albums">,
})
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} />
}
-9
View File
@@ -1,9 +0,0 @@
import { LibraryLoading } from "@/components/library-loading"
export default function Loading() {
return (
<div className="flex h-svh flex-col">
<LibraryLoading />
</div>
)
}
-43
View File
@@ -1,43 +0,0 @@
"use client"
import { useParams } from "next/navigation"
import { useQuery } from "convex/react"
import { ArtistView } from "@/components/artist-view"
import { LibraryLoading } from "@/components/library-loading"
import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
export default function Page() {
const { id } = useParams<{ id: string }>()
const data = useQuery(api.library.browseArtistDetail, {
id: 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}
recentlyAdded={data.recentlyAdded}
recentlyPlayed={data.recentlyPlayed}
/>
)
}
-31
View File
@@ -1,31 +0,0 @@
"use client"
import { useQuery } from "convex/react"
import { AlbumCard } from "@/components/album-card"
import { LibraryLoading } from "@/components/library-loading"
import { api } from "@/convex/_generated/api"
export default function Page() {
const albums = useQuery(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">Albums</h1>
</header>
{albums === undefined ? (
<LibraryLoading />
) : (
<div className="flex-1 overflow-y-auto p-6 pb-28">
<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} />
))}
</div>
</div>
)}
</div>
)
}
-26
View File
@@ -1,26 +0,0 @@
"use client"
import { useQuery } from "convex/react"
import { ArtistsView } from "@/components/artists-view"
import { LibraryLoading } from "@/components/library-loading"
import { api } from "@/convex/_generated/api"
export default function Page() {
const artists = useQuery(api.library.browseArtists)
const albums = useQuery(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>
)
}
-17
View File
@@ -1,17 +0,0 @@
"use client"
import { useQuery } from "convex/react"
import { LibraryLoading } from "@/components/library-loading"
import { SongsView } from "@/components/songs-view"
import { api } from "@/convex/_generated/api"
export default function Page() {
const songs = useQuery(api.library.browseSongs)
if (songs === undefined) {
return <LibraryLoading />
}
return <SongsView songs={songs} />
}
-46
View File
@@ -1,46 +0,0 @@
"use client"
import { useQuery } from "convex/react"
import { ContentCarousel } from "@/components/content-carousel"
import { LibraryLoading } from "@/components/library-loading"
import { api } from "@/convex/_generated/api"
export default function Page() {
const recentlyAdded = useQuery(api.library.browseRecentlyAdded)
const recentlyPlayed = useQuery(api.library.browseAlbums)
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">
<ContentCarousel
title="Recently Played"
href="/recently-played"
content={recentlyPlayed.slice(0, 9)}
/>
<ContentCarousel
title="Recently Added"
href="/recently-added"
content={recentlyAdded.slice(0, 9)}
/>
</div>
</div>
</div>
)
}
-37
View File
@@ -1,37 +0,0 @@
"use client"
import { useParams } from "next/navigation"
import { useQuery } from "convex/react"
import { LibraryLoading } from "@/components/library-loading"
import { PlaylistView } from "@/components/playlist-view"
import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
import type { BrowsePlaylistDetail } from "@/convex/library"
export default function Page() {
const { id } = useParams<{ id: string }>()
const playlist = useQuery(api.playlists.browsePlaylistDetail, {
id: 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 playlist={playlist} />
}
-33
View File
@@ -1,33 +0,0 @@
"use client"
import { useQuery } from "convex/react"
import { LibraryLoading } from "@/components/library-loading"
import { PlaylistView } from "@/components/playlist-view"
import { api } from "@/convex/_generated/api"
export default function Page() {
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} />
}
-39
View File
@@ -1,39 +0,0 @@
"use client"
import { useQuery } from "convex/react"
import { ContentCarousel } from "@/components/content-carousel"
import { LibraryLoading } from "@/components/library-loading"
import { api } from "@/convex/_generated/api"
import type { PlaylistSummary } from "@/convex/library"
import {
albumGridCarouselContentClassName,
albumGridCarouselSlideClassName,
albumGridClassName,
} from "@/lib/album-grid-classes"
import { AlbumCard } from "@/components/album-card"
import { PlaylistCard } from "@/components/playlist-card"
export default function Page() {
const playlists = useQuery(api.playlists.listAllPlaylists)
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">Playlists</h1>
</header>
{playlists === undefined ? (
<LibraryLoading />
) : (
<div className="flex-1 overflow-y-auto p-6 pb-28">
<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} />
))}
</div>
</div>
)}
</div>
)
}
-31
View File
@@ -1,31 +0,0 @@
"use client"
import { useQuery } from "convex/react"
import { AlbumCard } from "@/components/album-card"
import { LibraryLoading } from "@/components/library-loading"
import { api } from "@/convex/_generated/api"
export default function Page() {
const albums = useQuery(api.library.browseRecentlyAdded)
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">Recently Added</h1>
</header>
{albums === undefined ? (
<LibraryLoading />
) : (
<div className="flex-1 overflow-y-auto p-6 pb-28">
<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} />
))}
</div>
</div>
)}
</div>
)
}
-31
View File
@@ -1,31 +0,0 @@
"use client"
import { useQuery } from "convex/react"
import { AlbumCard } from "@/components/album-card"
import { LibraryLoading } from "@/components/library-loading"
import { api } from "@/convex/_generated/api"
export default function Page() {
const albums = useQuery(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">Recently Played</h1>
</header>
{albums === undefined ? (
<LibraryLoading />
) : (
<div className="flex-1 overflow-y-auto p-6 pb-28">
<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} />
))}
</div>
</div>
)}
</div>
)
}
-127
View File
@@ -1,127 +0,0 @@
"use client"
import { useDeferredValue, useState } from "react"
import { useQuery } from "convex/react"
import { SearchIcon } from "lucide-react"
import { ContentCarousel } from "@/components/content-carousel"
import { LibraryLoading } from "@/components/library-loading"
import { SearchSongItem } from "@/components/search-song-item"
import { SearchTopResultCard, type TopResult } from "@/components/search-top-result-card"
import { api } from "@/convex/_generated/api"
import type {
BrowseAlbum,
BrowseArtist,
BrowseSong,
PlaylistSummary,
} from "@/convex/library"
export default function Page() {
const [query, setQuery] = useState("")
const deferredQuery = useDeferredValue(query.trim())
const hasQuery = deferredQuery.length > 0
const results = useQuery(
api.library.searchLibrary,
hasQuery ? { query: deferredQuery } : "skip"
)
const playlistResults = useQuery(
api.playlists.searchPlaylists,
hasQuery ? { query: deferredQuery } : "skip"
)
const showPlaylists =
hasQuery && playlistResults !== undefined && playlistResults.length > 0
const isSearching = hasQuery && results === undefined
const hasLibraryResults =
results &&
(results.topResults.length > 0 ||
results.artists.length > 0 ||
results.albums.length > 0 ||
results.songs.length > 0)
const showResults = hasQuery && results !== undefined
return (
<div className="flex h-svh flex-col">
<header className="flex items-center justify-center border-b px-4 py-3">
<div className="relative w-full max-w-xl">
<SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
<input
type="search"
data-slot="input"
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder="Search"
className="h-10 w-full min-w-0 rounded-full border border-input bg-input/30 pr-3 pl-9 text-sm text-foreground transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
</header>
{isSearching ? (
<LibraryLoading />
) : !hasQuery ? (
<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>
) : !showResults ? null : (
<div className="flex-1 overflow-y-auto p-6 pb-28">
<div className="mx-auto flex max-w-6xl flex-col gap-10">
{!hasLibraryResults && (
<p className="text-muted-foreground">
No library results for &ldquo;{deferredQuery}&rdquo;
</p>
)}
{results.topResults.length > 0 && (
<section className="flex flex-col gap-4">
<h2 className="text-xl font-bold tracking-tight">Top Results</h2>
<div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-3">
{results.topResults.map((result) => (
<SearchTopResultCard
key={`${result.kind}-${result.item.id}`}
result={result as TopResult}
/>
))}
</div>
</section>
)}
{results.artists.length > 0 && (
<ContentCarousel
title="Artists"
content={results.artists}
/>
)}
{results.albums.length > 0 && (
<ContentCarousel
title="Albums"
content={results.albums}
/>
)}
{results.songs.length > 0 && (
<section className="flex flex-col gap-4">
<h2 className="text-xl font-bold tracking-tight">Songs</h2>
<div className="grid gap-x-6 gap-y-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{results.songs.map((song) => (
<SearchSongItem key={song.id} song={song} />
))}
</div>
</section>
)}
{showPlaylists && (
<ContentCarousel
title="Playlists"
content={playlistResults ?? []}
/>
)}
</div>
</div>
)}
</div>
)
}
-166
View File
@@ -1,166 +0,0 @@
import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
import { audioContentTypeForPath } from "@/lib/audio-content-type"
import { getConvexClient } from "@/lib/convex-server"
import { NextRequest, NextResponse } from "next/server"
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"
import fs from "node:fs/promises"
const DATA_DIR = process.env.NEXT_PUBLIC_CONVEX_URL?.includes("127.0.0.1")
? "/Users/joshuafhiggins/Downloads/test"
: process.env.DATA || "/data"
function ffmpegToReadableStream(ffmpegProcess: ChildProcessWithoutNullStreams) {
let closed = false
return new ReadableStream({
start(controller) {
const finalize = (err?: Error) => {
if (closed) {
return
}
closed = true
try {
if (err) {
controller.error(err)
} else {
controller.close()
}
} catch {
// Consumer may have already closed the stream (e.g. track change).
}
}
ffmpegProcess.stdout.on("data", (chunk: Buffer) => {
if (closed) {
return
}
try {
controller.enqueue(new Uint8Array(chunk))
} catch {
closed = true
ffmpegProcess.kill("SIGKILL")
}
})
ffmpegProcess.stderr.on("data", (data) => {
//console.error(`FFmpeg log: ${data.toString()}`)
})
ffmpegProcess.stdout.on("end", () => finalize())
ffmpegProcess.stdout.on("error", (err) => finalize(err))
ffmpegProcess.on("close", (code) => {
if (code !== 0 && !closed) {
finalize(new Error(`ffmpeg exited with code ${code}`))
} else {
finalize()
}
})
ffmpegProcess.on("error", (err) => finalize(err))
},
cancel() {
if (closed) {
return
}
closed = true
ffmpegProcess.kill("SIGKILL")
},
})
}
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
try {
const song = (await getConvexClient().query(api.library.getSong, {
id: id as Id<"songs">,
}))!
const album = (await getConvexClient().query(api.library.getAlbum, {
id: song.album,
}))!
const artist = (await getConvexClient().query(api.library.getArtist, {
id: song.albumArtist,
}))!
const quality = request.nextUrl.searchParams.get("quality") as
| "low"
| "medium"
| "high"
| "lossless"
| null
const preferAtmos =
request.nextUrl.searchParams.get("preferAtmos") === "true"
let kbps = 0
if (quality === "low") {
kbps = 64
} else if (quality === "medium") {
kbps = 128
} else if (quality === "high") {
kbps = 256
}
let originalCodec = "lossless" in song.files ? "lossless" : "normal"
let transcodeNeeded = true
if (preferAtmos && "atmos" in song.files) {
originalCodec = "atmos"
transcodeNeeded = false
} else if (kbps === 0 && "lossless" in song.files) {
originalCodec = "lossless"
transcodeNeeded = false
} else if (kbps === 0) {
transcodeNeeded = false
}
const file = `${DATA_DIR}/${originalCodec}/${artist.name}/${album.name}/${song.files[originalCodec]}`
if (!transcodeNeeded) {
const data = await fs.readFile(file)
return new NextResponse(data, {
status: 200,
headers: {
"Content-Type": audioContentTypeForPath(file),
"Cache-Control": "no-cache",
},
})
}
const ffmpegArgs = [
"-nostdin",
"-i",
file,
"-c:a",
`${quality === "low" ? "libfdk_aac" : "aac"}`,
"-b:a",
`${kbps}k`,
"-f",
"adts",
"pipe:1",
]
try {
const ffmpegProcess = spawn("ffmpeg", ffmpegArgs)
const stream = ffmpegToReadableStream(ffmpegProcess)
return new NextResponse(stream, {
status: 200,
headers: {
"Content-Type": "audio/aac",
"Transfer-Encoding": "chunked",
"Cache-Control": "no-cache",
},
})
} catch {
return new Response("Server Error", { status: 500 })
}
} catch {
return new Response("Not found", { status: 404 })
}
}
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

-51
View File
@@ -1,51 +0,0 @@
import { Geist, Geist_Mono, Inter } from "next/font/google"
import "./globals.css"
import { ConvexAuthNextjsServerProvider } from "@convex-dev/auth/nextjs/server"
import { ConvexClientProvider } from "@/components/convex-client-provider"
import { ThemeProvider } from "@/components/theme-provider"
import { cn } from "@/lib/utils"
import { Toaster } from "@/components/ui/sonner"
import type { Metadata } from "next"
const inter = Inter({ subsets: ["latin"], variable: "--font-sans" })
const fontMono = Geist_Mono({
subsets: ["latin"],
variable: "--font-mono",
})
export const metadata: Metadata = {
title: "oTunes",
description: "Our Music",
}
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html
lang="en"
suppressHydrationWarning
className={cn(
"antialiased",
fontMono.variable,
"font-sans",
inter.variable
)}
>
<body className={"overflow-x-hidden"}>
<ConvexAuthNextjsServerProvider>
<ConvexClientProvider>
<ThemeProvider>
{children}
<Toaster />
</ThemeProvider>
</ConvexClientProvider>
</ConvexAuthNextjsServerProvider>
</body>
</html>
)
}
+7
View File
@@ -0,0 +1,7 @@
ios/
android/
# @generated expo-cli sync-2b81b286409207a5da26e14c78851eb30d8ccbdb
# The following patterns were generated by expo-cli
expo-env.d.ts
# @end expo-cli
+83
View File
@@ -0,0 +1,83 @@
{
"expo": {
"name": "oTunes",
"slug": "otunes",
"version": "0.0.1",
"orientation": "portrait",
"scheme": "otunes",
"userInterfaceStyle": "automatic",
"icon": "./assets/icon.png",
"ios": {
"icon": "./assets/oTunes.icon",
"supportsTablet": true,
"bundleIdentifier": "com.abunchofknowitalls.otunes",
"infoPlist": {
"ITSAppUsesNonExemptEncryption": false
}
},
"android": {
"package": "com.abunchofknowitalls.otunes",
"predictiveBackGestureEnabled": false,
"permissions": [
"android.permission.MODIFY_AUDIO_SETTINGS",
"android.permission.FOREGROUND_SERVICE",
"android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"
],
"adaptiveIcon": {
"monochromeImage": "./assets/android-icon-monochrome.png",
"foregroundImage": "./assets/android-icon-foreground.png",
"backgroundColor": "#C60322"
}
},
"plugins": [
"expo-router",
"expo-secure-store",
[
"expo-audio",
{
"enableBackgroundPlayback": true
}
],
"expo-sharing",
"expo-font",
"expo-asset",
[
"expo-splash-screen",
{
"ios": {
"backgroundColor": "#ffffff",
"image": "./assets/ios-icon.png",
"dark": {
"image": "./assets/ios-icon-dark.png",
"backgroundColor": "#000000"
},
"imageWidth": 200
},
"android": {
"backgroundColor": "#ffffff",
"image": "./assets/icon.png",
"dark": {
"image": "./assets/icon-dark.png",
"backgroundColor": "#000000"
},
"imageWidth": 200
}
}
],
"expo-image",
"expo-status-bar",
"./plugins/with-ios-pod-deployment-target.js",
"./plugins/with-ios-scene-lifecycle.js"
],
"experiments": {
"typedRoutes": true
},
"extra": {
"router": {},
"eas": {
"projectId": "98b83584-d757-4da0-9bec-050c8336643f"
}
},
"owner": "joshuafhiggins"
}
}
+121
View File
@@ -0,0 +1,121 @@
import { DarkTheme, DefaultTheme, ThemeProvider } from "expo-router"
import { NativeTabs } from "expo-router/unstable-native-tabs"
import { DynamicColorIOS, Platform, useColorScheme } from "react-native"
import { useMemo } from "react"
import { TabBottomAccessory } from "@/components/mini-player"
import { usePlaybackQueue } from "@/contexts/playback"
import { appleMusic, colors } from "@/lib/theme"
function useRouterTheme() {
const isDark = useColorScheme() === "dark"
return useMemo(() => {
const palette = isDark ? colors.dark : colors.light
const base = isDark ? DarkTheme : DefaultTheme
return {
...base,
colors: {
...base.colors,
background: palette.background,
card: palette.card,
text: palette.foreground,
border: palette.border,
primary: palette.primary,
},
}
}, [isDark])
}
function useNativeTabColors() {
const isDark = useColorScheme() === "dark"
const inactive = appleMusic.tabInactive
const iconColor =
Platform.OS === "ios"
? {
default: DynamicColorIOS({ dark: inactive, light: "#636366" }),
selected: appleMusic.pink,
}
: {
default: isDark ? inactive : "#636366",
selected: appleMusic.pink,
}
const labelColor =
Platform.OS === "ios"
? DynamicColorIOS({ dark: inactive, light: "#636366" })
: isDark
? inactive
: "#636366"
return {
isDark,
iconColor,
labelStyle: {
default: { color: labelColor, fontSize: 10 },
selected: {
color: appleMusic.pink,
fontSize: 10,
fontWeight: "600" as const,
},
},
blurEffect: isDark
? "systemChromeMaterialDark"
: "systemChromeMaterialLight",
backgroundColor:
Platform.OS === "ios"
? undefined
: isDark
? appleMusic.background
: colors.light.background,
}
}
export default function TabsLayout() {
const routerTheme = useRouterTheme()
const tabColors = useNativeTabColors()
const { currentSong, queueSongIds } = usePlaybackQueue()
const showBottomAccessory = Boolean(currentSong && queueSongIds.length > 0)
return (
<ThemeProvider value={routerTheme}>
<NativeTabs
blurEffect={
tabColors.blurEffect as
"systemChromeMaterialDark" | "systemChromeMaterialLight"
}
backgroundColor={tabColors.backgroundColor}
iconColor={tabColors.iconColor}
labelStyle={tabColors.labelStyle}
tintColor={appleMusic.pink}
minimizeBehavior="onScrollDown"
>
{showBottomAccessory ? (
<NativeTabs.BottomAccessory>
<TabBottomAccessory />
</NativeTabs.BottomAccessory>
) : null}
<NativeTabs.Trigger name="home" disableTransparentOnScrollEdge>
<NativeTabs.Trigger.Icon sf="house.fill" md="home" />
<NativeTabs.Trigger.Label>Home</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger name="library" disableTransparentOnScrollEdge>
<NativeTabs.Trigger.Icon
sf="music.note.square.stack.fill"
md="library_music"
/>
<NativeTabs.Trigger.Label>Library</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger name="search" disableTransparentOnScrollEdge>
<NativeTabs.Trigger.Icon sf="magnifyingglass" md="search" />
<NativeTabs.Trigger.Label>Search</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
</NativeTabs>
</ThemeProvider>
)
}
@@ -0,0 +1,33 @@
import { Stack } from "expo-router"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
export const unstable_settings = {
initialRouteName: "index",
}
export default function HomeLayout() {
const baseOptions = useStackScreenOptions({ title: "Home" })
return (
<Stack
initialRouteName="index"
screenOptions={({ route }) => ({
...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Home",
headerRight: route.name === "settings" ? undefined : () => <ProfileHeaderButton />,
unstable_headerRightItems:
route.name === "settings"
? undefined
: () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
],
})}
/>
)
}
@@ -0,0 +1,338 @@
import { Stack, useIsFocused, useLocalSearchParams } from "expo-router"
import { StatusBar } from "expo-status-bar"
import { memo, useCallback, useEffect, useMemo } from "react"
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
import { Ionicons } from "@expo/vector-icons"
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 { 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 { 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 { 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"
export default function AlbumScreen() {
const { id } = useLocalSearchParams<{ id: string }>()
const { push } = useAppNavigation()
const colors = useThemeColors()
const { config } = useServerConfig()
const album = useCachedQuery(
api.library.browseAlbumDetail,
typeof id === "string" ? { id: id as Id<"albums"> } : "skip"
)
const { playAlbum, playAlbumShuffled, playFromSong } = usePlaybackActions()
const { isAlbumFavorite, toggleAlbumFavorite, isSongFavorite } =
useFavorites()
const {
handleAlbumDetailAction,
handleAlbumTrackAction,
isAlbumFavorite: isAlbumFav,
} = useMediaMenuActions()
const isFocused = useIsFocused()
const coverUri =
config && typeof id === "string" ? albumCoverUrl(config.serverUrl, id) : ""
const { palette, settled } = useCoverPalette(
coverUri,
album ? album.cover != null : album === null ? false : undefined
)
const songIds = useMemo(
() => album?.tracks.map((track) => track.id as Id<"songs">) ?? [],
[album]
)
useEffect(() => {
if (album) {
rememberSongs(albumDetailSongs(album))
}
}, [album])
const renderTrack = useCallback(
({ item, index }: { item: BrowseAlbumTrack; index: number }) =>
album ? (
<AlbumTrackRow
track={item}
index={index}
album={album}
songIds={songIds}
palette={palette}
favorited={isSongFavorite(item.id)}
onPlay={playFromSong}
onAction={handleAlbumTrackAction}
/>
) : null,
[album, handleAlbumTrackAction, isSongFavorite, palette, playFromSong, songIds]
)
if (album === undefined || !config || !settled) {
return (
<>
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
}}
/>
<CollectionDetailSkeleton />
</>
)
}
if (album === null) {
return (
<>
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
}}
/>
<View style={[styles.empty, { backgroundColor: colors.background }]}>
<Text style={{ color: colors.mutedForeground }}>
Album not found.
</Text>
</View>
</>
)
}
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}
favorited={isAlbumFav(album.id)}
share={{ type: "album", albumId: album.id }}
onAction={(action) =>
void handleAlbumDetailAction(
album.id as Id<"albums">,
songIds,
action
)
}
>
<Pressable hitSlop={8}>
<Ionicons
name="ellipsis-horizontal"
size={22}
color={palette.foreground}
/>
</Pressable>
</MediaActionMenu>
),
}}
/>
<FlatList
{...longListProps}
data={album.tracks}
keyExtractor={(track) => track.id}
style={{ flex: 1, backgroundColor: palette.background }}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
indicatorStyle={palette.isDark ? "white" : "black"}
ListHeaderComponent={
<View style={styles.hero}>
<CoverImage
uri={coverUri}
hasCover={album.cover != null}
style={styles.cover}
/>
<Text style={[styles.title, { color: palette.foreground }]}>
{album.title}
</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
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() => void playAlbumShuffled(album.id, songIds)}
style={[styles.iconAction, { backgroundColor: palette.surface }]}
>
<Ionicons
name="shuffle"
size={24}
color={palette.foreground}
/>
</Pressable>
</View>
</View>
}
renderItem={renderTrack}
/>
</>
)
}
const AlbumTrackRow = memo(function AlbumTrackRow({
track,
index,
album,
songIds,
palette,
favorited,
onPlay,
onAction,
}: {
track: BrowseAlbumTrack
index: 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, { borderBottomColor: palette.divider }]}
onPress={() => void onPlay(track.id as Id<"songs">, songIds)}
>
<Text
style={[styles.trackNumber, { color: palette.secondaryForeground }]}
>
{track.track || index + 1}
</Text>
<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>
</Pressable>
</MediaContextMenu>
)
})
const styles = StyleSheet.create({
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
hero: {
alignItems: "center",
padding: spacing.lg,
gap: spacing.sm,
},
cover: {
width: 220,
height: 220,
borderRadius: radius.lg,
},
title: { fontSize: 24, fontWeight: "800", textAlign: "center" },
artist: { fontSize: 16, fontWeight: "600" },
actions: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: spacing.sm,
marginTop: spacing.sm,
},
playButton: { borderRadius: 999, minWidth: 160 },
iconAction: {
width: 44,
height: 44,
borderRadius: 22,
alignItems: "center",
justifyContent: "center",
},
trackRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
minHeight: 60,
paddingHorizontal: spacing.lg,
paddingVertical: 12,
borderBottomWidth: StyleSheet.hairlineWidth,
},
trackNumber: { width: 24, textAlign: "center" },
trackMeta: { flex: 1, minWidth: 0 },
trackTitle: { fontSize: 16, fontWeight: "500" },
})
@@ -0,0 +1,172 @@
import { Stack, useLocalSearchParams } from "expo-router"
import { Pressable, StyleSheet, Text, View } from "react-native"
import { Ionicons } from "@expo/vector-icons"
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 { 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"
import { artistCoverUrl } from "@/lib/urls"
import { spacing, useThemeColors } from "@/lib/theme"
export default function ArtistScreen() {
const { id } = useLocalSearchParams<{ id: string }>()
const colors = useThemeColors()
const { config } = useServerConfig()
const data = useCachedQuery(
api.library.browseArtistDetail,
typeof id === "string" ? { id: id as Id<"artists"> } : "skip"
)
const { playArtist, playArtistShuffled } = usePlaybackActions()
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
const { handleArtistAction, isArtistFavorite: isArtistFav } =
useMediaMenuActions()
if (data === undefined || !config) {
return (
<>
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
}}
/>
<CollectionDetailSkeleton round />
</>
)
}
if (data === null) {
return (
<>
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
}}
/>
<View style={[styles.empty, { backgroundColor: colors.background }]}>
<Text style={{ color: colors.mutedForeground }}>
Artist not found.
</Text>
</View>
</>
)
}
return (
<>
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
headerRight: () => (
<MediaActionMenu
selectedCount={data.albums.length}
favorited={isArtistFav(data.artist.id)}
share={{ type: "artist", artistId: data.artist.id }}
onAction={(action) =>
void handleArtistAction(data.artist, action)
}
>
<Pressable hitSlop={8}>
<Ionicons
name="ellipsis-horizontal"
size={22}
color={colors.foreground}
/>
</Pressable>
</MediaActionMenu>
),
}}
/>
<MediaGridList
content={data.albums}
paddingBottom={contentBottomInset}
contentInset={false}
ListHeaderComponent={
<View style={styles.hero}>
<CoverImage
uri={artistCoverUrl(config.serverUrl, data.artist.id)}
hasCover={data.artist.photo != null}
style={styles.avatar}
/>
<Text style={[styles.title, { color: colors.foreground }]}>
{data.artist.name}
</Text>
<View style={styles.actions}>
<Pressable
onPress={() => void toggleArtistFavorite(data.artist.id)}
hitSlop={8}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
>
<Ionicons
name={
isArtistFavorite(data.artist.id) ? "star" : "star-outline"
}
size={24}
color={
isArtistFavorite(data.artist.id)
? colors.primary
: colors.foreground
}
/>
</Pressable>
<Button
title="Play"
icon="play"
onPress={() => void playArtist(data.artist.id)}
style={styles.playButton}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() => void playArtistShuffled(data.artist.id)}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
</View>
</View>
}
/>
</>
)
}
const styles = StyleSheet.create({
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
hero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm },
avatar: {
width: 180,
height: 180,
borderRadius: 90,
},
title: { fontSize: 28, fontWeight: "800", textAlign: "center" },
actions: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: spacing.sm,
marginTop: spacing.sm,
},
playButton: { borderRadius: 999, minWidth: 160 },
iconAction: {
width: 44,
height: 44,
borderRadius: 22,
alignItems: "center",
justifyContent: "center",
},
})
@@ -0,0 +1,74 @@
import { Stack } from "expo-router"
import { useCallback } from "react"
import { MediaGridList } from "@/components/media-cards"
import { MediaGridSkeleton } from "@/components/skeletons"
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"
const PAGE_SIZE = 50
export default function AlbumsScreen() {
const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch()
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
api.library.browseAlbumsPaginated,
{},
{ initialNumItems: PAGE_SIZE }
)
const searchResults = useCachedQuery(
api.library.searchLibrary,
searchQuery ? { query: searchQuery } : "skip"
)
const albums = searchQuery
? searchResults?.albums
: status === "LoadingFirstPage" && !isCached
? undefined
: results
const handleChangeText = useCallback(
(event: { nativeEvent: { text: string } }) => {
onQueryChange(event.nativeEvent.text)
},
[onQueryChange]
)
const searchBar = (
<Stack.Screen
options={{
headerSearchBarOptions: {
placeholder: "Search",
onChangeText: handleChangeText,
onSearchButtonPress: onSearchSubmit,
},
}}
/>
)
if (albums === undefined) {
return (
<>
{searchBar}
<MediaGridSkeleton />
</>
)
}
return (
<>
{searchBar}
<MediaGridList
content={albums}
paddingBottom={contentBottomInset}
onEndReached={() => {
if (!searchQuery && status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
/>
</>
)
}
@@ -0,0 +1,185 @@
import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router"
import { memo, useCallback } from "react"
import {
FlatList,
Pressable,
StyleSheet,
Text,
type ListRenderItemInfo,
} from "react-native"
import {
MediaContextMenu,
type MediaAction,
} from "@/components/media-context-menu"
import { CoverImage } from "@/components/cover-image"
import { ArtistListSkeleton } from "@/components/skeletons"
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"
const PAGE_SIZE = 50
export default function ArtistsScreen() {
const { push } = useAppNavigation()
const colors = useThemeColors()
const { config } = useServerConfig()
const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch()
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
api.library.browseArtistsPaginated,
{},
{ initialNumItems: PAGE_SIZE }
)
const searchResults = useCachedQuery(
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 handleChangeText = useCallback(
(event: { nativeEvent: { text: string } }) => {
onQueryChange(event.nativeEvent.text)
},
[onQueryChange]
)
const searchBar = (
<Stack.Screen
options={{
headerSearchBarOptions: {
placeholder: "Search",
onChangeText: handleChangeText,
onSearchButtonPress: onSearchSubmit,
},
}}
/>
)
if (artists === undefined || !config) {
return (
<>
{searchBar}
<ArtistListSkeleton />
</>
)
}
return (
<>
{searchBar}
<FlatList
{...longListProps}
data={artists}
keyExtractor={artistKey}
renderItem={renderItem}
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={styles.listContent}
contentInsetAdjustmentBehavior="automatic"
onEndReached={() => {
if (!searchQuery && status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
onEndReachedThreshold={0.5}
/>
</>
)
}
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",
gap: spacing.md,
paddingHorizontal: spacing.lg,
paddingVertical: spacing.md,
borderBottomWidth: StyleSheet.hairlineWidth,
},
avatar: {
width: 44,
height: 44,
borderRadius: 22,
},
name: { flex: 1, fontSize: 16, fontWeight: "600" },
})
@@ -0,0 +1,69 @@
import { Pressable } from "react-native"
import { MediaGridList } from "@/components/media-cards"
import { MediaGridSkeleton } from "@/components/skeletons"
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"
import { Stack } from "expo-router"
import { SymbolView } from "expo-symbols"
import { useAddToPlaylist } from "@/contexts/add-to-playlist"
export default function PlaylistsTabScreen() {
const colors = useThemeColors()
const playlists = useCachedQuery(api.playlists.listAllPlaylists)
const { openCreatePlaylist } = useAddToPlaylist()
if (playlists === undefined) {
return (
<>
<Stack.Screen
options={{
title: "Playlists",
headerLargeTitle: true,
headerRight: () => (
<Pressable
onPress={openCreatePlaylist}
accessibilityLabel="New playlist"
hitSlop={4}
>
<SymbolView
name="plus"
size={24}
tintColor={colors.foreground}
/>
</Pressable>
),
}}
/>
<MediaGridSkeleton />
</>
)
}
return (
<>
<Stack.Screen
options={{
title: "Playlists",
headerLargeTitle: true,
headerRight: () => (
<Pressable
onPress={openCreatePlaylist}
accessibilityLabel="New playlist"
hitSlop={4}
>
<SymbolView name="plus" size={24} tintColor={colors.foreground} />
</Pressable>
),
}}
/>
<MediaGridList
content={playlists}
paddingBottom={tabContentBottomInset}
/>
</>
)
}
@@ -0,0 +1,121 @@
import { Stack } from "expo-router"
import { useCallback, useState } from "react"
import { FlatList, StyleSheet, type ListRenderItemInfo } from "react-native"
import type { MediaAction } from "@/components/media-context-menu"
import { contentBottomInset, SongListRow } from "@/components/player"
import { SongListSkeleton } from "@/components/skeletons"
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"
const PAGE_SIZE = 50
export default function SongsScreen() {
const { playFromLibrarySong } = usePlaybackActions()
const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions()
const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch()
const [sortKey, setSortKey] = useState<"title" | "artist" | "album">("title")
const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc")
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
api.library.browseSongsPaginated,
{ sortKey, sortDirection },
{ initialNumItems: PAGE_SIZE }
)
const searchResults = useCachedQuery(
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 handleChangeText = useCallback(
(event: { nativeEvent: { text: string } }) => {
onQueryChange(event.nativeEvent.text)
},
[onQueryChange]
)
const searchBar = (
<Stack.Screen
options={{
headerSearchBarOptions: {
placeholder: "Search",
onChangeText: handleChangeText,
onSearchButtonPress: onSearchSubmit,
},
}}
/>
)
if (songs === undefined) {
return (
<>
{searchBar}
<SongListSkeleton />
</>
)
}
return (
<>
{searchBar}
<FlatList
{...longListProps}
data={songs}
keyExtractor={songKey}
renderItem={renderItem}
contentContainerStyle={styles.listContent}
contentInsetAdjustmentBehavior="automatic"
onEndReached={() => {
if (!searchQuery && status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
onEndReachedThreshold={0.5}
/>
</>
)
}
function songKey(song: BrowseSong) {
return song.id
}
const styles = StyleSheet.create({
listContent: { paddingBottom: contentBottomInset },
})
@@ -0,0 +1,78 @@
import { memo } from "react"
import { ScrollView, StyleSheet } from "react-native"
import { ContentCarousel } from "@/components/media-cards"
import { HomeSkeleton } from "@/components/skeletons"
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"
const CAROUSEL_ITEM_LIMIT = 10
const HomeCarousels = memo(function HomeCarousels({
recentlyAdded,
recentlyPlayed,
}: {
recentlyAdded: BrowseAlbum[]
recentlyPlayed: (BrowseAlbum | PlaylistSummary)[]
}) {
return (
<>
{recentlyPlayed.length > 0 ? (
<ContentCarousel
title="Recently Played"
href="/recently-played"
content={recentlyPlayed}
/>
) : null}
<ContentCarousel
title="Recently Added"
href="/recently-added"
content={recentlyAdded}
/>
</>
)
})
export default function HomeScreen() {
const colors = useThemeColors()
const recentlyAdded = useCachedPaginatedQuery(
api.library.browseRecentlyAddedPaginated,
{},
{ initialNumItems: CAROUSEL_ITEM_LIMIT }
)
const recentlyPlayed = useCachedPaginatedQuery(
api.library.browseRecentlyPlayedPaginated,
{},
{ initialNumItems: CAROUSEL_ITEM_LIMIT }
)
const isLoading = [recentlyAdded, recentlyPlayed].some(
(result) => result.status === "LoadingFirstPage" && !result.isCached
)
if (isLoading) {
return <HomeSkeleton />
}
const added = recentlyAdded.results.slice(0, CAROUSEL_ITEM_LIMIT)
const played = recentlyPlayed.results.slice(0, CAROUSEL_ITEM_LIMIT)
return (
<ScrollView
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={[styles.content, { paddingBottom: tabContentBottomInset }]}
contentInsetAdjustmentBehavior="automatic"
>
<HomeCarousels recentlyAdded={added} recentlyPlayed={played} />
</ScrollView>
)
}
const styles = StyleSheet.create({
content: {
padding: spacing.lg,
gap: spacing.xl,
},
})
@@ -0,0 +1,560 @@
import { useMutation } from "convex/react"
import { memo, useCallback, useEffect, useMemo } from "react"
import { Stack, useIsFocused, useLocalSearchParams, useRouter } from "expo-router"
import { StatusBar } from "expo-status-bar"
import {
FlatList,
Platform,
Pressable,
StyleSheet,
Text,
View,
type ListRenderItemInfo,
} from "react-native"
import ReanimatedSwipeable from "react-native-gesture-handler/ReanimatedSwipeable"
import { Ionicons } from "@expo/vector-icons"
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 { 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 { 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 { 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",
]
export default function PlaylistScreen() {
const { id } = useLocalSearchParams<{ id: string }>()
const colors = useThemeColors()
const { config } = useServerConfig()
const playlistId = typeof id === "string" ? (id as Id<"playlists">) : null
const playlist = useCachedQuery(
api.playlists.browsePlaylistDetail,
playlistId
? {
id: playlistId,
includeSongs: false,
}
: "skip"
)
const {
results: songs,
status,
loadMore,
isCached,
} = useCachedPaginatedQuery(
api.playlists.browsePlaylistSongsPaginated,
playlistId ? { id: playlistId } : "skip",
{ initialNumItems: PAGE_SIZE }
)
const allSongIds = useCachedQuery(
api.playlists.getPlaylistSongIds,
playlistId ? { playlistId } : "skip"
)
const coverUri =
config && playlistId
? playlistCoverUrl(config.serverUrl, playlist?.id ?? playlistId)
: ""
const { palette, settled } = useCoverPalette(
coverUri,
playlist ? playlist.cover != null : playlist === null ? false : undefined
)
useEffect(() => {
rememberSongs(songs)
}, [songs])
if (
playlist === undefined ||
(status === "LoadingFirstPage" && !isCached) ||
!config ||
!settled
) {
return (
<>
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
}}
/>
<CollectionDetailSkeleton />
</>
)
}
if (playlist === null) {
return (
<>
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
}}
/>
<View style={[styles.empty, { backgroundColor: colors.background }]}>
<Text style={{ color: colors.mutedForeground }}>
Playlist not found.
</Text>
</View>
</>
)
}
return (
<PlaylistContent
playlist={playlist}
songs={songs}
allSongIds={allSongIds}
coverUri={coverUri}
palette={palette}
onEndReached={() => {
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
/>
)
}
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)
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
try {
if (isSubscribed) {
await unsubscribe({ playlistId })
showSuccess("Unsubscribed")
} else {
await subscribe({ playlistId })
showSuccess("Subscribed")
}
} catch (error) {
showError(
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"
)
}
}
function handlePlaylistMenuAction(action: MediaAction) {
if (action === "delete-playlist") {
void handleDelete()
return
}
void handlePlaylistDetailAction(songIds, action)
}
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
song={song}
favorited={isSongFavorite(song.id)}
removable={canEdit}
palette={palette}
swipeGroup={swipeGroup}
onPlay={handlePlaySong}
onAction={handleSongMenuAction}
onRemove={handleRemoveSong}
/>
),
[
canEdit,
handlePlaySong,
handleRemoveSong,
handleSongMenuAction,
isSongFavorite,
palette,
swipeGroup,
]
)
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}
/>
}
/>
</>
)
}
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}
onPlay={onPlay}
onAction={onAction}
/>
)
if (!removable) {
return row
}
if (Platform.OS === "ios") {
return (
<SwipeToRemoveRow
group={swipeGroup}
backgroundColor={palette.background}
actionAccessibilityLabel={`Remove ${song.title} from playlist`}
onRemove={handleRemove}
>
{row}
</SwipeToRemoveRow>
)
}
return (
<ReanimatedSwipeable
friction={2}
rightThreshold={56}
overshootRight={false}
enableTrackpadTwoFingerGesture
containerStyle={{ backgroundColor: colors.destructive }}
childrenContainerStyle={{ backgroundColor: palette.background }}
renderRightActions={(_progress, _translation, swipeable) => (
<Pressable
accessibilityRole="button"
accessibilityLabel={`Remove ${song.title} from playlist`}
onPress={() => {
swipeable.close()
void handleRemove()
}}
style={[styles.removeAction, { backgroundColor: colors.destructive }]}
>
<Ionicons name="trash" size={22} color={colors.primaryForeground} />
<Text
style={[
styles.removeActionText,
{ color: colors.primaryForeground },
]}
>
Remove
</Text>
</Pressable>
)}
>
{row}
</ReanimatedSwipeable>
)
})
const PlaylistHero = memo(function PlaylistHero({
coverUri,
hasCover,
title,
ownerName,
palette,
isSubscribed,
showSubscribe = false,
onSubscribeToggle,
onPlay,
onShuffle,
}: {
coverUri: string
hasCover: boolean
title: string
ownerName: string
palette: CoverPalette
isSubscribed?: boolean
showSubscribe?: boolean
onSubscribeToggle?: () => void
onPlay: () => void
onShuffle: () => void
}) {
return (
<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,
}}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={onShuffle}
style={[styles.iconAction, { backgroundColor: palette.surface }]}
>
<Ionicons name="shuffle" size={24} color={palette.foreground} />
</Pressable>
</View>
</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,
},
title: { fontSize: 24, fontWeight: "800", textAlign: "center" },
actions: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: spacing.sm,
marginTop: spacing.sm,
},
playButton: { borderRadius: 999, minWidth: 160 },
iconAction: {
width: 44,
height: 44,
borderRadius: 22,
alignItems: "center",
justifyContent: "center",
},
removeAction: {
width: 96,
alignItems: "center",
justifyContent: "center",
gap: spacing.xs,
},
removeActionText: {
fontSize: 12,
fontWeight: "600",
},
})
@@ -0,0 +1,220 @@
import { memo, useCallback, useEffect, useMemo } from "react"
import {
FlatList,
Pressable,
StyleSheet,
Text,
View,
type ListRenderItemInfo,
} from "react-native"
import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset, SongListRow } 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 { 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"
onPlay={handlePlaySong}
onAction={handleSongMenuAction}
/>
),
[handlePlaySong, handleSongMenuAction, isSongFavorite]
)
if (
favorites === undefined ||
(status === "LoadingFirstPage" && !isCached) ||
!config
) {
return (
<>
<Stack.Screen options={SCREEN_OPTIONS} />
<CollectionDetailSkeleton />
</>
)
}
if (favorites === null) {
return (
<>
<Stack.Screen options={SCREEN_OPTIONS} />
<View style={[styles.empty, { backgroundColor: colors.background }]}>
<Text style={{ color: colors.mutedForeground }}>
Sign in to view your favorites.
</Text>
</View>
</>
)
}
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)
}}
onEndReachedThreshold={0.5}
ListHeaderComponent={
<FavoritesHero
title={favorites.title}
onPlay={handlePlay}
onShuffle={handleShuffle}
/>
}
/>
</>
)
}
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 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>
)
})
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",
alignItems: "center",
justifyContent: "center",
gap: spacing.sm,
marginTop: spacing.sm,
},
playButton: { borderRadius: 999, minWidth: 160 },
iconAction: {
width: 44,
height: 44,
borderRadius: 22,
alignItems: "center",
justifyContent: "center",
},
})
+186
View File
@@ -0,0 +1,186 @@
import { Stack, useRouter } from "expo-router"
import { memo, useCallback, useMemo } from "react"
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
import { Button } 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 { spacing, useThemeColors } from "@/lib/theme"
/** `key` stays stable when earlier songs leave the queue, so rows are not remounted on skip. */
type QueueItem = { songId: Id<"songs">; queueIndex: number; key: string }
function queueItemKey(item: QueueItem) {
return item.key
}
const QueueRow = memo(function QueueRow({
songId,
queueIndex,
isLast,
isCurrent,
onSkipTo,
onMove,
}: Omit<QueueItem, "key"> & {
isLast: boolean
isCurrent: boolean
onSkipTo: (index: number) => void
onMove: (index: number, direction: -1 | 1) => void
}) {
const colors = useThemeColors()
const song = useSong(songId)
return (
<View>
{song ? (
<SongRow song={song} onPress={() => onSkipTo(queueIndex)} />
) : (
<SongRowSkeleton />
)}
<View style={styles.queueActions}>
<Pressable
disabled={queueIndex === 0}
onPress={() => onMove(queueIndex, -1)}
>
<Text style={{ color: colors.foreground }}>Move up</Text>
</Pressable>
<Pressable disabled={isLast} onPress={() => onMove(queueIndex, 1)}>
<Text style={{ color: colors.foreground }}>Move down</Text>
</Pressable>
{isCurrent ? (
<Text style={{ color: colors.primary, fontWeight: "700" }}>
Now playing
</Text>
) : null}
</View>
</View>
)
})
export default function QueueScreen() {
const router = useRouter()
const colors = useThemeColors()
const { queueSongIds, queueHistorySongIds } = usePlaybackQueue()
const { skipToQueueIndex, clearQueue, reorderQueue } = usePlaybackActions()
const historySongs = useSongs(queueHistorySongIds)
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 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]
)
function handleClearQueue() {
if (router.canGoBack()) {
router.back()
setTimeout(() => {
void clearQueue()
}, 0)
return
}
void clearQueue()
}
return (
<>
<Stack.Screen
options={{
headerRight: () =>
queueSongIds.length > 0 ? (
<Button
title="Clear"
variant="ghost"
onPress={handleClearQueue}
/>
) : null,
}}
/>
<FlatList
style={{ flex: 1, backgroundColor: colors.background }}
ListHeaderComponent={
<View>
<Text style={[styles.section, { color: colors.mutedForeground }]}>
Up Next
</Text>
{queueSongIds.length === 0 ? (
<Text style={[styles.empty, { color: colors.mutedForeground }]}>
Queue is empty
</Text>
) : null}
</View>
}
{...longListProps}
data={items}
keyExtractor={queueItemKey}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
renderItem={({ item }) => (
<QueueRow
songId={item.songId}
queueIndex={item.queueIndex}
isLast={item.queueIndex === queueSongIds.length - 1}
isCurrent={item.queueIndex === 0}
onSkipTo={skipToQueueIndex}
onMove={moveSong}
/>
)}
ListFooterComponent={
queueHistorySongIds.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}`}
/>
)
)}
</View>
) : null
}
/>
</>
)
}
const styles = StyleSheet.create({
section: {
paddingHorizontal: spacing.lg,
paddingTop: spacing.md,
fontSize: 12,
fontWeight: "700",
textTransform: "uppercase",
},
empty: { padding: spacing.lg },
queueActions: {
flexDirection: "row",
gap: spacing.lg,
paddingHorizontal: spacing.lg,
paddingBottom: spacing.sm,
},
history: { marginTop: spacing.lg },
})
@@ -0,0 +1,29 @@
import { MediaGridList } from "@/components/media-cards"
import { MediaGridSkeleton } from "@/components/skeletons"
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(
api.library.browseRecentlyAddedPaginated,
{},
{ initialNumItems: PAGE_SIZE }
)
if (status === "LoadingFirstPage" && !isCached) {
return <MediaGridSkeleton />
}
return (
<MediaGridList
content={results}
paddingBottom={contentBottomInset}
onEndReached={() => {
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
/>
)
}
@@ -0,0 +1,29 @@
import { MediaGridList } from "@/components/media-cards"
import { MediaGridSkeleton } from "@/components/skeletons"
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(
api.library.browseRecentlyPlayedPaginated,
{},
{ initialNumItems: PAGE_SIZE }
)
if (status === "LoadingFirstPage" && !isCached) {
return <MediaGridSkeleton />
}
return (
<MediaGridList
content={results}
paddingBottom={contentBottomInset}
onEndReached={() => {
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
/>
)
}
@@ -0,0 +1,887 @@
import { Ionicons } from "@expo/vector-icons"
import { useAction, useMutation, useQuery } from "convex/react"
import { Image } from "expo-image"
import * as ImagePicker from "expo-image-picker"
import { useRouter } from "expo-router"
import { useState } from "react"
import {
Pressable,
ScrollView,
StyleSheet,
Switch,
Text,
View,
} from "react-native"
import type { StyleProp, ViewStyle } from "react-native"
import { contentBottomInset } from "@/components/player"
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 { radius, spacing, useThemeColors } from "@/lib/theme"
import { showError, showSuccess } from "@/lib/toast"
import type { PlaybackQuality } from "@/lib/urls"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
type Section = "profile" | "quality" | "library" | "users"
type CurrentUser = {
_id: Id<"users">
name: string
image?: string
email: string
isAdmin?: boolean
playbackQuality?: PlaybackQuality
preferAtmos?: boolean
}
type AdminUser = {
_id: Id<"users">
name: string
email: string
isAdmin?: boolean
}
type SectionConfig = {
id: Section
label: string
icon: React.ComponentProps<typeof Ionicons>["name"]
admin?: boolean
}
const QUALITY_OPTIONS: {
value: PlaybackQuality
label: string
description: string
}[] = [
{ value: "low", label: "Low", description: "AAC 64kb/s" },
{ value: "medium", label: "Medium", description: "AAC 128kb/s" },
{ value: "high", label: "High", description: "AAC 256kb/s" },
{ value: "lossless", label: "Lossless", description: "ALAC or FLAC" },
]
const SECTIONS: SectionConfig[] = [
{ id: "profile", label: "Profile", icon: "person-circle-outline" },
{ id: "quality", label: "Playback", icon: "volume-high-outline" },
{ id: "library", label: "Library", icon: "library-outline", admin: true },
{ id: "users", label: "Users", icon: "people-outline", admin: true },
]
export default function SettingsScreen() {
const colors = useThemeColors()
const router = useRouter()
const user = useCachedQuery(api.auth.currentUser)
const { invalidateSession } = useInvalidateAuthSession()
const { clearServer } = useServerConfig()
const [section, setSection] = useState<Section>("profile")
const allUsers = useQuery(
api.users.listUsers,
user?.isAdmin === true && section === "users" ? {} : "skip"
)
if (!user) {
return <LoadingView />
}
const isAdmin = user.isAdmin === true
const visibleSections = SECTIONS.filter((item) => !item.admin || isAdmin)
async function handleSignOut() {
await signOutToSignIn(router, invalidateSession)
}
async function handleChangeServer() {
await invalidateSession()
await clearLocalData()
await clearServer()
router.replace("/server")
}
return (
<ScrollView
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={[
styles.container,
{ paddingBottom: contentBottomInset + spacing.xl },
]}
contentInsetAdjustmentBehavior="automatic"
>
<View style={[styles.pillGroup, { backgroundColor: colors.card }]}>
{visibleSections.map((item) => {
const selected = section === item.id
return (
<Pressable
key={item.id}
accessibilityLabel={item.label}
accessibilityRole="button"
accessibilityState={{ selected }}
onPress={() => setSection(item.id)}
style={[
styles.pill,
{ backgroundColor: selected ? colors.primary : "transparent" },
]}
>
<Ionicons
name={item.icon}
size={26}
color={
selected ? colors.primaryForeground : colors.mutedForeground
}
/>
</Pressable>
)
})}
</View>
{section === "profile" ? <ProfileSection user={user} /> : null}
{section === "quality" ? <QualitySection user={user} /> : null}
{section === "library" && isAdmin ? <LibrarySection /> : null}
{section === "users" && isAdmin && allUsers ? (
<UsersSection users={allUsers} currentUserId={user._id} />
) : null}
{section === "profile" ? (
<SessionSection
onChangeServer={() => void handleChangeServer()}
onSignOut={() => void handleSignOut()}
/>
) : null}
</ScrollView>
)
}
function ProfileSection({ user }: { user: CurrentUser }) {
const colors = useThemeColors()
const updateName = useMutation(api.users.updateProfileName)
const updateEmail = useMutation(api.users.updateProfileEmail)
const updateImage = useMutation(api.users.updateProfileImage)
const updatePassword = useAction(api.users.updateOwnPassword)
const [name, setName] = useState(user.name)
const [email, setEmail] = useState(user.email)
const [newPassword, setNewPassword] = useState("")
const [confirmPassword, setConfirmPassword] = useState("")
const [changingPassword, setChangingPassword] = useState(false)
async function pickImage() {
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ["images"],
quality: 0.8,
base64: true,
})
if (result.canceled || !result.assets[0]?.base64) return
const mime = result.assets[0].mimeType ?? "image/jpeg"
try {
await updateImage({
image: `data:${mime};base64,${result.assets[0].base64}`,
})
showSuccess("Profile photo updated")
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to update photo"
)
}
}
async function removeImage() {
try {
await updateImage({ image: null })
showSuccess("Profile photo removed")
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to remove photo"
)
}
}
async function handlePasswordChange() {
if (newPassword !== confirmPassword) {
showError("Passwords do not match")
return
}
setChangingPassword(true)
try {
await updatePassword({ newPassword })
setNewPassword("")
setConfirmPassword("")
showSuccess("Password updated")
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to update password"
)
} finally {
setChangingPassword(false)
}
}
return (
<>
<SettingsCard
title="Profile Photo"
subtitle="This is the avatar shown in the app header and shared spaces."
>
<View style={styles.photoRow}>
<ProfileAvatar user={user} size={76} />
<View style={styles.photoActions}>
<Button
title="Choose Photo"
variant="secondary"
icon="image-outline"
onPress={() => void pickImage()}
/>
{user.image ? (
<Button
title="Remove"
variant="ghost"
icon="trash-outline"
onPress={() => void removeImage()}
/>
) : null}
</View>
</View>
</SettingsCard>
<SettingsCard
title="Account Details"
subtitle="Keep your profile information up to date."
>
<Field label="Name">
<Input value={name} onChangeText={setName} placeholder="Name" />
</Field>
<Button
title="Save Name"
variant="secondary"
disabled={name.trim() === user.name}
onPress={() =>
void updateName({ name: name.trim() }).then(
() => showSuccess("Name updated"),
(error: Error) => showError(error.message)
)
}
/>
<View style={[styles.divider, { backgroundColor: colors.border }]} />
<Field label="Email">
<Input
value={email}
onChangeText={setEmail}
placeholder="Email"
autoCapitalize="none"
keyboardType="email-address"
/>
</Field>
<Button
title="Save Email"
variant="secondary"
disabled={email.trim() === user.email}
onPress={() =>
void updateEmail({ email: email.trim() }).then(
() => showSuccess("Email updated"),
(error: Error) => showError(error.message)
)
}
/>
</SettingsCard>
<SettingsCard
title="Password"
subtitle="Choose a new password for this account."
>
<Field label="New Password">
<Input
value={newPassword}
onChangeText={setNewPassword}
placeholder="New password"
secureTextEntry
/>
</Field>
<Field label="Confirm Password">
<Input
value={confirmPassword}
onChangeText={setConfirmPassword}
placeholder="Confirm password"
secureTextEntry
/>
</Field>
<Button
title="Update Password"
loading={changingPassword}
disabled={!newPassword || newPassword !== confirmPassword}
onPress={() => void handlePasswordChange()}
/>
</SettingsCard>
</>
)
}
function QualitySection({ user }: { user: CurrentUser }) {
const colors = useThemeColors()
const updateQuality = useMutation(api.users.updatePlaybackQuality)
const updateAtmos = useMutation(api.users.updatePreferAtmos)
const quality = user.playbackQuality ?? "medium"
return (
<>
<SettingsCard
title="Streaming Quality"
subtitle="Pick the default audio quality for playback."
>
{QUALITY_OPTIONS.map((option) => {
const selected = quality === option.value
return (
<Pressable
key={option.value}
accessibilityRole="button"
accessibilityState={{ selected }}
onPress={() =>
void updateQuality({ playbackQuality: option.value }).catch(
(error: Error) => showError(error.message)
)
}
style={[
styles.optionRow,
{
borderColor: selected ? colors.primary : colors.border,
backgroundColor: selected ? colors.muted : colors.card,
},
]}
>
<View style={styles.optionCopy}>
<Text
style={[styles.optionTitle, { color: colors.foreground }]}
>
{option.label}
</Text>
<Text style={{ color: colors.mutedForeground }}>
{option.description}
</Text>
</View>
{selected ? (
<Ionicons
name="checkmark-circle"
size={22}
color={colors.primary}
/>
) : null}
</Pressable>
)
})}
</SettingsCard>
<SettingsCard title="Spatial Audio">
<SwitchRow
title="Prefer Dolby Atmos"
subtitle="Use Atmos versions when they are available."
value={user.preferAtmos ?? false}
onValueChange={(checked) =>
void updateAtmos({ preferAtmos: checked }).catch((error: Error) =>
showError(error.message)
)
}
/>
</SettingsCard>
</>
)
}
function LibrarySection() {
const updateLibrary = useAction(api.actions.updateLibrary)
const cleanupHlsStreams = useAction(api.actions.adminCleanupHlsStreams)
const [updating, setUpdating] = useState(false)
const [cleaningHls, setCleaningHls] = useState(false)
return (
<SettingsCard
title="Library Maintenance"
subtitle="Run administrative jobs for the shared music library."
>
<Button
title="Update Library"
icon="refresh-outline"
loading={updating}
onPress={async () => {
setUpdating(true)
try {
await updateLibrary({})
showSuccess("Library updated")
} catch (error) {
showError(
error instanceof Error
? error.message
: "Failed to update library"
)
} finally {
setUpdating(false)
}
}}
/>
<Button
title="Clean HLS Streams"
variant="secondary"
icon="sparkles-outline"
loading={cleaningHls}
onPress={async () => {
setCleaningHls(true)
try {
const result = await cleanupHlsStreams({})
showSuccess(`Removed ${result.removed} idle HLS streams`)
} catch (error) {
showError(
error instanceof Error
? error.message
: "Failed to clean HLS streams"
)
} finally {
setCleaningHls(false)
}
}}
/>
</SettingsCard>
)
}
function UsersSection({
users,
currentUserId,
}: {
users: AdminUser[]
currentUserId: Id<"users">
}) {
const colors = useThemeColors()
const appSettings = useQuery(api.users.getAppSettings)
const setDisableCreation = useMutation(api.users.setDisableAccountCreation)
const setAdmin = useMutation(api.users.setUserAdmin)
const deleteUserMutation = useMutation(api.users.deleteUser)
return (
<>
<SettingsCard title="Sign Up">
<SwitchRow
title="Disable account creation"
subtitle="Stop people from registering themselves. Admins can still create accounts from the web app."
value={appSettings?.disableAccountCreation ?? false}
onValueChange={(checked) =>
void setDisableCreation({ disabled: checked }).catch(
(error: Error) => showError(error.message)
)
}
/>
</SettingsCard>
<SettingsCard
title="People"
subtitle="Manage who can access this server."
>
{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={[styles.userName, { color: colors.foreground }]}
numberOfLines={1}
>
{user.name}
</Text>
{user.isAdmin ? (
<View
style={[styles.badge, { backgroundColor: colors.muted }]}
>
<Text
style={[
styles.badgeText,
{ color: colors.mutedForeground },
]}
>
Admin
</Text>
</View>
) : null}
</View>
<Text
style={{ color: colors.mutedForeground }}
numberOfLines={1}
>
{user.email}
</Text>
</View>
</View>
{user._id !== currentUserId ? (
<View style={styles.userActions}>
<Button
title={user.isAdmin ? "Remove Admin" : "Make Admin"}
variant="secondary"
onPress={() =>
void setAdmin({
userId: user._id,
isAdmin: !user.isAdmin,
}).then(
() => showSuccess("Updated permissions"),
(error: Error) => showError(error.message)
)
}
style={styles.userActionButton}
/>
<Button
title="Delete"
variant="destructive"
onPress={() =>
void deleteUserMutation({ userId: user._id }).then(
() => showSuccess("User deleted"),
(error: Error) => showError(error.message)
)
}
style={styles.userActionButton}
/>
</View>
) : null}
</View>
))}
</SettingsCard>
</>
)
}
function SessionSection({
onChangeServer,
onSignOut,
}: {
onChangeServer: () => void
onSignOut: () => void
}) {
const colors = useThemeColors()
return (
<SettingsCard title="Session">
<ActionRow
icon="server-outline"
title="Change Server"
subtitle="Disconnect from this server and choose another."
onPress={onChangeServer}
/>
<View style={[styles.divider, { backgroundColor: colors.border }]} />
<ActionRow
icon="log-out-outline"
title="Sign Out"
subtitle="Return to the sign-in screen."
destructive
onPress={onSignOut}
/>
</SettingsCard>
)
}
function SettingsCard({
title,
subtitle,
children,
}: {
title: string
subtitle?: string
children: React.ReactNode
}) {
const colors = useThemeColors()
return (
<View style={[styles.card, { backgroundColor: colors.card }]}>
<View style={styles.cardHeader}>
<Text style={[styles.cardTitle, { color: colors.foreground }]}>
{title}
</Text>
{subtitle ? (
<Text
style={[styles.cardSubtitle, { color: colors.mutedForeground }]}
>
{subtitle}
</Text>
) : null}
</View>
{children}
</View>
)
}
function Field({
label,
children,
}: {
label: string
children: React.ReactNode
}) {
const colors = useThemeColors()
return (
<View style={styles.field}>
<Text style={[styles.fieldLabel, { color: colors.mutedForeground }]}>
{label}
</Text>
{children}
</View>
)
}
function SwitchRow({
title,
subtitle,
value,
onValueChange,
}: {
title: string
subtitle?: string
value: boolean
onValueChange: (checked: boolean) => void
}) {
const colors = useThemeColors()
return (
<View style={styles.switchRow}>
<View style={styles.optionCopy}>
<Text style={[styles.optionTitle, { color: colors.foreground }]}>
{title}
</Text>
{subtitle ? (
<Text style={{ color: colors.mutedForeground }}>{subtitle}</Text>
) : null}
</View>
<Switch value={value} onValueChange={onValueChange} />
</View>
)
}
function ActionRow({
icon,
title,
subtitle,
destructive,
onPress,
}: {
icon: React.ComponentProps<typeof Ionicons>["name"]
title: string
subtitle: string
destructive?: boolean
onPress: () => void
}) {
const colors = useThemeColors()
const tint = destructive ? colors.destructive : colors.foreground
return (
<Pressable
accessibilityRole="button"
onPress={onPress}
style={({ pressed }) => [
styles.actionRow,
{ opacity: pressed ? 0.75 : 1 },
]}
>
<View style={[styles.actionIcon, { backgroundColor: colors.muted }]}>
<Ionicons name={icon} size={20} color={tint} />
</View>
<View style={styles.optionCopy}>
<Text style={[styles.optionTitle, { color: tint }]}>{title}</Text>
<Text style={{ color: colors.mutedForeground }}>{subtitle}</Text>
</View>
<Ionicons
name="chevron-forward"
size={18}
color={colors.mutedForeground}
/>
</Pressable>
)
}
function ProfileAvatar({
user,
size,
style,
}: {
user: Pick<CurrentUser, "name" | "image">
size: number
style?: StyleProp<ViewStyle>
}) {
const colors = useThemeColors()
const avatarStyle = [
styles.avatar,
{
width: size,
height: size,
borderRadius: size / 2,
backgroundColor: colors.muted,
},
style,
]
if (user.image) {
return (
<View style={avatarStyle}>
<Image
source={{ uri: user.image }}
style={styles.avatarImage}
contentFit="cover"
/>
</View>
)
}
return (
<View style={avatarStyle}>
<Text
style={[
styles.avatarInitials,
{ color: colors.foreground, fontSize: size * 0.34 },
]}
>
{initialsFromName(user.name)}
</Text>
</View>
)
}
const styles = StyleSheet.create({
container: {
gap: spacing.lg,
paddingHorizontal: spacing.lg,
paddingTop: spacing.md,
},
badge: {
alignSelf: "flex-start",
borderRadius: radius.full,
paddingHorizontal: spacing.sm,
paddingVertical: 2,
},
badgeText: {
fontSize: 12,
fontWeight: "700",
},
pillGroup: {
borderRadius: radius.xl,
padding: spacing.xs,
flexDirection: "row",
gap: spacing.xs,
},
pill: {
flex: 1,
minHeight: 48,
borderRadius: radius.full,
alignItems: "center",
justifyContent: "center",
},
card: {
borderRadius: radius.xl,
padding: spacing.lg,
gap: spacing.md,
},
cardHeader: {
gap: spacing.xs,
},
cardTitle: {
fontSize: 18,
fontWeight: "800",
},
cardSubtitle: {
fontSize: 14,
lineHeight: 20,
},
photoRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.lg,
},
photoActions: {
flex: 1,
gap: spacing.sm,
},
field: {
gap: spacing.sm,
},
fieldLabel: {
fontSize: 13,
fontWeight: "700",
textTransform: "uppercase",
},
divider: {
height: StyleSheet.hairlineWidth,
},
optionRow: {
borderWidth: 1,
borderRadius: radius.lg,
padding: spacing.md,
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
},
optionCopy: {
flex: 1,
gap: 3,
},
optionTitle: {
fontSize: 16,
fontWeight: "700",
},
switchRow: {
minHeight: 56,
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
},
userRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
},
userCopy: {
flex: 1,
gap: 3,
},
userNameRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.sm,
},
userName: {
flexShrink: 1,
fontSize: 16,
fontWeight: "700",
},
userActions: {
flexDirection: "row",
gap: spacing.sm,
marginTop: spacing.md,
},
userActionButton: {
flex: 1,
},
actionRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
},
actionIcon: {
width: 36,
height: 36,
borderRadius: 18,
alignItems: "center",
justifyContent: "center",
},
avatar: {
alignItems: "center",
justifyContent: "center",
overflow: "hidden",
},
avatarImage: {
width: "100%",
height: "100%",
},
avatarInitials: {
fontWeight: "800",
},
})
@@ -0,0 +1,33 @@
import { Stack } from "expo-router"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
export const unstable_settings = {
initialRouteName: "index",
}
export default function LibraryLayout() {
const baseOptions = useStackScreenOptions({ title: "Library" })
return (
<Stack
initialRouteName="index"
screenOptions={({ route }) => ({
...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Library",
headerRight: route.name === "settings" ? undefined : () => <ProfileHeaderButton />,
unstable_headerRightItems:
route.name === "settings"
? undefined
: () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
],
})}
/>
)
}
@@ -0,0 +1 @@
export { default } from "../../home/album/[id]"
@@ -0,0 +1 @@
export { default } from "../../home/artist/[id]"
@@ -0,0 +1 @@
export { default } from "../../home/browse/albums"
@@ -0,0 +1 @@
export { default } from "../../home/browse/artists"
@@ -0,0 +1 @@
export { default } from "../../home/browse/playlists"
@@ -0,0 +1 @@
export { default } from "../../home/browse/songs"
@@ -0,0 +1,130 @@
import { useMemo } from "react"
import { Pressable, StyleSheet, Text, View } from "react-native"
import { SymbolView } from "expo-symbols"
import { Platform } from "react-native"
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 { useAppNavigation } from "@/lib/app-navigation"
import { api } from "@otunes/convex/_generated/api"
import { appleMusic, spacing, useThemeColors } from "@/lib/theme"
const PAGE_SIZE = 16
const links = [
{ title: "Playlists", href: "/browse/playlists", icon: "music.note.list" as const },
{ title: "Artists", href: "/browse/artists", icon: "mic.fill" as const },
{ title: "Albums", href: "/browse/albums", icon: "square.stack" as const },
{ title: "Songs", href: "/browse/songs", icon: "music.note" as const },
{ title: "Recently Played", href: "/recently-played", icon: "clock" as const },
{ title: "Favorites", href: "/playlist/favorites", icon: "star" as const },
]
function LibraryIcon({ name }: { name: (typeof links)[number]["icon"] }) {
if (Platform.OS === "ios") {
return (
<SymbolView
name={name}
size={22}
tintColor={appleMusic.pink}
weight="semibold"
/>
)
}
const ionMap: Record<string, keyof typeof Ionicons.glyphMap> = {
"music.note.list": "list",
"mic.fill": "mic",
"square.stack": "albums",
"music.note": "musical-notes",
clock: "time",
sparkles: "sparkles",
star: "star",
}
return <Ionicons name={ionMap[name] ?? "musical-notes"} size={22} color={appleMusic.pink} />
}
export default function LibraryScreen() {
const { push } = useAppNavigation()
const colors = useThemeColors()
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
api.library.browseRecentlyAddedPaginated,
{},
{ initialNumItems: PAGE_SIZE }
)
const listHeader = useMemo(
() => (
<View>
{links.map((link) => (
<Pressable
key={link.href}
style={[styles.row, { borderBottomColor: colors.border }]}
onPress={() => push(link.href)}
>
<LibraryIcon name={link.icon} />
<Text style={[styles.rowTitle, { color: colors.foreground }]}>{link.title}</Text>
<Ionicons name="chevron-forward" size={16} color={colors.mutedForeground} />
</Pressable>
))}
<Pressable
style={[styles.section, { paddingHorizontal: spacing.lg }]}
onPress={() => push("/recently-added")}
>
<Text style={[styles.sectionTitle, { color: colors.foreground }]}>
Recently Added
</Text>
</Pressable>
</View>
),
[colors.border, colors.foreground, colors.mutedForeground, push]
)
if (status === "LoadingFirstPage" && !isCached) {
return (
<View style={{ flex: 1, backgroundColor: colors.background }}>
{listHeader}
<MediaGridSkeleton contentInset={false} />
</View>
)
}
return (
<MediaGridList
content={results}
paddingBottom={tabContentBottomInset}
contentInset={false}
ListHeaderComponent={listHeader}
onEndReached={() => {
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
/>
)
}
const styles = StyleSheet.create({
row: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
paddingHorizontal: spacing.lg,
paddingVertical: 14,
borderBottomWidth: StyleSheet.hairlineWidth,
},
rowTitle: {
flex: 1,
fontSize: 20,
fontWeight: "400",
},
section: {
paddingTop: spacing.xl,
paddingBottom: spacing.md,
},
sectionTitle: {
fontSize: 22,
fontWeight: "700",
},
})
@@ -0,0 +1 @@
export { default } from "../../home/playlist/[id]"
@@ -0,0 +1 @@
export { default } from "../../home/playlist/favorites"
@@ -0,0 +1 @@
export { default } from "../home/queue"
@@ -0,0 +1 @@
export { default } from "../home/recently-added"
@@ -0,0 +1 @@
export { default } from "../home/recently-played"
@@ -0,0 +1 @@
export { default } from "../home/settings"
@@ -0,0 +1,33 @@
import { Stack } from "expo-router"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
export const unstable_settings = {
initialRouteName: "index",
}
export default function SearchLayout() {
const baseOptions = useStackScreenOptions({ title: "Search" })
return (
<Stack
initialRouteName="index"
screenOptions={({ route }) => ({
...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Search",
headerRight: route.name === "settings" ? undefined : () => <ProfileHeaderButton />,
unstable_headerRightItems:
route.name === "settings"
? undefined
: () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
],
})}
/>
)
}
@@ -0,0 +1 @@
export { default } from "../../home/album/[id]"
@@ -0,0 +1 @@
export { default } from "../../home/artist/[id]"
@@ -0,0 +1 @@
export { default } from "../../home/browse/albums"
@@ -0,0 +1 @@
export { default } from "../../home/browse/artists"
@@ -0,0 +1 @@
export { default } from "../../home/browse/songs"
@@ -0,0 +1,29 @@
import { Stack } from "expo-router"
import { useCallback } from "react"
import { SearchResults } from "@/components/search-results"
import { useDebouncedSearch } from "@/hooks/use-debounced-search"
export default function SearchScreen() {
const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch()
const handleChangeText = useCallback(
(event: { nativeEvent: { text: string } }) => {
onQueryChange(event.nativeEvent.text)
},
[onQueryChange]
)
return (
<>
<Stack.SearchBar
placeholder="Artists, Albums, Songs, and More"
onChangeText={handleChangeText}
onSearchButtonPress={onSearchSubmit}
autoCapitalize="none"
/>
<SearchResults searchQuery={searchQuery} />
</>
)
}
@@ -0,0 +1 @@
export { default } from "../../home/playlist/[id]"
@@ -0,0 +1 @@
export { default } from "../../home/playlist/favorites"
@@ -0,0 +1 @@
export { default } from "../home/queue"
@@ -0,0 +1 @@
export { default } from "../home/recently-added"
@@ -0,0 +1 @@
export { default } from "../home/recently-played"
@@ -0,0 +1 @@
export { default } from "../home/settings"
+103
View File
@@ -0,0 +1,103 @@
import { useConvexAuth as useLocalConvexAuth } from "@convex-dev/auth/react"
import {
useConvexAuth as useServerConvexAuth,
useConvexConnectionState,
} from "convex/react"
import { Redirect, Stack } from "expo-router"
import { Platform } from "react-native"
import { useEffect } from "react"
import { ConvexAuthRecovery } from "@/components/convex-auth-recovery"
import { LoadingView } from "@/components/ui/primitives"
import { AddToPlaylistProvider } from "@/contexts/add-to-playlist"
import { useInvalidateAuthSession } from "@/contexts/convex-auth-session"
import { FavoritesProvider } from "@/contexts/favorites"
import { PlaybackProvider } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { useStackScreenOptions } from "@/lib/navigation"
import { AppNavigationSync } from "@/lib/app-navigation"
const AUTH_HANDSHAKE_TIMEOUT_MS = 15_000
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
) {
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)
return () => clearTimeout(timer)
}, [
invalidateSession,
isWebSocketConnected,
localAuth?.isAuthenticated,
serverAuth?.isAuthenticated,
])
if (!config) {
return <Redirect href="/server" />
}
if (!localAuth || localAuth.isLoading) {
return <LoadingView />
}
if (!localAuth.isAuthenticated) {
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.
return (
<ConvexAuthRecovery onInvalidate={invalidateSession}>
<PlaybackProvider>
<AppNavigationSync />
<AddToPlaylistProvider>
<FavoritesProvider>
<Stack screenOptions={stackOptions}>
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
<Stack.Screen
name="settings"
options={{
headerShown: false,
presentation: Platform.OS === "ios" ? "modal" : "fullScreenModal",
animation: "slide_from_bottom",
gestureEnabled: true,
gestureDirection: "vertical",
}}
/>
<Stack.Screen
name="player"
options={{
headerShown: false,
presentation: Platform.OS === "ios" ? "modal" : "fullScreenModal",
animation: "slide_from_bottom",
gestureEnabled: true,
gestureDirection: "vertical",
fullScreenGestureEnabled: true,
}}
/>
</Stack>
</FavoritesProvider>
</AddToPlaylistProvider>
</PlaybackProvider>
</ConvexAuthRecovery>
)
}
+5
View File
@@ -0,0 +1,5 @@
import { Redirect } from "expo-router"
export default function AppIndex() {
return <Redirect href="/(app)/(tabs)/home" />
}
+383
View File
@@ -0,0 +1,383 @@
import { Ionicons } from "@expo/vector-icons"
import Slider from "@react-native-community/slider"
import { BlurView } from "expo-blur"
import { useRouter } from "expo-router"
import * as Haptics from "expo-haptics"
import { useEffect, useRef } from "react"
import {
Platform,
Pressable,
StyleSheet,
Text,
View,
} from "react-native"
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context"
import { StatusBar } from "expo-status-bar"
import { MediaActionMenu, type MediaAction } from "@/components/media-actions-sheet"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { CoverImage } from "@/components/cover-image"
import { useFavorites } from "@/contexts/favorites"
import { usePlayback } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { formatDuration, formatRemainingDuration } from "@/lib/format"
import { useAppNavigation } from "@/lib/app-navigation"
import { albumCoverUrl } from "@/lib/urls"
import { appleMusic, radius, spacing, usePlayerTheme } from "@/lib/theme"
export default function PlayerScreen() {
const router = useRouter()
const hadSongRef = useRef(false)
const { push } = useAppNavigation()
const insets = useSafeAreaInsets()
const player = usePlayerTheme()
const { config } = useServerConfig()
const { isSongFavorite, toggleSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions()
const {
currentSong,
isPlaying,
shuffleEnabled,
repeatEnabled,
currentTime,
duration,
volume,
queueSongIds,
setIsPlaying,
setVolume,
seekTo,
toggleShuffle,
cycleRepeat,
skipNext,
skipPrevious,
} = usePlayback()
const hasQueue = queueSongIds.length > 0
useEffect(() => {
if (hasQueue) {
hadSongRef.current = true
return
}
if (hadSongRef.current) {
router.back()
}
}, [hasQueue, router])
if (!currentSong || !config) {
return null
}
const hasCover = currentSong.album.cover != null
const coverUri = albumCoverUrl(config.serverUrl, currentSong.album.id)
const favorited = isSongFavorite(currentSong.id)
const bottomInset = Math.max(insets.bottom, spacing.md) + spacing.lg
const { colors } = player
async function handleAction(action: MediaAction) {
if (!currentSong) return
await handleSongAction(currentSong, action)
}
function togglePlayback() {
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light)
setIsPlaying(!isPlaying)
}
return (
<View style={[styles.root, { backgroundColor: colors.background }]}>
<StatusBar style={player.statusBar} />
<CoverImage
uri={coverUri}
hasCover={hasCover}
style={[styles.backgroundImage, { opacity: player.backgroundImageOpacity }]}
contentFit="cover"
blurRadius={60}
placeholderVariant="solid"
/>
{Platform.OS === "ios" ? (
<>
<BlurView intensity={90} tint={player.blurTint} style={StyleSheet.absoluteFill} />
<View style={[styles.scrim, { backgroundColor: player.scrim }]} />
</>
) : (
<View style={[StyleSheet.absoluteFill, { backgroundColor: player.androidScrim }]} />
)}
<SafeAreaView style={styles.safe} edges={["top"]}>
<Pressable
onPress={() => router.back()}
hitSlop={12}
style={styles.handleRow}
accessibilityRole="button"
accessibilityLabel="Close player"
>
<View style={[styles.handle, { backgroundColor: player.handle }]} />
</Pressable>
<View style={styles.upper}>
<View style={styles.artworkWrap}>
<CoverImage uri={coverUri} hasCover={hasCover} style={styles.artwork} />
</View>
</View>
<View style={[styles.controls, { paddingBottom: bottomInset }]}>
<View style={styles.metaRow}>
<View style={styles.metaText}>
<Text style={[styles.songTitle, { color: colors.foreground }]} numberOfLines={2}>
{currentSong.title}
</Text>
<Text style={[styles.artistName, { color: colors.mutedForeground }]} numberOfLines={1}>
{currentSong.artist.name}
</Text>
</View>
<View style={styles.metaActions}>
<Pressable
onPress={() => void toggleSongFavorite(currentSong.id)}
hitSlop={10}
style={[styles.circleButton, { backgroundColor: player.buttonSurface }]}
>
<Ionicons
name={favorited ? "star" : "star-outline"}
size={20}
color={favorited ? appleMusic.pink : colors.foreground}
/>
</Pressable>
<MediaActionMenu
favorited={favorited}
navigation={{
artist: { id: currentSong.artist.id },
album: { id: currentSong.album.id },
}}
includeActions={[
"play-next",
"play-last",
"shuffle",
"favorite",
"go-artist",
"go-album",
]}
onAction={handleAction}
>
<Pressable
hitSlop={10}
style={[styles.circleButton, { backgroundColor: player.buttonSurface }]}
>
<Ionicons name="ellipsis-horizontal" size={20} color={colors.foreground} />
</Pressable>
</MediaActionMenu>
</View>
</View>
<View style={styles.progressSection}>
<Slider
style={styles.slider}
minimumValue={0}
maximumValue={duration > 0 ? duration : 1}
value={Math.min(currentTime, duration || 0)}
onSlidingComplete={(value) => void seekTo(value)}
minimumTrackTintColor={colors.foreground}
maximumTrackTintColor={player.trackInactive}
thumbTintColor={colors.foreground}
/>
<View style={styles.timeRow}>
<Text style={[styles.time, { color: colors.mutedForeground }]}>
{formatDuration(currentTime)}
</Text>
<Text style={[styles.time, { color: colors.mutedForeground }]}>
{formatRemainingDuration(currentTime, duration)}
</Text>
</View>
</View>
<View style={styles.transport}>
<Pressable onPress={() => void skipPrevious()} hitSlop={12}>
<Ionicons name="play-back" size={36} color={colors.foreground} />
</Pressable>
<Pressable onPress={togglePlayback} style={styles.playButton} hitSlop={12}>
<Ionicons
name={isPlaying ? "pause" : "play"}
size={52}
color={colors.foreground}
/>
</Pressable>
<Pressable onPress={() => void skipNext()} hitSlop={12}>
<Ionicons name="play-forward" size={36} color={colors.foreground} />
</Pressable>
</View>
<View style={styles.volumeSection}>
<Ionicons name="volume-low" size={18} color={colors.mutedForeground} />
<Slider
style={styles.volumeSlider}
minimumValue={0}
maximumValue={1}
value={volume}
onValueChange={setVolume}
minimumTrackTintColor={colors.foreground}
maximumTrackTintColor={player.trackInactive}
thumbTintColor={colors.foreground}
/>
<Ionicons name="volume-high" size={18} color={colors.mutedForeground} />
</View>
<View style={styles.footer}>
<Pressable onPress={() => void toggleShuffle()} hitSlop={12} style={styles.footerButton}>
<Ionicons
name="shuffle"
size={22}
color={shuffleEnabled ? appleMusic.pink : colors.mutedForeground}
/>
</Pressable>
<Pressable onPress={() => void cycleRepeat()} hitSlop={12} style={styles.footerButton}>
<Ionicons
name={repeatEnabled === "once" ? "repeat-outline" : "repeat"}
size={22}
color={repeatEnabled !== "none" ? appleMusic.pink : colors.mutedForeground}
/>
</Pressable>
<Pressable
onPress={() => push("/queue")}
hitSlop={12}
style={styles.footerButton}
disabled={queueSongIds.length === 0}
>
<Ionicons name="list" size={22} color={colors.mutedForeground} />
</Pressable>
</View>
</View>
</SafeAreaView>
</View>
)
}
const styles = StyleSheet.create({
root: {
flex: 1,
},
backgroundImage: {
...StyleSheet.absoluteFill,
},
scrim: {
...StyleSheet.absoluteFill,
},
safe: {
flex: 1,
paddingHorizontal: spacing.xl,
},
handleRow: {
alignItems: "center",
paddingTop: spacing.sm,
paddingBottom: spacing.md,
},
handle: {
width: 36,
height: 5,
borderRadius: radius.full,
},
upper: {
flex: 1,
minHeight: 0,
justifyContent: "center",
},
artworkWrap: {
alignItems: "center",
justifyContent: "center",
paddingVertical: spacing.sm,
},
artwork: {
width: "100%",
maxWidth: 320,
aspectRatio: 1,
borderRadius: 12,
shadowColor: "#000",
shadowOpacity: 0.45,
shadowRadius: 24,
shadowOffset: { width: 0, height: 12 },
},
controls: {
flexShrink: 0,
},
metaRow: {
flexDirection: "row",
alignItems: "flex-start",
gap: spacing.md,
marginBottom: spacing.md,
},
metaText: {
flex: 1,
minWidth: 0,
},
songTitle: {
fontSize: 22,
fontWeight: "700",
lineHeight: 28,
},
artistName: {
fontSize: 18,
marginTop: spacing.xs,
},
metaActions: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
paddingTop: 4,
},
circleButton: {
width: 34,
height: 34,
borderRadius: 17,
alignItems: "center",
justifyContent: "center",
},
progressSection: {
marginBottom: spacing.lg,
},
slider: {
width: "100%",
height: 28,
},
timeRow: {
flexDirection: "row",
justifyContent: "space-between",
marginTop: -4,
},
time: {
fontSize: 13,
fontVariant: ["tabular-nums"],
},
transport: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: 48,
marginBottom: spacing.lg,
},
playButton: {
width: 72,
alignItems: "center",
},
volumeSection: {
flexDirection: "row",
alignItems: "center",
gap: spacing.sm,
marginBottom: spacing.md,
},
volumeSlider: {
flex: 1,
height: 28,
},
footer: {
flexDirection: "row",
justifyContent: "space-between",
paddingHorizontal: spacing.xxl,
paddingTop: spacing.sm,
},
footerButton: {
minWidth: 44,
minHeight: 44,
alignItems: "center",
justifyContent: "center",
},
})
+1
View File
@@ -0,0 +1 @@
export { default } from "./(tabs)/home/settings"
+28
View File
@@ -0,0 +1,28 @@
import { useConvexAuth } from "@convex-dev/auth/react"
import { Redirect, Stack } from "expo-router"
import { LoadingView } from "@/components/ui/primitives"
import { useServerConfig } from "@/contexts/server-config"
export default function AuthLayout() {
const { config, isLoading: serverLoading } = useServerConfig()
const auth = useConvexAuth()
if (serverLoading) {
return <LoadingView />
}
if (!config) {
return <Redirect href="/server" />
}
if (!auth || auth.isLoading) {
return <LoadingView />
}
if (auth.isAuthenticated) {
return <Redirect href="/(app)/(tabs)/home" />
}
return <Stack screenOptions={{ headerShown: false }} />
}
@@ -1,7 +1,5 @@
"use client"
import { AuthForm } from "@/components/auth-form"
export default function SignInPage() {
export default function SignInScreen() {
return <AuthForm flow="signIn" />
}
@@ -1,7 +1,5 @@
"use client"
import { AuthForm } from "@/components/auth-form"
export default function SignUpPage() {
export default function SignUpScreen() {
return <AuthForm flow="signUp" />
}
+32
View File
@@ -0,0 +1,32 @@
import { Stack } from "expo-router"
import { StatusBar } from "expo-status-bar"
import { useColorScheme } from "react-native"
import { GestureHandlerRootView } from "react-native-gesture-handler"
import { SafeAreaProvider } from "react-native-safe-area-context"
import { Toaster } from "@/components/ui/toaster"
import { ConvexAppProvider } from "@/contexts/convex-app"
import { ServerConfigProvider } from "@/contexts/server-config"
export default function RootLayout() {
const colorScheme = useColorScheme()
return (
<GestureHandlerRootView style={{ flex: 1 }}>
<SafeAreaProvider>
<ServerConfigProvider>
<ConvexAppProvider>
<StatusBar style={colorScheme === "dark" ? "light" : "dark"} />
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen name="index" />
<Stack.Screen name="server" />
<Stack.Screen name="(auth)" />
<Stack.Screen name="(app)" />
</Stack>
<Toaster />
</ConvexAppProvider>
</ServerConfigProvider>
</SafeAreaProvider>
</GestureHandlerRootView>
)
}
+19
View File
@@ -0,0 +1,19 @@
import { Redirect } from "expo-router"
import { LoadingView } from "@/components/ui/primitives"
import { useServerConfig } from "@/contexts/server-config"
import { AuthenticatedRedirect } from "@/components/authenticated-redirect"
export default function Index() {
const { config, isLoading } = useServerConfig()
if (isLoading) {
return <LoadingView />
}
if (!config) {
return <Redirect href="/server" />
}
return <AuthenticatedRedirect />
}
+117
View File
@@ -0,0 +1,117 @@
import { useRouter } from "expo-router"
import { useEffect, useState } from "react"
import {
KeyboardAvoidingView,
Platform,
StyleSheet,
Text,
View,
} from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { Button, Card, Input } from "@/components/ui/primitives"
import { useServerConfig } from "@/contexts/server-config"
import { spacing, useThemeColors } from "@/lib/theme"
export default function ServerScreen() {
const router = useRouter()
const colors = useThemeColors()
const { config, isLoading, setServerHostname } = useServerConfig()
const [hostname, setHostname] = useState("")
const [error, setError] = useState<string | null>(null)
const [submitting, setSubmitting] = useState(false)
useEffect(() => {
if (config?.hostname) {
setHostname(config.hostname)
}
}, [config?.hostname])
async function handleContinue() {
setError(null)
setSubmitting(true)
try {
const ok = await setServerHostname(hostname)
if (!ok) {
setError(
"Enter a valid server address, e.g. music.example.com, localhost:3000"
)
return
}
router.replace("/signin")
} catch {
setError(
"Could not save the server address. Check device storage and try again."
)
} finally {
setSubmitting(false)
}
}
if (isLoading) {
return null
}
return (
<SafeAreaView style={[styles.safe, { backgroundColor: colors.background }]}>
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : undefined}
style={styles.container}
>
<View style={styles.hero}>
<Text style={[styles.brand, { color: colors.foreground }]}>
oTunes
</Text>
<Text style={[styles.subtitle, { color: colors.mutedForeground }]}>
Connect to your oTunes server to start listening.
</Text>
</View>
<Card>
<Text style={[styles.label, { color: colors.foreground }]}>
Server address
</Text>
<Input
value={hostname}
onChangeText={setHostname}
placeholder="music.example.com"
autoCapitalize="none"
autoCorrect={false}
keyboardType="url"
returnKeyType="go"
onSubmitEditing={() => void handleContinue()}
/>
<Text style={[styles.hint, { color: colors.mutedForeground }]}>
Convex will connect to convex.{"{your hostname}"}
</Text>
{error ? (
<Text style={[styles.error, { color: colors.destructive }]}>
{error}
</Text>
) : null}
<Button
title="Continue"
loading={submitting}
onPress={() => void handleContinue()}
/>
</Card>
</KeyboardAvoidingView>
</SafeAreaView>
)
}
const styles = StyleSheet.create({
safe: { flex: 1 },
container: {
flex: 1,
justifyContent: "center",
padding: spacing.xl,
gap: spacing.xl,
},
hero: { gap: spacing.sm },
brand: { fontSize: 32, fontWeight: "800" },
subtitle: { fontSize: 16, lineHeight: 22 },
label: { fontSize: 14, fontWeight: "600" },
hint: { fontSize: 13 },
error: { fontSize: 14 },
})
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 963 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 8.8 KiB

After

Width:  |  Height:  |  Size: 8.8 KiB

@@ -1,6 +1,9 @@
{
"fill" : {
"automatic-gradient" : "display-p3:0.90526,0.26335,0.25253,1.00000"
"linear-gradient" : [
"display-p3:0.91748,0.28540,0.37329,1.00000",
"display-p3:0.91602,0.18677,0.24341,1.00000"
]
},
"groups" : [
{
@@ -13,7 +16,10 @@
{
"appearance" : "dark",
"value" : {
"automatic-gradient" : "display-p3:0.90526,0.26335,0.25253,1.00000"
"linear-gradient" : [
"display-p3:0.91357,0.19995,0.29419,1.00000",
"display-p3:0.82129,0.17517,0.18677,1.00000"
]
}
}
],
@@ -30,11 +36,11 @@
],
"shadow" : {
"kind" : "neutral",
"opacity" : 0.5
"opacity" : 0.6
},
"translucency" : {
"enabled" : true,
"value" : 0.5
"enabled" : false,
"value" : 0.2
}
}
],
+7
View File
@@ -0,0 +1,7 @@
module.exports = function (api) {
api.cache(true)
return {
presets: ["babel-preset-expo"],
plugins: ["react-native-reanimated/plugin"],
}
}
+199
View File
@@ -0,0 +1,199 @@
import { useAuthActions, useConvexAuth } from "@convex-dev/auth/react"
import { Link, useRouter } from "expo-router"
import { useQuery } from "convex/react"
import { useEffect, useState } from "react"
import {
KeyboardAvoidingView,
Platform,
Pressable,
StyleSheet,
Text,
View,
} from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { Button, Card, Input } from "@/components/ui/primitives"
import { useServerConfig } from "@/contexts/server-config"
import { api } from "@otunes/convex/_generated/api"
import { spacing, useThemeColors } from "@/lib/theme"
type AuthFlow = "signIn" | "signUp"
const copy: Record<
AuthFlow,
{
title: string
description: string
submit: string
switchPrompt: string
switchLabel: string
switchHref: "/signin" | "/signup"
}
> = {
signIn: {
title: "Welcome back",
description: "Sign in to your oTunes account to keep listening.",
submit: "Sign in",
switchPrompt: "Don't have an account?",
switchLabel: "Sign up",
switchHref: "/signup",
},
signUp: {
title: "Create your account",
description: "Sign up to start building your oTunes library.",
submit: "Sign up",
switchPrompt: "Already have an account?",
switchLabel: "Sign in",
switchHref: "/signin",
},
}
export function AuthForm({ flow }: { flow: AuthFlow }) {
const { signIn } = useAuthActions()
const auth = useConvexAuth()
const router = useRouter()
const colors = useThemeColors()
const { config } = useServerConfig()
const appSettings = useQuery(api.users.getAppSettings)
const [name, setName] = useState("")
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const [error, setError] = useState<string | null>(null)
const [submitting, setSubmitting] = useState(false)
useEffect(() => {
if (auth.isAuthenticated) {
router.replace("/(app)/(tabs)/home")
}
}, [auth.isAuthenticated, router])
const text = copy[flow]
const accountCreationDisabled = appSettings?.disableAccountCreation ?? false
const signupsDisabled = flow === "signUp" && accountCreationDisabled
const hideSignUpLink = flow === "signIn" && accountCreationDisabled
async function handleSubmit() {
if (signupsDisabled) return
setError(null)
setSubmitting(true)
const formData = new FormData()
formData.set("flow", flow)
formData.set("email", email.trim())
formData.set("password", password)
if (flow === "signUp") {
formData.set("name", name.trim())
}
try {
await signIn("password", formData)
} catch {
setError(
flow === "signIn"
? "Invalid email or password."
: "Could not create account. Try a different email."
)
setSubmitting(false)
}
}
return (
<SafeAreaView style={[styles.safe, { backgroundColor: colors.background }]}>
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : undefined}
style={styles.container}
>
<Card>
<View style={styles.header}>
<Text style={[styles.title, { color: colors.foreground }]}>{text.title}</Text>
<Text style={[styles.description, { color: colors.mutedForeground }]}>
{text.description}
</Text>
{config ? (
<Text style={[styles.server, { color: colors.mutedForeground }]}>
Server: {config.hostname}
</Text>
) : null}
</View>
{signupsDisabled ? (
<Text style={{ color: colors.mutedForeground }}>
New account registration is currently disabled. Contact an administrator if you need
access.
</Text>
) : (
<View style={styles.form}>
{flow === "signUp" ? (
<Input
value={name}
onChangeText={setName}
placeholder="Name"
autoComplete="name"
/>
) : null}
<Input
value={email}
onChangeText={setEmail}
placeholder="Email"
autoCapitalize="none"
keyboardType="email-address"
autoComplete="email"
/>
<Input
value={password}
onChangeText={setPassword}
placeholder="Password"
secureTextEntry
autoComplete={flow === "signIn" ? "current-password" : "new-password"}
/>
{error ? <Text style={{ color: colors.destructive }}>{error}</Text> : null}
<Button title={text.submit} loading={submitting} onPress={() => void handleSubmit()} />
{!hideSignUpLink ? (
<View style={styles.switchRow}>
<Text style={{ color: colors.mutedForeground }}>{text.switchPrompt} </Text>
<Link href={text.switchHref} asChild>
<Pressable>
<Text style={{ color: colors.foreground, fontWeight: "600" }}>
{text.switchLabel}
</Text>
</Pressable>
</Link>
</View>
) : null}
</View>
)}
</Card>
<Link href="/server" asChild>
<Pressable style={styles.changeServer}>
<Text style={{ color: colors.mutedForeground }}>Change server</Text>
</Pressable>
</Link>
</KeyboardAvoidingView>
</SafeAreaView>
)
}
const styles = StyleSheet.create({
safe: { flex: 1 },
container: {
flex: 1,
justifyContent: "center",
padding: spacing.xl,
gap: spacing.lg,
},
header: { gap: spacing.xs },
title: { fontSize: 22, fontWeight: "700" },
description: { fontSize: 14, lineHeight: 20 },
server: { fontSize: 13, marginTop: spacing.xs },
form: { gap: spacing.md },
switchRow: {
flexDirection: "row",
justifyContent: "center",
flexWrap: "wrap",
},
changeServer: {
alignItems: "center",
padding: spacing.md,
},
})
@@ -0,0 +1,24 @@
import { useConvexAuth } from "@convex-dev/auth/react"
import { Redirect } from "expo-router"
import { LoadingView } from "@/components/ui/primitives"
export function AuthenticatedRedirect() {
const auth = useConvexAuth()
if (!auth) {
return <LoadingView />
}
const { isLoading, isAuthenticated } = auth
if (isLoading) {
return <LoadingView />
}
if (!isAuthenticated) {
return <Redirect href="/signin" />
}
return <Redirect href="/(app)/(tabs)/home" />
}
@@ -0,0 +1,129 @@
import { useConvexAuth as useLocalConvexAuth } from "@convex-dev/auth/react"
import { useConvexAuth as useServerConvexAuth } from "convex/react"
import {
Component,
useCallback,
useEffect,
useRef,
type ErrorInfo,
type ReactNode,
} from "react"
import { LoadingView } from "@/components/ui/primitives"
import {
isConvexAuthError,
shouldInvalidateAuthSession,
} from "@/lib/auth-errors"
type ConvexAuthRecoveryProps = {
children: ReactNode
onInvalidate: () => Promise<void>
}
type ConvexAuthErrorBoundaryProps = {
children: ReactNode
sessionEstablished: boolean
onAuthError: () => void
}
type ConvexAuthErrorBoundaryState = {
error: Error | null
}
class ConvexAuthErrorBoundary extends Component<
ConvexAuthErrorBoundaryProps,
ConvexAuthErrorBoundaryState
> {
state: ConvexAuthErrorBoundaryState = { error: null }
static getDerivedStateFromError(error: Error): ConvexAuthErrorBoundaryState {
return { error }
}
componentDidCatch(error: Error, _errorInfo: ErrorInfo) {
if (shouldInvalidateAuthSession(error, this.props.sessionEstablished)) {
this.props.onAuthError()
}
}
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)) {
return <LoadingView />
}
throw error
}
return this.props.children
}
}
export function ConvexAuthRecovery({ children, onInvalidate }: ConvexAuthRecoveryProps) {
const localAuth = useLocalConvexAuth()
const serverAuth = useServerConvexAuth()
const hadServerAuthRef = useRef(false)
const invalidatingRef = useRef(false)
if (serverAuth?.isAuthenticated) {
hadServerAuthRef.current = true
}
const invalidateOnce = useCallback(async () => {
if (invalidatingRef.current) {
return
}
invalidatingRef.current = true
try {
await onInvalidate()
} catch {
invalidatingRef.current = false
}
}, [onInvalidate])
useEffect(() => {
if (!hadServerAuthRef.current) {
return
}
if (!localAuth?.isAuthenticated) {
return
}
if (!serverAuth || serverAuth.isLoading || serverAuth.isRefreshing) {
return
}
if (serverAuth.isAuthenticated) {
return
}
void invalidateOnce()
}, [invalidateOnce, localAuth, serverAuth])
const sessionEstablished = Boolean(
serverAuth &&
!serverAuth.isLoading &&
!serverAuth.isRefreshing &&
serverAuth.isAuthenticated
)
return (
<ConvexAuthErrorBoundary
sessionEstablished={sessionEstablished}
onAuthError={() => void invalidateOnce()}
>
{children}
</ConvexAuthErrorBoundary>
)
}
+114
View File
@@ -0,0 +1,114 @@
import { Ionicons } from "@expo/vector-icons"
import { Image, type ImageContentFit, type ImageStyle } from "expo-image"
import { memo, useMemo } from "react"
import {
PixelRatio,
StyleProp,
StyleSheet,
View,
type ViewStyle,
} from "react-native"
import { useThemeColors } from "@/lib/theme"
import {
coverImageSizes,
type CoverImageSize,
withCoverImageSize,
} from "@/lib/urls"
const DEFAULT_SOURCE_SIZE: CoverImageSize = 1024
const PIXEL_RATIO = PixelRatio.get()
function sourceSize(style: ImageStyle): CoverImageSize {
const layoutSizes = [
style.width,
style.height,
style.maxWidth,
style.maxHeight,
].filter((value): value is number => typeof value === "number")
if (layoutSizes.length === 0) return DEFAULT_SOURCE_SIZE
const requiredPixels = Math.max(...layoutSizes) * PIXEL_RATIO
return (
coverImageSizes.find((size) => size >= requiredPixels) ??
DEFAULT_SOURCE_SIZE
)
}
function placeholderIconSize(style: ImageStyle): number {
const { width, height, maxWidth } = style
if (typeof width === "number" && typeof height === "number") {
return Math.min(width, height) * 0.38
}
if (typeof width === "number") {
return width * 0.38
}
if (typeof maxWidth === "number") {
return maxWidth * 0.38
}
return 48
}
const placeholderBaseStyle: ViewStyle = {
alignItems: "center",
justifyContent: "center",
overflow: "hidden",
}
export const CoverImage = memo(function CoverImage({
uri,
hasCover,
style,
contentFit = "cover",
blurRadius,
placeholderVariant = "icon",
}: {
uri: string
hasCover: boolean
style?: StyleProp<ImageStyle>
contentFit?: ImageContentFit
blurRadius?: number
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])
if (!hasCover) {
return (
<View
style={[
style,
placeholderBaseStyle,
{ backgroundColor: colors.coverPlaceholder },
]}
>
{placeholderVariant === "icon" ? (
<Ionicons
name="musical-note"
size={placeholderIconSize(flatStyle)}
color={colors.coverPlaceholderIcon}
/>
) : null}
</View>
)
}
return (
<Image
source={source}
style={[style, { backgroundColor: colors.coverPlaceholder }]}
contentFit={contentFit}
transition={150}
blurRadius={blurRadius}
cachePolicy="memory-disk"
recyclingKey={sourceUri}
enforceEarlyResizing
/>
)
})
@@ -0,0 +1,359 @@
import * as Haptics from "expo-haptics"
import { SymbolView } from "expo-symbols"
import { useCallback, useMemo, useState, type ReactNode } from "react"
import {
PlatformColor,
Pressable,
StyleSheet,
type LayoutChangeEvent,
} from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import Animated, {
cancelAnimation,
Extrapolation,
interpolate,
useAnimatedStyle,
useSharedValue,
withSpring,
withTiming,
} from "react-native-reanimated"
import { scheduleOnRN } from "react-native-worklets"
const ACTION_WIDTH = 82
const CARD_ROUNDING_REVEAL = 40
const PILL_MIN_MARGIN = 10
const PILL_COMMITTED_MARGIN = 6
const PILL_WIDTH_INPUT = [24, ACTION_WIDTH, 220]
const PILL_WIDTH_OUTPUT = [0, 62, 200]
const PILL_HEIGHT_INPUT = [0, 24, 62, 140, 200]
const PILL_HEIGHT_RATIO = [0, 0.3, 0.77, 0.82, 0.86]
const ICON_FULL_SIZE_REVEAL = 64
const FULL_SWIPE_RATIO = 0.55
const FLING_VELOCITY = 400
const SETTLE_SPRING = { duration: 450, dampingRatio: 1 }
const LABEL_SPRING = { duration: 300, dampingRatio: 0.85 }
const SLIDE_OUT = { duration: 200 }
const COLLAPSE = { duration: 250 }
/**
* Keeps at most one row open, like a `UITableView`: opening a row closes the
* previous one, and `closeOpenRow` closes whichever is open (call it when the
* list starts scrolling).
*/
export type SwipeRowGroup = {
setOpen: (close: () => void) => void
clear: (close: () => void) => void
closeOpenRow: () => void
}
export function useSwipeRowGroup(): SwipeRowGroup {
const [group] = useState<SwipeRowGroup>(() => {
let openRowClose: (() => void) | null = null
return {
setOpen(close) {
if (openRowClose && openRowClose !== close) openRowClose()
openRowClose = close
},
clear(close) {
if (openRowClose === close) openRowClose = null
},
closeOpenRow() {
openRowClose?.()
openRowClose = null
},
}
})
return group
}
type SwipeToRemoveRowProps = {
group: SwipeRowGroup
backgroundColor: string
actionAccessibilityLabel: string
/** Resolves `false` if the removal failed, which restores the row. */
onRemove: () => Promise<boolean>
children: ReactNode
}
/**
* The iOS 26 trailing swipe-to-delete row: the row lifts into a rounded card
* and a red pill grows in the revealed space. Release past half the pill to
* leave it open, or drag past the full-swipe point (haptic, the pill fills the
* space) to remove on release.
*/
export function SwipeToRemoveRow(props: SwipeToRemoveRowProps) {
const [generation, setGeneration] = useState(0)
const restore = useCallback(() => setGeneration((value) => value + 1), [])
return <SwipeRowBody key={generation} {...props} onRestore={restore} />
}
function SwipeRowBody({
group,
backgroundColor,
actionAccessibilityLabel,
onRemove,
onRestore,
children,
}: SwipeToRemoveRowProps & { onRestore: () => void }) {
const width = useSharedValue(0)
const height = useSharedValue(0)
const translateX = useSharedValue(0)
const startX = useSharedValue(0)
const committed = useSharedValue(false)
const commitProgress = useSharedValue(0)
const collapse = useSharedValue(0)
const removing = useSharedValue(false)
const [isOpen, setIsOpen] = useState(false)
const close = useCallback(() => {
if (removing.value) return
translateX.value = withSpring(0, SETTLE_SPRING)
setIsOpen(false)
}, [removing, translateX])
const handleSwipeStart = useCallback(() => group.setOpen(close), [close, group])
const handleSettle = useCallback(
(open: boolean) => {
setIsOpen(open)
if (!open) group.clear(close)
},
[close, group]
)
const handleRemove = useCallback(async () => {
group.clear(close)
if (!(await onRemove())) onRestore()
}, [close, group, onRemove, onRestore])
const animateRemoval = useCallback(() => {
"worklet"
removing.value = true
commitProgress.value = withSpring(1, LABEL_SPRING)
translateX.value = withTiming(-width.value, SLIDE_OUT, (slid) => {
if (!slid) return
collapse.value = withTiming(1, COLLAPSE, (collapsed) => {
if (collapsed) scheduleOnRN(handleRemove)
})
})
}, [collapse, commitProgress, handleRemove, removing, translateX, width])
const pan = useMemo(() => {
const gesture = Gesture.Pan()
.failOffsetY([-10, 10])
.onStart(() => {
if (removing.value) return
cancelAnimation(translateX)
startX.value = translateX.value
scheduleOnRN(handleSwipeStart)
})
.onUpdate((event) => {
if (removing.value) return
const rowWidth = width.value
const x = Math.max(
-rowWidth,
Math.min(0, startX.value + event.translationX)
)
translateX.value = x
const shouldCommit = -x > rowWidth * FULL_SWIPE_RATIO
if (shouldCommit !== committed.value) {
committed.value = shouldCommit
commitProgress.value = withSpring(shouldCommit ? 1 : 0, LABEL_SPRING)
scheduleOnRN(impact)
}
})
.onEnd((event) => {
if (removing.value) return
if (committed.value) {
animateRemoval()
return
}
const velocity = event.velocityX
const open =
velocity < -FLING_VELOCITY ||
(velocity <= FLING_VELOCITY && translateX.value < -ACTION_WIDTH / 2)
translateX.value = withSpring(open ? -ACTION_WIDTH : 0, {
...SETTLE_SPRING,
velocity,
})
scheduleOnRN(handleSettle, open)
})
return isOpen
? gesture.activeOffsetX([-10, 10])
: gesture.activeOffsetX(-10).failOffsetX(10)
}, [
animateRemoval,
commitProgress,
committed,
handleSettle,
handleSwipeStart,
isOpen,
removing,
startX,
translateX,
width,
])
const handleLayout = useCallback(
(event: LayoutChangeEvent) => {
if (removing.value) return
width.value = event.nativeEvent.layout.width
height.value = event.nativeEvent.layout.height
},
[height, removing, width]
)
const containerStyle = useAnimatedStyle(() =>
collapse.value > 0 ? { height: height.value * (1 - collapse.value) } : {}
)
const contentStyle = useAnimatedStyle(() => ({
borderRadius: interpolate(
-translateX.value,
[0, CARD_ROUNDING_REVEAL],
[0, height.value / 2],
Extrapolation.CLAMP
),
transform: [{ translateX: translateX.value }],
}))
const cardFillStyle = useAnimatedStyle(() => ({
opacity: interpolate(
-translateX.value,
[0, CARD_ROUNDING_REVEAL],
[0, 1],
Extrapolation.CLAMP
),
}))
const actionStyle = useAnimatedStyle(() => ({
width: -translateX.value,
}))
// The pill grows out of a dot centered in the revealed space; past the
// full-swipe point it stretches to fill that space.
const pillStyle = useAnimatedStyle(() => {
const revealed = -translateX.value
const rowHeight = height.value
const resting = Math.min(
revealed - PILL_MIN_MARGIN * 2,
interpolate(
revealed,
PILL_WIDTH_INPUT,
PILL_WIDTH_OUTPUT,
Extrapolation.EXTEND
)
)
const pillWidth = Math.max(
0,
resting +
(revealed - PILL_COMMITTED_MARGIN * 2 - resting) *
commitProgress.value
)
const restingHeight = interpolate(
pillWidth,
PILL_HEIGHT_INPUT,
PILL_HEIGHT_RATIO.map((ratio) => ratio * rowHeight),
Extrapolation.CLAMP
)
const pillHeight =
restingHeight +
(rowHeight - PILL_COMMITTED_MARGIN * 2 - restingHeight) *
commitProgress.value
return {
width: pillWidth,
height: pillHeight,
borderRadius: pillHeight / 2,
opacity: 1 - collapse.value,
}
})
const iconStyle = useAnimatedStyle(() => ({
transform: [
{
scale: interpolate(
-translateX.value,
[PILL_WIDTH_INPUT[0], ICON_FULL_SIZE_REVEAL],
[0, 1],
Extrapolation.CLAMP
),
},
],
}))
return (
<Animated.View
onLayout={handleLayout}
style={[styles.container, containerStyle]}
>
<Animated.View style={[styles.action, actionStyle]}>
<Pressable
accessibilityRole="button"
accessibilityLabel={actionAccessibilityLabel}
onPress={() => animateRemoval()}
style={styles.actionButton}
>
<Animated.View style={[styles.pill, pillStyle]}>
<Animated.View style={iconStyle}>
<SymbolView
name="minus.circle.fill"
size={20}
tintColor="white"
/>
</Animated.View>
</Animated.View>
</Pressable>
</Animated.View>
<GestureDetector gesture={pan}>
<Animated.View style={[styles.card, { backgroundColor }, contentStyle]}>
<Animated.View
pointerEvents="none"
style={[styles.cardFill, cardFillStyle]}
/>
{children}
{isOpen ? (
<Pressable
accessible={false}
onPress={close}
style={StyleSheet.absoluteFill}
/>
) : null}
</Animated.View>
</GestureDetector>
</Animated.View>
)
}
function impact() {
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium)
}
const styles = StyleSheet.create({
container: { overflow: "hidden" },
card: { overflow: "hidden" },
cardFill: {
...StyleSheet.absoluteFill,
backgroundColor: PlatformColor("tertiarySystemFill"),
},
action: {
position: "absolute",
top: 0,
right: 0,
bottom: 0,
},
actionButton: {
flex: 1,
alignItems: "center",
justifyContent: "center",
},
pill: {
alignItems: "center",
justifyContent: "center",
overflow: "hidden",
backgroundColor: PlatformColor("systemRed"),
},
})
@@ -0,0 +1,7 @@
export type { MediaAction, MediaMenuConfig, MediaNavigation } from "@/components/media-context-menu"
export type { MediaShareContext } from "@/lib/media-links"
export {
buildMediaMenuActions,
MediaActionMenu,
MediaContextMenu,
} from "@/components/media-context-menu"
+359
View File
@@ -0,0 +1,359 @@
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 { 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,
PlaylistSummary,
} from "@otunes/convex/types"
import { albumCoverUrl, artistCoverUrl, playlistCoverUrl } from "@/lib/urls"
import {
carouselCardWidth,
radius,
spacing,
useThemeColors,
useTwoColumnCardWidth,
} from "@/lib/theme"
export type MediaItem = BrowseAlbum | BrowseArtist | PlaylistSummary
const GRID_INITIAL_ROWS = 5
export const AlbumCard = memo(function AlbumCard({
album,
width = carouselCardWidth,
}: {
album: BrowseAlbum
width?: number
}) {
const { push } = useAppNavigation()
const { config } = useServerConfig()
const colors = useThemeColors()
const { handleAlbumAction, isAlbumFavorite } = useMediaMenuActions()
const onPress = useCallback(() => {
push(`/album/${album.id}`)
}, [push, album.id])
if (!config) return null
const card = (
<Pressable style={[styles.card, { width }]} onPress={onPress}>
<CoverImage
uri={albumCoverUrl(config.serverUrl, album.id)}
hasCover={album.cover != null}
style={{ width, height: width, borderRadius: radius.md }}
/>
<Text
style={[styles.title, { color: colors.foreground }]}
numberOfLines={2}
>
{album.title}
</Text>
<Text
style={[styles.subtitle, { color: colors.mutedForeground }]}
numberOfLines={1}
>
{album.artist.name}
</Text>
</Pressable>
)
return (
<MediaContextMenu
favorited={isAlbumFavorite(album.id)}
navigation={{ artist: { id: album.artist.id } }}
share={{ type: "album", albumId: album.id }}
onAction={(action) => void handleAlbumAction(album, action)}
>
{card}
</MediaContextMenu>
)
})
export const ArtistCard = memo(function ArtistCard({
artist,
width = carouselCardWidth,
}: {
artist: BrowseArtist
width?: number
}) {
const { push } = useAppNavigation()
const { config } = useServerConfig()
const colors = useThemeColors()
const { handleArtistAction, isArtistFavorite } = useMediaMenuActions()
const onPress = useCallback(() => {
push(`/artist/${artist.id}`)
}, [push, artist.id])
if (!config) return null
const card = (
<Pressable style={[styles.card, { width }]} onPress={onPress}>
<CoverImage
uri={artistCoverUrl(config.serverUrl, artist.id)}
hasCover={artist.photo != null}
style={{ width, height: width, borderRadius: width / 2 }}
/>
<Text
style={[styles.title, { color: colors.foreground }]}
numberOfLines={2}
>
{artist.name}
</Text>
</Pressable>
)
return (
<MediaContextMenu
favorited={isArtistFavorite(artist.id)}
share={{ type: "artist", artistId: artist.id }}
onAction={(action) => void handleArtistAction(artist, action)}
>
{card}
</MediaContextMenu>
)
})
export const PlaylistCard = memo(function PlaylistCard({
playlist,
width = carouselCardWidth,
}: {
playlist: PlaylistSummary
width?: number
}) {
const { push } = useAppNavigation()
const { config } = useServerConfig()
const colors = useThemeColors()
const { handlePlaylistAction } = useMediaMenuActions()
const onPress = useCallback(() => {
push(`/playlist/${playlist.id}`)
}, [push, playlist.id])
if (!config) return null
const card = (
<Pressable style={[styles.card, { width }]} onPress={onPress}>
<CoverImage
uri={playlistCoverUrl(config.serverUrl, playlist.id)}
hasCover={playlist.cover != null}
style={{ width, height: width, borderRadius: radius.md }}
/>
<Text
style={[styles.title, { color: colors.foreground }]}
numberOfLines={2}
>
{playlist.title}
</Text>
<Text
style={[styles.subtitle, { color: colors.mutedForeground }]}
numberOfLines={1}
>
{playlist.owner}
</Text>
</Pressable>
)
return (
<MediaContextMenu
showFavorite={false}
share={{ type: "playlist", playlistId: playlist.id }}
onAction={(action) => void handlePlaylistAction(playlist, action)}
>
{card}
</MediaContextMenu>
)
})
const CarouselCard = memo(function CarouselCard({
item,
width,
}: {
item: MediaItem
width: number
}) {
if ("owner" in item) return <PlaylistCard playlist={item} width={width} />
if ("artist" in item) return <AlbumCard album={item} width={width} />
return <ArtistCard artist={item} width={width} />
})
export function MediaGrid({ content }: { content: MediaItem[] }) {
const cardWidth = useTwoColumnCardWidth()
return (
<View style={styles.grid}>
{content.map((item) => (
<View key={item.id} style={{ width: cardWidth }}>
<CarouselCard item={item} width={cardWidth} />
</View>
))}
</View>
)
}
export function MediaGridList({
content,
paddingBottom,
onEndReached,
ListHeaderComponent,
contentInset = true,
}: {
content: MediaItem[]
paddingBottom: number
onEndReached?: () => void
ListHeaderComponent?: ReactElement | null
contentInset?: boolean
}) {
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}
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,
{ paddingBottom },
]}
columnWrapperStyle={[
styles.gridListRow,
!contentInset && styles.gridListRowInset,
]}
contentInsetAdjustmentBehavior="automatic"
ListHeaderComponent={ListHeaderComponent}
onEndReached={onEndReached}
onEndReachedThreshold={0.5}
/>
)
}
function mediaItemKey(item: MediaItem) {
return item.id
}
function renderCarouselItem({ item }: ListRenderItemInfo<MediaItem>) {
return (
<View>
<CarouselCard item={item} width={carouselCardWidth} />
</View>
)
}
function ContentCarouselBody({
title,
href,
content,
}: {
title: string
href?: string
content: MediaItem[]
}) {
const { push } = useAppNavigation()
const colors = useThemeColors()
const onHeaderPress = useCallback(() => {
if (href) {
push(href)
}
}, [href, push])
return (
<View style={styles.section}>
<Pressable
disabled={!href}
onPress={onHeaderPress}
style={styles.sectionHeader}
>
<Text style={[styles.sectionTitle, { color: colors.foreground }]}>
{title}
</Text>
{href ? (
<Ionicons
name="chevron-forward"
size={18}
color={colors.mutedForeground}
/>
) : null}
</Pressable>
<FlatList
data={content}
keyExtractor={mediaItemKey}
renderItem={renderCarouselItem}
horizontal
showsHorizontalScrollIndicator={false}
contentContainerStyle={styles.carouselContent}
/>
</View>
)
}
export const ContentCarousel = memo(ContentCarouselBody)
const styles = StyleSheet.create({
card: {
gap: spacing.xs,
},
title: {
fontSize: 14,
fontWeight: "600",
},
subtitle: {
fontSize: 12,
},
section: {
gap: spacing.md,
},
sectionHeader: {
flexDirection: "row",
alignItems: "center",
gap: spacing.xs,
},
sectionTitle: {
fontSize: 22,
fontWeight: "700",
},
carouselContent: {
gap: spacing.md,
},
grid: {
flexDirection: "row",
flexWrap: "wrap",
gap: spacing.md,
},
gridListContent: {
padding: spacing.lg,
gap: spacing.md,
},
gridListContentInset: {
gap: spacing.md,
},
gridListRow: {
gap: spacing.md,
},
gridListRowInset: {
paddingHorizontal: spacing.lg,
},
})
@@ -0,0 +1,269 @@
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 { useServerConfig } from "@/contexts/server-config"
import type { MediaShareContext } from "@/lib/media-links"
import { shouldShowShare } from "@/lib/media-links"
import { shareMediaLink } from "@/lib/share-media-link"
export type MediaAction =
| "share"
| "playlist"
| "play-next"
| "play-last"
| "shuffle"
| "favorite"
| "go-artist"
| "go-album"
| "delete-playlist"
export type MediaNavigation = {
artist?: { id: string }
album?: { id: string }
}
export type MediaMenuConfig = {
selectedCount?: number
playlistLabel?: string
favorited?: boolean
showFavorite?: boolean
navigation?: MediaNavigation
share?: MediaShareContext
includeActions?: MediaAction[]
onAction: (action: MediaAction) => void
}
type MediaMenuWrapperProps = MediaMenuConfig & {
children: ReactNode
style?: StyleProp<ViewStyle>
}
const QUEUE_ACTIONS: MediaAction[] = ["play-next", "play-last", "shuffle"]
const MEDIA_ACTION_ITEMS: {
action: MediaAction
label: (
countSuffix: string,
favorited: boolean | undefined,
playlistLabel: string
) => string
image: NonNullable<MenuAction["image"]> & string
}[] = [
{
action: "playlist",
label: (countSuffix, _favorited, playlistLabel) =>
`${playlistLabel}${countSuffix}`,
image: "text.badge.plus",
},
{
action: "play-next",
label: (countSuffix) => `Play Next${countSuffix}`,
image: "text.line.first.and.arrowtriangle.forward",
},
{
action: "play-last",
label: (countSuffix) => `Play Last${countSuffix}`,
image: "text.line.last.and.arrowtriangle.forward",
},
{
action: "shuffle",
label: (countSuffix) => `Shuffle${countSuffix}`,
image: "shuffle",
},
{
action: "go-artist",
label: () => "Go to Artist",
image: "person",
},
{
action: "go-album",
label: () => "Go to Album",
image: "opticaldisc",
},
{
action: "favorite",
label: (countSuffix, favorited) =>
`${favorited ? "Unfavorite" : "Favorite"}${countSuffix}`,
image: "star",
},
{
action: "delete-playlist",
label: () => "Delete Playlist",
image: "trash",
},
]
function isActionIncluded(
action: MediaAction,
config: Omit<MediaMenuConfig, "onAction">
): boolean {
if (config.includeActions) {
return config.includeActions.includes(action)
}
if (action === "delete-playlist") {
return false
}
if (action === "share") {
return shouldShowShare(config.share, config.selectedCount ?? 1)
}
if (action === "favorite" && config.showFavorite === false) {
return false
}
if (action === "go-artist" && !config.navigation?.artist) {
return false
}
if (action === "go-album" && !config.navigation?.album) {
return false
}
return true
}
export function buildMediaMenuActions(
config: Omit<MediaMenuConfig, "onAction">
): MenuAction[] {
const {
selectedCount = 1,
favorited,
playlistLabel = "Add to Playlist",
} = config
const countSuffix = selectedCount > 1 ? ` (${selectedCount})` : ""
const actions: MenuAction[] = []
if (isActionIncluded("share", config)) {
actions.push({
id: "share",
title: "Share",
image: "square.and.arrow.up",
})
}
for (const item of MEDIA_ACTION_ITEMS) {
if (!isActionIncluded(item.action, config)) {
continue
}
actions.push({
id: item.action,
title: item.label(countSuffix, favorited, playlistLabel),
image:
item.action === "favorite" && favorited ? "star.fill" : item.image,
})
}
return actions
}
function MediaMenuBase({
children,
style,
shouldOpenOnLongPress,
onAction,
share,
...actionConfig
}: MediaMenuWrapperProps & { shouldOpenOnLongPress?: boolean }) {
const { config } = useServerConfig()
return (
<MenuView
shouldOpenOnLongPress={shouldOpenOnLongPress}
actions={buildMediaMenuActions({ ...actionConfig, share })}
onPressAction={(event) => {
const action = event.nativeEvent.event as MediaAction
if (action === "share" && share && config) {
void shareMediaLink(config.serverUrl, share)
return
}
onAction(action)
}}
style={[{ alignSelf: "stretch" }, style]}
>
{children}
</MenuView>
)
}
// 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 />
}
export function MediaActionMenu(props: MediaMenuWrapperProps) {
return <MediaMenuBase {...props} />
}
export const MEDIA_QUEUE_ACTIONS = QUEUE_ACTIONS
+342
View File
@@ -0,0 +1,342 @@
import { Ionicons } from "@expo/vector-icons"
import { NativeTabs } from "expo-router/unstable-native-tabs"
import { useRouter } from "expo-router"
import { Platform, Pressable, StyleSheet, Text, View } from "react-native"
import { CoverImage } from "@/components/cover-image"
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { albumCoverUrl } from "@/lib/urls"
import {
miniPlayerHeight,
tabBarHeight,
useBlurTint,
useMiniPlayerBackground,
useThemeColors,
} from "@/lib/theme"
function MiniPlayerContent({
placement,
variant = "bar",
onOpenPlayer,
}: {
placement: "regular" | "inline"
variant: "bar" | "accessory"
onOpenPlayer: () => void
}) {
const colors = useThemeColors()
const { config } = useServerConfig()
const { currentSong, isPlaying } = usePlaybackQueue()
const { setIsPlaying, skipNext } = usePlaybackActions()
if (!currentSong || !config) {
return null
}
const compact = placement === "inline"
const isAccessory = variant === "accessory"
const artworkStyle = isAccessory ? styles.accessoryArtwork : styles.artwork
const rowStyle = compact
? styles.inlineContent
: isAccessory
? styles.accessoryContent
: styles.content
if (compact) {
return (
<Pressable style={rowStyle} onPress={onOpenPlayer}>
<CoverImage
uri={albumCoverUrl(config.serverUrl, currentSong.album.id)}
hasCover={currentSong.album.cover != null}
style={
isAccessory ? styles.accessoryInlineArtwork : styles.inlineArtwork
}
/>
<View
style={isAccessory ? styles.accessoryInlineMeta : styles.inlineMeta}
>
<Text
style={[
isAccessory ? styles.accessoryTitle : styles.title,
{ color: colors.foreground },
]}
numberOfLines={1}
>
{currentSong.title}
</Text>
</View>
<Pressable
style={styles.controlButton}
onPress={(event) => {
event.stopPropagation()
setIsPlaying(!isPlaying)
}}
hitSlop={6}
>
<Ionicons
name={isPlaying ? "pause" : "play"}
size={20}
color={colors.foreground}
/>
</Pressable>
</Pressable>
)
}
return (
<Pressable style={rowStyle} onPress={onOpenPlayer}>
<CoverImage
uri={albumCoverUrl(config.serverUrl, currentSong.album.id)}
hasCover={currentSong.album.cover != null}
style={artworkStyle}
/>
<View style={isAccessory ? styles.accessoryMeta : styles.meta}>
<Text
style={[
isAccessory ? styles.accessoryTitle : styles.title,
{ color: colors.foreground },
]}
numberOfLines={1}
>
{currentSong.title}
</Text>
<Text
style={[
isAccessory ? styles.accessoryArtist : styles.artist,
{ color: colors.mutedForeground },
]}
numberOfLines={1}
>
{currentSong.artist.name}
</Text>
</View>
<View style={styles.controls}>
<Pressable
style={styles.controlButton}
onPress={(event) => {
event.stopPropagation()
setIsPlaying(!isPlaying)
}}
hitSlop={6}
>
<Ionicons
name={isPlaying ? "pause" : "play"}
size={24}
color={colors.foreground}
/>
</Pressable>
<Pressable
style={styles.controlButton}
onPress={(event) => {
event.stopPropagation()
void skipNext()
}}
hitSlop={6}
>
<Ionicons name="play-forward" size={24} color={colors.foreground} />
</Pressable>
</View>
</Pressable>
)
}
function MiniPlayerChrome({ children }: { children: React.ReactNode }) {
const colors = useThemeColors()
const backgroundColor = useMiniPlayerBackground()
return (
<View style={[styles.androidBar, { backgroundColor }]}>
<View style={[styles.topBorder, { backgroundColor: colors.border }]} />
{children}
</View>
)
}
export function TabBottomAccessory() {
const router = useRouter()
const { currentSong, queueSongIds } = usePlaybackQueue()
const placement = NativeTabs.BottomAccessory.usePlacement()
if (!currentSong || queueSongIds.length === 0) {
return null
}
const content = (
<View style={styles.accessoryContainer}>
<MiniPlayerContent
placement={placement}
variant="accessory"
onOpenPlayer={() => router.push("/player")}
/>
</View>
)
if (Platform.OS === "android") {
return <MiniPlayerChrome>{content}</MiniPlayerChrome>
}
return content
}
//
// function useFloatingMiniPlayerLayout() {
// const segments = useSegments() as string[]
// const insets = useSafeAreaInsets()
//
// const onPlayerModal = segments.includes("player")
// const onAuthFlow =
// segments.includes("signin") ||
// segments.includes("signup") ||
// segments.includes("server")
// const onTabs = segments.includes("(tabs)")
//
// const bottom = insets.bottom + (onTabs ? 0 : 0)
//
// return {
// bottom,
// hidden: onPlayerModal || onAuthFlow || onTabs,
// }
// }
//
// export function FloatingMiniPlayer() {
// const router = useRouter()
// const { bottom, hidden } = useFloatingMiniPlayerLayout()
// const { currentSong, queueSongIds } = usePlayback()
//
// if (hidden || !currentSong || queueSongIds.length === 0) {
// return null
// }
//
// return (
// <View pointerEvents="box-none" style={[styles.floatingContainer, { bottom }]}>
// <MiniPlayerChrome>
// <MiniPlayerContent onOpenPlayer={() => router.push("/player")} />
// </MiniPlayerChrome>
// </View>
// )
// }
const styles = StyleSheet.create({
floatingContainer: {
position: "absolute",
left: 0,
right: 0,
zIndex: 100,
},
accessoryContainer: {
flex: 1,
justifyContent: "center",
alignSelf: "stretch",
},
blur: {
overflow: "hidden",
},
androidBar: {
overflow: "hidden",
},
topBorder: {
height: StyleSheet.hairlineWidth,
},
content: {
flexDirection: "row",
alignItems: "center",
paddingHorizontal: 16,
paddingVertical: 10,
minHeight: miniPlayerHeight,
gap: 12,
},
accessoryContent: {
flex: 1,
flexDirection: "row",
alignItems: "center",
alignSelf: "stretch",
paddingHorizontal: 12,
paddingVertical: 8,
gap: 12,
},
inlineContent: {
flex: 1,
flexDirection: "row",
alignItems: "center",
alignSelf: "stretch",
paddingHorizontal: 12,
paddingVertical: 8,
gap: 10,
},
artwork: {
width: 36,
height: 36,
borderRadius: 5,
},
accessoryArtwork: {
width: 32,
height: 32,
borderRadius: 4,
},
inlineArtwork: {
width: 28,
height: 28,
borderRadius: 4,
},
accessoryInlineArtwork: {
width: 24,
height: 24,
borderRadius: 4,
},
meta: {
flex: 1,
minWidth: 0,
justifyContent: "center",
},
accessoryMeta: {
flex: 1,
minWidth: 0,
justifyContent: "center",
paddingTop: 3,
},
inlineMeta: {
flex: 1,
minWidth: 0,
justifyContent: "center",
},
accessoryInlineMeta: {
flex: 1,
minWidth: 0,
justifyContent: "center",
paddingTop: 2,
},
title: {
fontSize: 15,
fontWeight: "500",
lineHeight: 18,
},
accessoryTitle: {
fontSize: 14,
fontWeight: "500",
lineHeight: 17,
},
artist: {
fontSize: 13,
lineHeight: 16,
marginTop: 2,
},
accessoryArtist: {
fontSize: 12,
lineHeight: 15,
marginTop: 1,
},
controls: {
flexDirection: "row",
alignItems: "center",
gap: 4,
marginLeft: 4,
},
controlButton: {
width: 36,
height: 36,
alignItems: "center",
justifyContent: "center",
},
})
export { miniPlayerHeight, tabBarHeight }
+158
View File
@@ -0,0 +1,158 @@
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 { Pressable, StyleSheet, Text, View } from "react-native"
import {
MediaContextMenu,
type MediaAction,
type MediaMenuConfig,
} from "@/components/media-context-menu"
export const SongRow = memo(function SongRow({
song,
onPress,
contextMenu,
trailing,
palette,
}: {
song: BrowseSong
onPress?: () => void
contextMenu?: Omit<MediaMenuConfig, "onAction"> & {
onAction: MediaMenuConfig["onAction"]
}
trailing?: React.ReactNode
palette?: Pick<CoverPalette, "foreground" | "secondaryForeground" | "divider">
}) {
const { config } = useServerConfig()
const colors = useThemeColors()
if (!config) return null
const foreground = palette?.foreground ?? colors.foreground
const secondaryForeground =
palette?.secondaryForeground ?? colors.mutedForeground
const row = (
<Pressable
style={[
styles.row,
{ borderBottomColor: palette?.divider ?? colors.border },
]}
onPress={onPress}
>
<CoverImage
uri={albumCoverUrl(config.serverUrl, song.album.id)}
hasCover={song.album.cover != null}
style={styles.rowArtwork}
/>
<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}
</Pressable>
)
if (!contextMenu) {
return row
}
return (
<MediaContextMenu {...contextMenu}>
{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,
onPlay,
onAction,
}: {
song: BrowseSong
favorited: boolean
playlistLabel?: string
palette?: Pick<CoverPalette, "foreground" | "secondaryForeground" | "divider">
onPlay: (song: BrowseSong) => void
onAction: (song: BrowseSong, action: MediaAction) => void
}) {
const handlePress = useCallback(() => onPlay(song), [onPlay, song])
return (
<SongRow
song={song}
palette={palette}
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
const styles = StyleSheet.create({
row: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
minHeight: 64,
paddingVertical: 10,
paddingHorizontal: spacing.lg,
borderBottomWidth: StyleSheet.hairlineWidth,
},
rowArtwork: {
width: 44,
height: 44,
borderRadius: 6,
},
rowMeta: {
flex: 1,
minWidth: 0,
},
rowTitle: {
fontSize: 16,
fontWeight: "500",
},
rowSubtitle: {
fontSize: 14,
marginTop: 3,
},
duration: {
fontSize: 12,
marginRight: spacing.xs,
},
})
@@ -0,0 +1,65 @@
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"
export function ProfileHeaderButton() {
const router = useRouter()
const colors = useThemeColors()
const user = useCachedQuery(api.auth.currentUser)
return (
<Pressable
accessibilityLabel="Open profile"
accessibilityRole="button"
hitSlop={8}
onPress={() => router.push("/(app)/settings")}
style={({ pressed }) => [styles.button, { opacity: pressed ? 0.75 : 1 }]}
>
<View
style={[
styles.avatar,
{
backgroundColor: colors.muted,
borderColor: colors.border,
},
]}
>
{user?.image ? (
<Image source={{ uri: user.image }} style={styles.image} contentFit="cover" />
) : (
<Text style={[styles.initials, { color: colors.foreground }]}>
{initialsFromName(user?.name ?? "Me")}
</Text>
)}
</View>
</Pressable>
)
}
const styles = StyleSheet.create({
button: {
marginRight: 4,
},
avatar: {
width: 42,
height: 42,
borderRadius: radius.full,
borderWidth: 1,
alignItems: "center",
justifyContent: "center",
overflow: "hidden",
},
image: {
width: "100%",
height: "100%",
},
initials: {
fontSize: 14,
fontWeight: "700",
},
})
+141
View File
@@ -0,0 +1,141 @@
import { memo, useCallback, useMemo } from "react"
import {
FlatList,
StyleSheet,
Text,
View,
type ListRenderItemInfo,
} 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 { 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"
import { spacing, useThemeColors } from "@/lib/theme"
function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
const colors = useThemeColors()
const { playFromSong } = usePlaybackActions()
const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions()
const hasQuery = searchQuery.length > 0
const results = useCachedQuery(
api.library.searchLibrary,
hasQuery ? { query: searchQuery } : "skip"
)
const playlistResults = useCachedQuery(
api.playlists.searchPlaylists,
hasQuery ? { query: searchQuery } : "skip"
)
const isSearching =
hasQuery && (results === undefined || playlistResults === undefined)
const hasResults = useMemo(
() =>
Boolean(
(results &&
(results.topResults.length > 0 ||
results.artists.length > 0 ||
results.albums.length > 0 ||
results.songs.length > 0)) ||
(playlistResults && playlistResults.length > 0)
),
[playlistResults, results]
)
const songIds = useMemo(
() => 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 />
}
if (!hasQuery) {
return <></>
}
return (
<FlatList
data={results?.songs ?? []}
keyExtractor={(song) => song.id}
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{ paddingBottom: tabContentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
keyboardShouldPersistTaps="handled"
ListHeaderComponent={
<>
{!hasResults ? (
<View style={styles.empty}>
<Text
style={[styles.emptyText, { color: colors.mutedForeground }]}
>
No results for "{searchQuery}"
</Text>
</View>
) : null}
{results?.artists.length ? (
<View style={styles.section}>
<ContentCarousel title="Artists" content={results.artists} />
</View>
) : null}
{results?.albums.length ? (
<View style={styles.section}>
<ContentCarousel title="Albums" content={results.albums} />
</View>
) : null}
</>
}
renderItem={renderItem}
ListFooterComponent={
playlistResults && playlistResults.length > 0 ? (
<View style={styles.section}>
<ContentCarousel title="Playlists" content={playlistResults} />
</View>
) : null
}
/>
)
}
export const SearchResults = memo(SearchResultsBody)
const styles = StyleSheet.create({
empty: { padding: spacing.xl, alignItems: "center" },
emptyText: { fontSize: 16 },
section: {
paddingHorizontal: spacing.lg,
paddingBottom: spacing.lg,
gap: spacing.md,
},
})
Loaded 100 of 371 files, more files were not shown because too many files have changed in this diff. Show more