Compare commits

...
315 changed files with 31437 additions and 17203 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 -->
+63 -90
View File
@@ -7,112 +7,85 @@
# To ensure security and compatibility, regularly update the NODE_VERSION ARG to the latest LTS version.
ARG NODE_VERSION=24.13.0-slim
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* ./
# 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
# ============================================
# Stage 2: Build Next.js application in standalone mode
# ============================================
FROM node:${NODE_VERSION} AS builder
# Set working directory
WORKDIR /app
# Copy project dependencies from dependencies stage
COPY --from=dependencies /app/node_modules ./node_modules
# Copy application source code
COPY . .
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
# 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
# ============================================
# Stage 3: Run Next.js application
# ============================================
FROM node:${NODE_VERSION} AS runner
FROM node:${NODE_VERSION} AS runner-base
RUN apt-get update && \
apt-get install -y ffmpeg && \
rm -rf /var/lib/apt/lists/*
# Set working directory
FROM node:${NODE_VERSION} AS dependencies
WORKDIR /app
# 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/
# Explicit workspace — do not use apps/* so mobile cannot be discovered.
RUN printf '%s\n' \
'packages:' \
' - "apps/web"' \
' - "packages/convex"' \
> pnpm-workspace.yaml
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
# ============================================
# Reuse the installed workspace — no need to re-copy node_modules from a blank image.
FROM dependencies AS builder
WORKDIR /app
# Overlay sources; nested node_modules must be dockerignored so they do not
# replace the install from the dependencies stage with host pnpm symlinks.
COPY apps/web ./apps/web
COPY packages/convex ./packages/convex
# Re-apply the install tree after source COPY so module resolution cannot be
# clobbered even if a nested node_modules slips into the build context.
COPY --from=dependencies /app/node_modules ./node_modules
COPY --from=dependencies /app/apps/web/node_modules ./apps/web/node_modules
COPY --from=dependencies /app/packages/convex/node_modules ./packages/convex/node_modules
ENV NODE_ENV=production
ARG NEXT_PUBLIC_CONVEX_URL
WORKDIR /app/apps/web
RUN --mount=type=cache,target=/app/apps/web/.next/cache \
corepack enable pnpm && pnpm build
# ============================================
# Stage 3: Run Next.js application
# ============================================
FROM runner-base AS runner
WORKDIR /app
# Set production environment variables
ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
# 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 mkdir /data
# Copy production assets
COPY --from=builder --chown=node:node /app/public ./public
COPY --from=builder --chown=node:node /app/apps/web/public ./apps/web/public
COPY --from=builder --chown=node:node /app/apps/web/.next/standalone ./
COPY --from=builder --chown=node:node /app/apps/web/.next/static ./apps/web/.next/static
# Set the correct permission for prerender cache
RUN mkdir .next
RUN chown node:node .next
RUN mkdir -p apps/web/.next && chown -R node:node apps/web/.next
# 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
# 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
# Switch to non-root user for security best practices
USER node
# Expose port 3000 to allow HTTP traffic
EXPOSE 3000
# Start Next.js standalone server
CMD ["node", "server.js"]
CMD ["node", "apps/web/server.js"]
+53 -1
View File
@@ -2,6 +2,53 @@
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
```
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:
@@ -19,7 +66,12 @@ services:
- 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
image: otunes
build:
context: .
dockerfile: Dockerfile
args:
- NEXT_PUBLIC_CONVEX_URL=http://127.0.0.1:3210
backend:
stop_grace_period: 10s
stop_signal: SIGINT
-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} />
}
-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}
/>
)
}
-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} />
}
-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} />
}
-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

+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
+81
View File
@@ -0,0 +1,81 @@
{
"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"
],
"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,34 @@
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 === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
})}
/>
)
}
@@ -0,0 +1,270 @@
import { useQuery } from "convex/react"
import { Stack, useLocalSearchParams } from "expo-router"
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
import { Ionicons } from "@expo/vector-icons"
import { CoverImage } from "@/components/cover-image"
import {
MediaActionMenu,
MediaContextMenu,
} from "@/components/media-actions-sheet"
import { Button, LoadingView } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { useCoverBackgroundColor } from "@/hooks/use-cover-background-color"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseAlbumTrack } from "@otunes/convex/types"
import { formatDuration, formatMetadata } from "@/lib/format"
import { useAppNavigation } from "@/lib/app-navigation"
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 = useQuery(
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 coverUri =
config && album ? albumCoverUrl(config.serverUrl, album.id) : ""
const backgroundColor = useCoverBackgroundColor(
coverUri,
album?.cover != null,
colors.background
)
if (album === undefined || !config) {
return (
<>
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
}}
/>
<LoadingView />
</>
)
}
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 songIds = album.tracks.map(
(track: BrowseAlbumTrack) => track.id as Id<"songs">
)
const metadata = formatMetadata(album.genre, album.year)
return (
<>
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
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={colors.foreground}
/>
</Pressable>
</MediaActionMenu>
),
}}
/>
<FlatList
data={album.tracks}
keyExtractor={(track) => track.id}
style={{ flex: 1, backgroundColor }}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
ListHeaderComponent={
<View style={styles.hero}>
<CoverImage
uri={coverUri}
hasCover={album.cover != null}
style={styles.cover}
/>
<Text style={[styles.title, { color: colors.foreground }]}>
{album.title}
</Text>
<Pressable onPress={() => push(`/artist/${album.artist.id}`)}>
<Text style={[styles.artist, { color: colors.mutedForeground }]}>
{album.artist.name}
</Text>
</Pressable>
{metadata ? (
<Text style={{ color: colors.mutedForeground }}>{metadata}</Text>
) : null}
<View style={styles.actions}>
<Pressable
onPress={() => void toggleAlbumFavorite(album.id)}
hitSlop={8}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
>
<Ionicons
name={isAlbumFavorite(album.id) ? "star" : "star-outline"}
size={24}
color={
isAlbumFavorite(album.id)
? colors.primary
: colors.foreground
}
/>
</Pressable>
<Button
title="Play"
icon="play"
onPress={() => void playAlbum(album.id)}
style={styles.playButton}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() => void playAlbumShuffled(album.id)}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
</View>
</View>
}
renderItem={({ item: track, index }) => (
<MediaContextMenu
favorited={isSongFavorite(track.id)}
navigation={{
artist: { id: album.artist.id },
album: { id: album.id },
}}
share={{
type: "song",
albumId: album.id,
songId: track.id,
}}
onAction={(action) =>
void handleAlbumTrackAction(track, album, action)
}
>
<Pressable
style={[styles.trackRow, { borderBottomColor: colors.border }]}
onPress={() => void playFromSong(track.id, songIds)}
>
<Text
style={[styles.trackNumber, { color: colors.mutedForeground }]}
>
{track.track || index + 1}
</Text>
<View style={styles.trackMeta}>
<Text
style={[styles.trackTitle, { color: colors.foreground }]}
numberOfLines={1}
>
{track.title}
</Text>
{track.artists ? (
<Text
style={{ color: colors.mutedForeground }}
numberOfLines={1}
>
{track.artists.join(", ")}
</Text>
) : null}
</View>
<Text style={{ color: colors.mutedForeground }}>
{formatDuration(track.durationSeconds)}
</Text>
</Pressable>
</MediaContextMenu>
)}
/>
</>
)
}
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,171 @@
import { useQuery } from "convex/react"
import { Stack, useLocalSearchParams } from "expo-router"
import { Pressable, StyleSheet, Text, View } from "react-native"
import { Ionicons } from "@expo/vector-icons"
import { CoverImage } from "@/components/cover-image"
import { MediaGridList } from "@/components/media-cards"
import { MediaActionMenu } from "@/components/media-actions-sheet"
import { Button, LoadingView } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { 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 = useQuery(
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,
}}
/>
<LoadingView />
</>
)
}
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,67 @@
import { usePaginatedQuery, useQuery } from "convex/react"
import { Stack } from "expo-router"
import { useCallback } from "react"
import { MediaGridList } from "@/components/media-cards"
import { LoadingView } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player"
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 } = usePaginatedQuery(
api.library.browseAlbumsPaginated,
{},
{ initialNumItems: PAGE_SIZE }
)
const searchResults = useQuery(
api.library.searchLibrary,
searchQuery ? { query: searchQuery } : "skip"
)
const albums = searchQuery ? searchResults?.albums : 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}
<LoadingView />
</>
)
}
return (
<>
{searchBar}
<MediaGridList
content={albums}
paddingBottom={contentBottomInset}
onEndReached={() => {
if (!searchQuery && status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
/>
</>
)
}
@@ -0,0 +1,126 @@
import { Ionicons } from "@expo/vector-icons"
import { usePaginatedQuery, useQuery } from "convex/react"
import { Stack } from "expo-router"
import { useCallback } from "react"
import { FlatList, Pressable, StyleSheet, Text } from "react-native"
import { MediaContextMenu } from "@/components/media-context-menu"
import { CoverImage } from "@/components/cover-image"
import { LoadingView } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player"
import { useServerConfig } from "@/contexts/server-config"
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 { 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 } = usePaginatedQuery(
api.library.browseArtistsPaginated,
{},
{ initialNumItems: PAGE_SIZE }
)
const searchResults = useQuery(
api.library.searchLibrary,
searchQuery ? { query: searchQuery } : "skip"
)
const { handleArtistAction, isArtistFavorite } = useMediaMenuActions()
const artists = searchQuery ? searchResults?.artists : 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 (artists === undefined || !config) {
return (
<>
{searchBar}
<LoadingView />
</>
)
}
return (
<>
{searchBar}
<FlatList
data={artists}
keyExtractor={(artist) => artist.id}
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
onEndReached={() => {
if (!searchQuery && status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
onEndReachedThreshold={0.5}
renderItem={({ item: artist }: { item: BrowseArtist }) => (
<MediaContextMenu
favorited={isArtistFavorite(artist.id)}
share={{ type: "artist", artistId: artist.id }}
onAction={(action) => void handleArtistAction(artist, action)}
>
<Pressable
style={[styles.row, { borderBottomColor: colors.border }]}
onPress={() => push(`/artist/${artist.id}`)}
>
<CoverImage
uri={artistCoverUrl(config.serverUrl, artist.id)}
hasCover={artist.photo != null}
style={styles.avatar}
/>
<Text
style={[styles.name, { color: colors.foreground }]}
numberOfLines={1}
>
{artist.name}
</Text>
<Ionicons name="chevron-forward" size={16} color={colors.mutedForeground} />
</Pressable>
</MediaContextMenu>
)}
/>
</>
)
}
const styles = StyleSheet.create({
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 { useQuery } from "convex/react"
import { Pressable } from "react-native"
import { MediaGridList } from "@/components/media-cards"
import { LoadingView } from "@/components/ui/primitives"
import { tabContentBottomInset } from "@/components/player"
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 = useQuery(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>
),
}}
/>
<LoadingView />
</>
)
}
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,115 @@
import { usePaginatedQuery, useQuery } from "convex/react"
import { Stack } from "expo-router"
import { useCallback, useState } from "react"
import { FlatList, StyleSheet } from "react-native"
import { contentBottomInset, SongRow } from "@/components/player"
import { LoadingView } from "@/components/ui/primitives"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback"
import { useDebouncedSearch } from "@/hooks/use-debounced-search"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { spacing } from "@/lib/theme"
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 } = usePaginatedQuery(
api.library.browseSongsPaginated,
{ sortKey, sortDirection },
{ initialNumItems: PAGE_SIZE }
)
const searchResults = useQuery(
api.library.searchLibrary,
searchQuery ? { query: searchQuery } : "skip"
)
const songs = searchQuery ? searchResults?.songs : 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 (songs === undefined) {
return (
<>
{searchBar}
<LoadingView />
</>
)
}
return (
<>
{searchBar}
<FlatList
data={songs}
keyExtractor={(item) => item.id}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
onEndReached={() => {
if (!searchQuery && status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
onEndReachedThreshold={0.5}
renderItem={({ item }) => (
<SongRow
song={item}
onPress={() =>
void playFromLibrarySong(item.id as Id<"songs">, {
sortKey,
sortDirection,
})
}
contextMenu={{
favorited: isSongFavorite(item.id),
navigation: {
artist: { id: item.artist.id },
album: { id: item.album.id },
},
share: {
type: "song",
albumId: item.album.id,
songId: item.id,
},
onAction: (action) => void handleSongAction(item, action),
}}
/>
)}
/>
</>
)
}
const styles = StyleSheet.create({
sortRow: {
flexDirection: "row",
justifyContent: "space-around",
paddingVertical: spacing.sm,
borderBottomWidth: StyleSheet.hairlineWidth,
},
sortButton: { padding: spacing.sm },
})
@@ -0,0 +1,86 @@
import { usePaginatedQuery } from "convex/react"
import { memo, useRef } from "react"
import { ScrollView, StyleSheet } from "react-native"
import { ContentCarousel } from "@/components/media-cards"
import { LoadingView } from "@/components/ui/primitives"
import { tabContentBottomInset } from "@/components/player"
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 { results: recentlyAdded } = usePaginatedQuery(
api.library.browseRecentlyAddedPaginated,
{},
{ initialNumItems: CAROUSEL_ITEM_LIMIT }
)
const { results: recentlyPlayed } = usePaginatedQuery(
api.library.browseRecentlyPlayedPaginated,
{},
{ initialNumItems: CAROUSEL_ITEM_LIMIT }
)
const cachedData = useRef<{
recentlyAdded?: BrowseAlbum[]
recentlyPlayed?: (BrowseAlbum | PlaylistSummary)[]
}>({})
if (recentlyAdded !== undefined) {
cachedData.current.recentlyAdded = recentlyAdded
}
if (recentlyPlayed !== undefined) {
cachedData.current.recentlyPlayed = recentlyPlayed
}
const added = recentlyAdded ?? cachedData.current.recentlyAdded
const played = recentlyPlayed ?? cachedData.current.recentlyPlayed
if (added === undefined || played === undefined) {
return <LoadingView />
}
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,583 @@
import { useMutation, usePaginatedQuery, useQuery } from "convex/react"
import {
Button as SwiftUIButton,
ContextMenu,
Host,
List,
RNHostView,
SwipeActions,
} from "@expo/ui/swift-ui"
import {
frame,
listRowBackground,
listRowInsets,
listRowSeparator,
listSectionSpacing,
listRowSpacing,
listStyle,
onAppear,
scrollContentBackground,
} from "@expo/ui/swift-ui/modifiers"
import { Stack, useLocalSearchParams, useRouter } from "expo-router"
import {
FlatList,
Platform,
Pressable,
StyleSheet,
Text,
View,
} from "react-native"
import ReanimatedSwipeable from "react-native-gesture-handler/ReanimatedSwipeable"
import { Ionicons } from "@expo/vector-icons"
import { CoverImage } from "@/components/cover-image"
import {
MediaActionMenu,
type MediaAction,
} from "@/components/media-actions-sheet"
import { Button, LoadingView } from "@/components/ui/primitives"
import { contentBottomInset, SongRow } from "@/components/player"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { useCoverBackgroundColor } from "@/hooks/use-cover-background-color"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong } from "@otunes/convex/types"
import { shareMediaLink } from "@/lib/share-media-link"
import { showError, showSuccess } from "@/lib/toast"
import { playlistCoverUrl } from "@/lib/urls"
import { radius, spacing, useThemeColors } from "@/lib/theme"
const PAGE_SIZE = 50
const NATIVE_LOAD_MORE_THRESHOLD = 10
export default function PlaylistScreen() {
const { id } = useLocalSearchParams<{ id: string }>()
const router = useRouter()
const colors = useThemeColors()
const { config } = useServerConfig()
const playlistId = typeof id === "string" ? (id as Id<"playlists">) : null
const playlist = useQuery(
api.playlists.browsePlaylistDetail,
playlistId
? {
id: playlistId,
includeSongs: false,
}
: "skip"
)
const {
results: songs,
status,
loadMore,
} = usePaginatedQuery(
api.playlists.browsePlaylistSongsPaginated,
playlistId ? { id: playlistId } : "skip",
{ initialNumItems: PAGE_SIZE }
)
const allSongIds = useQuery(
api.playlists.getPlaylistSongIds,
playlistId ? { playlistId } : "skip"
)
const { playPlaylist, playPlaylistShuffled, playFromSong } =
usePlaybackActions()
const { isSongFavorite } = useFavorites()
const { handleSongAction, handlePlaylistDetailAction } = useMediaMenuActions()
const subscribe = useMutation(api.playlists.subscribeToPlaylist)
const unsubscribe = useMutation(api.playlists.unsubscribeFromPlaylist)
const deletePlaylist = useMutation(api.playlists.deletePlaylist)
const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist)
const coverUri =
config && playlist
? playlistCoverUrl(config.serverUrl, playlist.id ?? "favorites")
: ""
const backgroundColor = useCoverBackgroundColor(
coverUri,
playlist?.cover != null,
colors.background
)
if (
playlist === undefined ||
songs === undefined ||
allSongIds === undefined ||
!config
) {
return (
<>
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
}}
/>
<LoadingView />
</>
)
}
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>
</>
)
}
const songIds = allSongIds
const serverUrl = config.serverUrl
function maybeLoadMore() {
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
}
async function handleSubscribeToggle() {
if (!playlist?.id) return
try {
if (playlist.isSubscribed) {
await unsubscribe({ playlistId: playlist.id })
showSuccess("Unsubscribed")
} else {
await subscribe({ playlistId: playlist.id })
showSuccess("Subscribed")
}
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to update subscription"
)
}
}
async function handleDelete() {
if (!playlist?.id) return
try {
await deletePlaylist({ playlistId: playlist.id })
showSuccess("Playlist deleted")
router.back()
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to delete playlist"
)
}
}
function handlePlaylistMenuAction(action: MediaAction) {
if (action === "delete-playlist") {
void handleDelete()
return
}
void handlePlaylistDetailAction(songIds, action)
}
async function handleRemoveSong(songId: Id<"songs">) {
if (!playlist?.id) return
try {
await removeSongs({ playlistId: playlist.id, songIds: [songId] })
showSuccess("Removed from playlist")
} catch (error) {
showError(
error instanceof Error
? error.message
: "Failed to remove from playlist"
)
}
}
function renderSongRow(song: BrowseSong, includeContextMenu = true) {
const row = (
<SongRow
song={song}
onPress={() => void playFromSong(song.id, songIds)}
contextMenu={
includeContextMenu
? {
favorited: isSongFavorite(song.id),
playlistLabel: "Add to Another Playlist",
navigation: {
artist: { id: song.artist.id },
album: { id: song.album.id },
},
share: {
type: "song",
albumId: song.album.id,
songId: song.id,
},
onAction: (action) => void handleSongAction(song, action),
}
: undefined
}
/>
)
return row
}
function renderNativeSongContextMenu(song: BrowseSong) {
return (
<ContextMenu.Items>
<SwiftUIButton
label="Share"
systemImage="square.and.arrow.up"
onPress={() =>
void shareMediaLink(serverUrl, {
type: "song",
albumId: song.album.id,
songId: song.id,
})
}
/>
<SwiftUIButton
label="Add to Another Playlist"
systemImage="text.badge.plus"
onPress={() => void handleSongAction(song, "playlist")}
/>
<SwiftUIButton
label="Play Next"
systemImage="text.line.first.and.arrowtriangle.forward"
onPress={() => void handleSongAction(song, "play-next")}
/>
<SwiftUIButton
label="Play Last"
systemImage="text.line.last.and.arrowtriangle.forward"
onPress={() => void handleSongAction(song, "play-last")}
/>
<SwiftUIButton
label="Shuffle"
systemImage="shuffle"
onPress={() => void handleSongAction(song, "shuffle")}
/>
<SwiftUIButton
label="Go to Artist"
systemImage="person"
onPress={() => void handleSongAction(song, "go-artist")}
/>
<SwiftUIButton
label="Go to Album"
systemImage="opticaldisc"
onPress={() => void handleSongAction(song, "go-album")}
/>
<SwiftUIButton
label={isSongFavorite(song.id) ? "Unfavorite" : "Favorite"}
systemImage={isSongFavorite(song.id) ? "star.fill" : "star"}
onPress={() => void handleSongAction(song, "favorite")}
/>
</ContextMenu.Items>
)
}
const nativeListRowModifiers = [
listRowBackground(backgroundColor),
listRowInsets({ top: 0, leading: 0, bottom: 0, trailing: 0 }),
listRowSeparator("hidden"),
]
const nativeSongRowModifiers = [frame({ height: 32 })]
const shouldUseNativeSwipeList =
Platform.OS === "ios" && playlist.isOwner && playlist.id
return (
<>
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
headerRight: () => (
<MediaActionMenu
selectedCount={songIds.length}
playlistLabel="Add to Another Playlist"
share={{
type: "playlist",
playlistId: playlist.id ?? "favorites",
}}
includeActions={
playlist.isOwner && playlist.id
? [
"share",
"playlist",
"play-next",
"play-last",
"shuffle",
"favorite",
"delete-playlist",
]
: undefined
}
onAction={handlePlaylistMenuAction}
>
<Pressable hitSlop={8}>
<Ionicons
name="ellipsis-horizontal"
size={22}
color={colors.foreground}
/>
</Pressable>
</MediaActionMenu>
),
}}
/>
{shouldUseNativeSwipeList ? (
<Host style={[styles.iosSwipeListHost, { backgroundColor }]}>
<List
modifiers={[
listStyle("plain"),
listSectionSpacing(0),
listRowSpacing(0),
scrollContentBackground("hidden"),
]}
>
<SwipeActions modifiers={nativeListRowModifiers}>
<RNHostView matchContents>
<PlaylistHero
coverUri={coverUri}
hasCover={playlist.cover != null}
title={playlist.title}
ownerName={playlist.owner.name}
colors={colors}
onPlay={() => playlist.id && void playPlaylist(playlist.id)}
onShuffle={() =>
playlist.id && void playPlaylistShuffled(playlist.id)
}
/>
</RNHostView>
</SwipeActions>
{songs.map((song, index) => {
const nearEnd = index >= songs.length - NATIVE_LOAD_MORE_THRESHOLD
return (
<SwipeActions
key={song.id}
modifiers={[
...nativeSongRowModifiers,
...(nearEnd ? [onAppear(maybeLoadMore)] : []),
]}
>
<ContextMenu>
<ContextMenu.Trigger>
<RNHostView matchContents>
<View style={styles.nativeSongRow}>
{renderSongRow(song, false)}
</View>
</RNHostView>
</ContextMenu.Trigger>
{renderNativeSongContextMenu(song)}
</ContextMenu>
<SwipeActions.Actions edge="trailing">
<SwiftUIButton
label=""
systemImage="minus.circle.fill"
role="destructive"
onPress={() => void handleRemoveSong(song.id)}
/>
</SwipeActions.Actions>
</SwipeActions>
)
})}
</List>
</Host>
) : (
<FlatList
data={songs}
keyExtractor={(song) => song.id}
style={{ flex: 1, backgroundColor }}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
onEndReached={maybeLoadMore}
onEndReachedThreshold={0.5}
ListHeaderComponent={
<PlaylistHero
coverUri={coverUri}
hasCover={playlist.cover != null}
title={playlist.title}
ownerName={playlist.owner.name}
colors={colors}
isSubscribed={playlist.isSubscribed}
showSubscribe={!playlist.isOwner && !!playlist.id}
onSubscribeToggle={() => void handleSubscribeToggle()}
onPlay={() => playlist.id && void playPlaylist(playlist.id)}
onShuffle={() =>
playlist.id && void playPlaylistShuffled(playlist.id)
}
/>
}
renderItem={({ item: song }) => {
const row = renderSongRow(song)
if (!playlist.isOwner || !playlist.id) {
return <View>{row}</View>
}
return (
<ReanimatedSwipeable
friction={2}
rightThreshold={56}
overshootRight={false}
enableTrackpadTwoFingerGesture
containerStyle={{ backgroundColor: colors.destructive }}
childrenContainerStyle={{ backgroundColor }}
renderRightActions={(_progress, _translation, swipeable) => (
<Pressable
accessibilityRole="button"
accessibilityLabel={`Remove ${song.title} from playlist`}
onPress={() => {
swipeable.close()
void handleRemoveSong(song.id)
}}
style={[
styles.removeAction,
{ backgroundColor: colors.destructive },
]}
>
<Ionicons
name="trash"
size={22}
color={colors.primaryForeground}
/>
<Text
style={[
styles.removeActionText,
{ color: colors.primaryForeground },
]}
>
Remove
</Text>
</Pressable>
)}
>
{row}
</ReanimatedSwipeable>
)
}}
/>
)}
</>
)
}
function PlaylistHero({
coverUri,
hasCover,
title,
ownerName,
colors,
isSubscribed,
showSubscribe = false,
onSubscribeToggle,
onPlay,
onShuffle,
}: {
coverUri: string
hasCover: boolean
title: string
ownerName: string
colors: ReturnType<typeof useThemeColors>
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: colors.foreground }]}>{title}</Text>
<Text style={{ color: colors.mutedForeground }}>{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 ? colors.muted : colors.primary,
},
]}
>
<Ionicons
name={isSubscribed ? "checkmark" : "add"}
size={24}
color={
isSubscribed ? colors.foreground : colors.primaryForeground
}
/>
</Pressable>
) : null}
<Button
title="Play"
icon="play"
onPress={onPlay}
style={styles.playButton}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={onShuffle}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
</View>
</View>
)
}
const styles = StyleSheet.create({
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
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",
},
iosSwipeListHost: {
flex: 1,
alignSelf: "stretch",
width: "100%",
},
nativeSongRow: {
height: 64,
overflow: "hidden",
},
removeAction: {
width: 96,
alignItems: "center",
justifyContent: "center",
gap: spacing.xs,
},
removeActionText: {
fontSize: 12,
fontWeight: "600",
},
})
@@ -0,0 +1,158 @@
import { useQuery } from "convex/react"
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
import { Button, LoadingView } from "@/components/ui/primitives"
import { contentBottomInset, SongRow } from "@/components/player"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api"
import type { BrowseSong } from "@otunes/convex/types"
import { radius, spacing, useThemeColors } from "@/lib/theme"
import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router"
export default function FavoritesScreen() {
const colors = useThemeColors()
const { config } = useServerConfig()
const favorites = useQuery(api.favorites.browseFavoritesPlaylistDetail)
const { playInOrder, playShuffled, playFromSong } = usePlaybackActions()
const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions()
if (favorites === undefined || !config) {
return (
<>
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
}}
/>
<LoadingView />
</>
)
}
if (favorites === null) {
return (
<>
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
}}
/>
<View style={[styles.empty, { backgroundColor: colors.background }]}>
<Text style={{ color: colors.mutedForeground }}>
Sign in to view your favorites.
</Text>
</View>
</>
)
}
const songIds = favorites.songs.map((song: BrowseSong) => song.id)
return (
<>
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
}}
/>
<FlatList
data={favorites.songs}
keyExtractor={(song) => song.id}
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
ListHeaderComponent={
<View style={styles.hero}>
<View
style={[
styles.cover,
{
backgroundColor: colors.coverPlaceholder,
alignItems: "center",
justifyContent: "center",
overflow: "hidden",
},
]}
>
<Ionicons name="star" size={120} color={colors.primary} />
</View>
<Text style={[styles.title, { color: colors.foreground }]}>
{favorites.title}
</Text>
<View style={styles.actions}>
<Button
title="Play"
icon="play"
onPress={() => void playInOrder(songIds)}
style={styles.playButton}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() => void playShuffled(songIds)}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
</View>
</View>
}
renderItem={({ item: song }: { item: BrowseSong }) => (
<SongRow
song={song}
onPress={() => void playFromSong(song.id, songIds)}
contextMenu={{
favorited: isSongFavorite(song.id),
playlistLabel: "Add to Another Playlist",
navigation: {
artist: { id: song.artist.id },
album: { id: song.album.id },
},
share: {
type: "song",
albumId: song.album.id,
songId: song.id,
},
onAction: (action) => void handleSongAction(song, action),
}}
/>
)}
/>
</>
)
}
const styles = StyleSheet.create({
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
hero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm },
cover: {
width: 200,
height: 200,
borderRadius: radius.lg,
},
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",
},
})
+171
View File
@@ -0,0 +1,171 @@
import { usePaginatedQuery, useQuery } from "convex/react"
import { Stack, useRouter } from "expo-router"
import { useState } from "react"
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
import { Button, LoadingView } from "@/components/ui/primitives"
import { contentBottomInset, SongRow } from "@/components/player"
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
import { api } from "@otunes/convex/_generated/api"
import type { BrowseSong } from "@otunes/convex/types"
import { spacing, useThemeColors } from "@/lib/theme"
import { showError } from "@/lib/toast"
const PAGE_SIZE = 50
export default function QueueScreen() {
const router = useRouter()
const colors = useThemeColors()
const { queueSongIds, currentSong } = usePlaybackQueue()
const { skipToQueueIndex, clearQueue, reorderQueue } = usePlaybackActions()
const [reordering, setReordering] = useState(false)
const queueVersion = queueSongIds.length
? `${queueSongIds.length}:${queueSongIds[0]}:${queueSongIds[queueSongIds.length - 1]}`
: "empty"
const {
results: queueSongs,
status,
loadMore,
} = usePaginatedQuery(
api.playback.getQueuePaginated,
queueSongIds.length > 0 ? { queueVersion } : "skip",
{ initialNumItems: PAGE_SIZE }
)
const historySongs = useQuery(api.playback.getQueueHistory)
async function moveSong(fromIndex: number, direction: -1 | 1) {
if (reordering) return
const toIndex = fromIndex + direction
if (toIndex < 0 || toIndex >= queueSongIds.length) return
const next = [...queueSongIds]
const [item] = next.splice(fromIndex, 1)
next.splice(toIndex, 0, item)
setReordering(true)
try {
await reorderQueue(next)
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to reorder queue"
)
} finally {
setReordering(false)
}
}
function handleClearQueue() {
if (router.canGoBack()) {
router.back()
setTimeout(() => {
void clearQueue()
}, 0)
return
}
void clearQueue()
}
if (queueSongIds.length > 0 && queueSongs === undefined) {
return <LoadingView />
}
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>
}
data={queueSongs ?? []}
keyExtractor={(item) => `${item.id}-${item.queueIndex}`}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
onEndReached={() => {
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
renderItem={({ item }) => (
<View>
<SongRow
song={item}
onPress={() => void skipToQueueIndex(item.queueIndex)}
/>
<View style={styles.queueActions}>
<Pressable
disabled={reordering || item.queueIndex === 0}
onPress={() => void moveSong(item.queueIndex, -1)}
>
<Text style={{ color: colors.foreground }}>Move up</Text>
</Pressable>
<Pressable
disabled={
reordering || item.queueIndex === queueSongIds.length - 1
}
onPress={() => void moveSong(item.queueIndex, 1)}
>
<Text style={{ color: colors.foreground }}>Move down</Text>
</Pressable>
{currentSong?.id === item.id ? (
<Text style={{ color: colors.primary, fontWeight: "700" }}>
Now playing
</Text>
) : null}
</View>
</View>
)}
ListFooterComponent={
historySongs && historySongs.length > 0 ? (
<View style={styles.history}>
<Text style={[styles.section, { color: colors.mutedForeground }]}>
History
</Text>
{historySongs.map((song: BrowseSong) => (
<SongRow key={song.id} song={song} />
))}
</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,30 @@
import { usePaginatedQuery } from "convex/react"
import { MediaGridList } from "@/components/media-cards"
import { LoadingView } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player"
import { api } from "@otunes/convex/_generated/api"
const PAGE_SIZE = 16
export default function RecentlyAddedScreen() {
const { results, status, loadMore } = usePaginatedQuery(
api.library.browseRecentlyAddedPaginated,
{},
{ initialNumItems: PAGE_SIZE }
)
if (results === undefined) {
return <LoadingView />
}
return (
<MediaGridList
content={results}
paddingBottom={contentBottomInset}
onEndReached={() => {
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
/>
)
}
@@ -0,0 +1,30 @@
import { usePaginatedQuery } from "convex/react"
import { MediaGridList } from "@/components/media-cards"
import { LoadingView } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player"
import { api } from "@otunes/convex/_generated/api"
const PAGE_SIZE = 50
export default function RecentlyPlayedScreen() {
const { results, status, loadMore } = usePaginatedQuery(
api.library.browseRecentlyPlayedPaginated,
{},
{ initialNumItems: PAGE_SIZE }
)
if (results === undefined) {
return <LoadingView />
}
return (
<MediaGridList
content={results}
paddingBottom={contentBottomInset}
onEndReached={() => {
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
/>
)
}
@@ -0,0 +1,885 @@
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 { 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 = useQuery(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 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="Prevent new users from creating accounts."
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,34 @@
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 === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
})}
/>
)
}
@@ -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 { usePaginatedQuery } from "convex/react"
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 { LoadingView } from "@/components/ui/primitives"
import { useAppNavigation } from "@/lib/app-navigation"
import { api } from "@otunes/convex/_generated/api"
import { appleMusic, spacing, useThemeColors } from "@/lib/theme"
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 } = usePaginatedQuery(
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 (results === undefined) {
return (
<View style={{ flex: 1, backgroundColor: colors.background }}>
{listHeader}
<LoadingView />
</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,34 @@
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 === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
})}
/>
)
}
@@ -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"
+97
View File
@@ -0,0 +1,97 @@
import { useConvexAuth as useLocalConvexAuth } from "@convex-dev/auth/react"
import { useConvexAuth as useServerConvexAuth } 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 { invalidateSession } = useInvalidateAuthSession()
const stackOptions = useStackScreenOptions()
useEffect(() => {
if (!localAuth?.isAuthenticated || serverAuth?.isAuthenticated) {
return
}
const timer = setTimeout(() => {
void invalidateSession()
}, AUTH_HANDSHAKE_TIMEOUT_MS)
return () => clearTimeout(timer)
}, [
invalidateSession,
localAuth?.isAuthenticated,
serverAuth?.isAuthenticated,
])
if (!config) {
return <Redirect href="/server" />
}
if (!localAuth || localAuth.isLoading) {
return <LoadingView />
}
if (!localAuth.isAuthenticated) {
return <Redirect href="/signin" />
}
if (!serverAuth || serverAuth.isLoading || serverAuth.isRefreshing) {
return <LoadingView />
}
if (!serverAuth.isAuthenticated) {
return <LoadingView />
}
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" />
}
+381
View File
@@ -0,0 +1,381 @@
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()
useEffect(() => {
if (currentSong) {
hadSongRef.current = true
return
}
if (hadSongRef.current) {
router.back()
}
}, [currentSong, 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 }} />
}
+5
View File
@@ -0,0 +1,5 @@
import { AuthForm } from "@/components/auth-form"
export default function SignInScreen() {
return <AuthForm flow="signIn" />
}
+5
View File
@@ -0,0 +1,5 @@
import { AuthForm } from "@/components/auth-form"
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,114 @@
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 { 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()
}
}
render() {
const { error } = this.state
if (error) {
if (shouldInvalidateAuthSession(error, this.props.sessionEstablished)) {
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>
)
}
+105
View File
@@ -0,0 +1,105 @@
import { Ionicons } from "@expo/vector-icons"
import { Image, type ImageContentFit, type ImageStyle } from "expo-image"
import { memo } 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
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) * PixelRatio.get()
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
}
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 = StyleSheet.flatten(style) ?? {}
if (!hasCover) {
const placeholderStyle: ViewStyle = {
backgroundColor: colors.coverPlaceholder,
alignItems: "center",
justifyContent: "center",
overflow: "hidden",
}
return (
<View style={[style, placeholderStyle]}>
{placeholderVariant === "icon" ? (
<Ionicons
name="musical-note"
size={placeholderIconSize(flatStyle)}
color={colors.coverPlaceholderIcon}
/>
) : null}
</View>
)
}
const sourceUri = withCoverImageSize(uri, sourceSize(flatStyle))
return (
<Image
source={{ uri: sourceUri }}
style={[style, { backgroundColor: colors.coverPlaceholder }]}
contentFit={contentFit}
transition={150}
blurRadius={blurRadius}
cachePolicy="memory-disk"
recyclingKey={sourceUri}
enforceEarlyResizing
/>
)
})
@@ -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"
+334
View File
@@ -0,0 +1,334 @@
import { Ionicons } from "@expo/vector-icons"
import { memo, useCallback, type ReactElement } from "react"
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
import { CoverImage } from "@/components/cover-image"
import { MediaContextMenu } from "@/components/media-context-menu"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { useServerConfig } from "@/contexts/server-config"
import { useAppNavigation } from "@/lib/app-navigation"
import 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
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()
return (
<FlatList
data={content}
keyExtractor={(item) => item.id}
numColumns={2}
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}
renderItem={({ item }) => (
<View style={{ width: cardWidth }}>
<CarouselCard item={item} width={cardWidth} />
</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={(item) => item.id}
horizontal
showsHorizontalScrollIndicator={false}
contentContainerStyle={styles.carouselContent}
renderItem={({ item }) => (
<View>
<CarouselCard item={item} width={carouselCardWidth} />
</View>
)}
/>
</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,201 @@
import { MenuView, type MenuAction } from "@expo/ui/community/menu"
import type { ReactNode } from "react"
import type { StyleProp, ViewStyle } from "react-native"
import { useServerConfig } from "@/contexts/server-config"
import type { MediaShareContext } from "@/lib/media-links"
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>
)
}
export function MediaContextMenu(props: MediaMenuWrapperProps) {
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 }
+106
View File
@@ -0,0 +1,106 @@
import { CoverImage } from "@/components/cover-image"
import { useServerConfig } from "@/contexts/server-config"
import type { BrowseSong } from "@otunes/convex/types"
import { formatDuration } from "@/lib/format"
import { albumCoverUrl } from "@/lib/urls"
import {
miniPlayerHeight,
spacing,
tabBarHeight,
useThemeColors,
} from "@/lib/theme"
import { Pressable, StyleSheet, Text, View } from "react-native"
import {
MediaContextMenu,
type MediaMenuConfig,
} from "@/components/media-context-menu"
export function SongRow({
song,
onPress,
contextMenu,
trailing,
}: {
song: BrowseSong
onPress?: () => void
contextMenu?: Omit<MediaMenuConfig, "onAction"> & {
onAction: MediaMenuConfig["onAction"]
}
trailing?: React.ReactNode
}) {
const { config } = useServerConfig()
const colors = useThemeColors()
if (!config) return null
const row = (
<Pressable
style={[styles.row, { borderBottomColor: 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: colors.foreground }]} numberOfLines={1}>
{song.title}
</Text>
<Text style={[styles.rowSubtitle, { color: colors.mutedForeground }]} numberOfLines={1}>
{song.artist.name} · {song.album.title}
</Text>
</View>
<Text style={[styles.duration, { color: colors.mutedForeground }]}>
{formatDuration(song.durationSeconds)}
</Text>
{trailing}
</Pressable>
)
if (!contextMenu) {
return row
}
return (
<MediaContextMenu {...contextMenu}>
{row}
</MediaContextMenu>
)
}
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 { useQuery } from "convex/react"
import { Image } from "expo-image"
import { useRouter } from "expo-router"
import { Pressable, StyleSheet, Text, View } from "react-native"
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 = useQuery(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",
},
})
+132
View File
@@ -0,0 +1,132 @@
import { useQuery } from "convex/react"
import { memo, useMemo } from "react"
import { FlatList, StyleSheet, Text, View } from "react-native"
import { ContentCarousel } from "@/components/media-cards"
import { tabContentBottomInset, SongRow } from "@/components/player"
import { LoadingView } from "@/components/ui/primitives"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback"
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 = useQuery(
api.library.searchLibrary,
hasQuery ? { query: searchQuery } : "skip"
)
const playlistResults = useQuery(
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]
)
if (isSearching) {
return <LoadingView />
}
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={({ item: song }: { item: BrowseSong }) => (
<SongRow
song={song}
onPress={() => void playFromSong(song.id, songIds)}
contextMenu={{
favorited: isSongFavorite(song.id),
navigation: {
artist: { id: song.artist.id },
album: { id: song.album.id },
},
share: {
type: "song",
albumId: song.album.id,
songId: song.id,
},
onAction: (action) => void handleSongAction(song, action),
}}
/>
)}
ListFooterComponent={
playlistResults && playlistResults.length > 0 ? (
<View style={styles.section}>
<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,
},
})
+153
View File
@@ -0,0 +1,153 @@
import {
ActivityIndicator,
Pressable,
PressableProps,
StyleProp,
StyleSheet,
Text,
TextInput,
TextInputProps,
View,
ViewStyle,
} from "react-native"
import { Ionicons } from "@expo/vector-icons"
import { radius, spacing, useThemeColors } from "@/lib/theme"
type ButtonProps = Omit<PressableProps, "style"> & {
title: string
variant?: "primary" | "secondary" | "ghost" | "destructive"
loading?: boolean
icon?: React.ComponentProps<typeof Ionicons>["name"]
style?: StyleProp<ViewStyle>
}
export function Button({
title,
variant = "primary",
loading = false,
disabled,
icon,
style,
...props
}: ButtonProps) {
const colors = useThemeColors()
const isDisabled = disabled || loading
const backgroundColor =
variant === "primary"
? colors.primary
: variant === "secondary"
? colors.muted
: variant === "destructive"
? colors.destructive
: "transparent"
const textColor =
variant === "primary"
? colors.primaryForeground
: variant === "destructive"
? "#fff"
: colors.foreground
return (
<Pressable
{...props}
disabled={isDisabled}
style={({ pressed }) => [
styles.button,
{
backgroundColor,
opacity: isDisabled ? 0.5 : pressed ? 0.85 : 1,
},
style,
]}
>
{loading ? (
<ActivityIndicator color={textColor} />
) : (
<View style={styles.buttonContent}>
{icon ? <Ionicons name={icon} size={18} color={textColor} /> : null}
<Text style={[styles.buttonText, { color: textColor }]}>{title}</Text>
</View>
)}
</Pressable>
)
}
export function Input({ style, ...props }: TextInputProps) {
const colors = useThemeColors()
return (
<TextInput
{...props}
placeholderTextColor={colors.mutedForeground}
style={[
styles.input,
{
color: colors.foreground,
backgroundColor: colors.muted,
borderColor: colors.border,
},
style,
]}
/>
)
}
export function Card({ children }: { children: React.ReactNode }) {
const colors = useThemeColors()
return (
<View style={[styles.card, { backgroundColor: colors.card, borderColor: colors.border }]}>
{children}
</View>
)
}
export function LoadingView() {
const colors = useThemeColors()
return (
<View style={styles.loading}>
<ActivityIndicator color={colors.foreground} size="large" />
</View>
)
}
const styles = StyleSheet.create({
button: {
minHeight: 44,
borderRadius: radius.md,
alignItems: "center",
justifyContent: "center",
paddingHorizontal: spacing.lg,
paddingVertical: spacing.sm,
},
buttonContent: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: spacing.xs,
},
buttonText: {
fontSize: 16,
fontWeight: "600",
},
input: {
minHeight: 44,
borderRadius: radius.md,
borderWidth: 1,
paddingHorizontal: spacing.md,
fontSize: 16,
},
card: {
borderRadius: radius.lg,
borderWidth: 1,
padding: spacing.lg,
gap: spacing.md,
},
loading: {
flex: 1,
alignItems: "center",
justifyContent: "center",
padding: spacing.xl,
},
})
+30
View File
@@ -0,0 +1,30 @@
import { Toaster as SonnerToaster } from "sonner-native"
import { useColorScheme } from "react-native"
import { colors, radius } from "@/lib/theme"
export function Toaster() {
const scheme = useColorScheme()
const themeColors = scheme === "dark" ? colors.dark : colors.light
return (
<SonnerToaster
position="top-center"
theme={scheme === "dark" ? "dark" : "light"}
toastOptions={{
style: {
backgroundColor: themeColors.card,
borderColor: themeColors.border,
borderWidth: 1,
borderRadius: radius.lg,
},
titleStyle: {
color: themeColors.foreground,
},
descriptionStyle: {
color: themeColors.mutedForeground,
},
}}
/>
)
}
+380
View File
@@ -0,0 +1,380 @@
import { useConvex, useMutation, useQuery } from "convex/react"
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react"
import {
FlatList,
Modal,
Pressable,
StyleSheet,
Text,
View,
} from "react-native"
import { Button, Input } from "@/components/ui/primitives"
import { api } from "@otunes/convex/_generated/api"
import type { OwnedPlaylistForAdd } from "@otunes/convex/types"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { showError, showSuccess } from "@/lib/toast"
import { useAppNavigation } from "@/lib/app-navigation"
import { useThemeColors } from "@/lib/theme"
type AddToPlaylistContextValue = {
openAddToPlaylist: (songIds: Id<"songs">[]) => void
openAddAlbumToPlaylist: (albumId: Id<"albums">) => Promise<void>
openAddPlaylistToPlaylist: (playlistId: Id<"playlists">) => Promise<void>
openAddArtistToPlaylist: (artistId: Id<"artists">) => Promise<void>
openCreatePlaylist: () => void
}
const AddToPlaylistContext = createContext<AddToPlaylistContextValue | null>(
null
)
export function useAddToPlaylist() {
const context = useContext(AddToPlaylistContext)
if (!context) {
throw new Error(
"useAddToPlaylist must be used within AddToPlaylistProvider"
)
}
return context
}
export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
const convex = useConvex()
const { push } = useAppNavigation()
const colors = useThemeColors()
const addSongs = useMutation(api.playlists.addSongsToPlaylist)
const createPlaylist = useMutation(api.playlists.createPlaylist)
const [open, setOpen] = useState(false)
const [createOpen, setCreateOpen] = useState(false)
const [pendingSongIds, setPendingSongIds] = useState<Id<"songs">[]>([])
const [newPlaylistName, setNewPlaylistName] = useState("")
const [submitting, setSubmitting] = useState(false)
const [addingToPlaylistId, setAddingToPlaylistId] =
useState<Id<"playlists"> | null>(null)
const selectionRequestIdRef = useRef(0)
const ownedPlaylists = useQuery(
api.playlists.listOwnedPlaylists,
open ? {} : "skip"
)
useEffect(
() => () => {
selectionRequestIdRef.current += 1
},
[]
)
const openAddToPlaylist = useCallback((songIds: Id<"songs">[]) => {
selectionRequestIdRef.current += 1
setPendingSongIds(songIds)
setOpen(true)
}, [])
const closeAddToPlaylist = useCallback(() => {
selectionRequestIdRef.current += 1
setOpen(false)
setAddingToPlaylistId(null)
setPendingSongIds([])
}, [])
const openAddAlbumToPlaylist = useCallback(
async (albumId: Id<"albums">) => {
const requestId = ++selectionRequestIdRef.current
try {
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
albumId,
})
if (selectionRequestIdRef.current !== requestId) return
setPendingSongIds(songIds)
setOpen(true)
} catch (error) {
if (selectionRequestIdRef.current !== requestId) return
showError(
error instanceof Error ? error.message : "Failed to load album"
)
}
},
[convex]
)
const openAddPlaylistToPlaylist = useCallback(
async (playlistId: Id<"playlists">) => {
const requestId = ++selectionRequestIdRef.current
try {
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
playlistId,
})
if (selectionRequestIdRef.current !== requestId) return
setPendingSongIds(songIds)
setOpen(true)
} catch (error) {
if (selectionRequestIdRef.current !== requestId) return
showError(
error instanceof Error ? error.message : "Failed to load playlist"
)
}
},
[convex]
)
const openAddArtistToPlaylist = useCallback(
async (artistId: Id<"artists">) => {
const requestId = ++selectionRequestIdRef.current
try {
const songIds = await convex.query(
api.playlists.getOrderedArtistSongIds,
{ artistId }
)
if (selectionRequestIdRef.current !== requestId) return
setPendingSongIds(songIds)
setOpen(true)
} catch (error) {
if (selectionRequestIdRef.current !== requestId) return
showError(
error instanceof Error ? error.message : "Failed to load artist"
)
}
},
[convex]
)
const openCreatePlaylist = useCallback(() => {
selectionRequestIdRef.current += 1
setPendingSongIds([])
setNewPlaylistName("")
setCreateOpen(true)
}, [])
const handleAddToPlaylist = useCallback(
async (
playlistId: Id<"playlists">,
title: string,
existing: Id<"songs">[]
) => {
if (addingToPlaylistId) return
const existingSet = new Set(existing)
const toAdd = pendingSongIds.filter((id) => !existingSet.has(id))
if (toAdd.length === 0) {
showSuccess(`All selected songs are already in ${title}`)
closeAddToPlaylist()
return
}
setAddingToPlaylistId(playlistId)
try {
await addSongs({ playlistId, songIds: toAdd })
showSuccess(
toAdd.length > 1
? `Added ${toAdd.length} songs to ${title}`
: `Added to ${title}`
)
closeAddToPlaylist()
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to add to playlist"
)
} finally {
setAddingToPlaylistId(null)
}
},
[addSongs, addingToPlaylistId, closeAddToPlaylist, pendingSongIds]
)
const handleCreatePlaylist = useCallback(async () => {
const name = newPlaylistName.trim()
if (!name) return
setSubmitting(true)
try {
const playlistId = await createPlaylist({
name,
songIds: pendingSongIds,
})
showSuccess("Playlist created")
setCreateOpen(false)
closeAddToPlaylist()
push(`/playlist/${playlistId}`)
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to create playlist"
)
} finally {
setSubmitting(false)
}
}, [
closeAddToPlaylist,
createPlaylist,
newPlaylistName,
pendingSongIds,
push,
])
const value = useMemo(
() => ({
openAddToPlaylist,
openAddAlbumToPlaylist,
openAddPlaylistToPlaylist,
openAddArtistToPlaylist,
openCreatePlaylist,
}),
[
openAddToPlaylist,
openAddAlbumToPlaylist,
openAddPlaylistToPlaylist,
openAddArtistToPlaylist,
openCreatePlaylist,
]
)
return (
<AddToPlaylistContext.Provider value={value}>
{children}
<Modal
visible={open}
animationType="slide"
transparent
onRequestClose={closeAddToPlaylist}
>
<Pressable style={styles.overlay} onPress={closeAddToPlaylist}>
<Pressable
style={[
styles.sheet,
{ backgroundColor: colors.card, borderColor: colors.border },
]}
onPress={(event) => event.stopPropagation()}
>
<Text style={[styles.title, { color: colors.foreground }]}>
Add to Playlist
</Text>
<FlatList
style={styles.list}
data={ownedPlaylists ?? []}
keyExtractor={(playlist) => playlist.id}
renderItem={({
item: playlist,
}: {
item: OwnedPlaylistForAdd
}) => (
<Pressable
style={styles.row}
disabled={addingToPlaylistId !== null}
onPress={() =>
void handleAddToPlaylist(
playlist.id,
playlist.title,
playlist.songIds
)
}
>
<Text style={{ color: colors.foreground }}>
{playlist.title}
</Text>
</Pressable>
)}
/>
<Button
title="New Playlist"
variant="secondary"
onPress={() => {
selectionRequestIdRef.current += 1
setOpen(false)
setNewPlaylistName("")
setCreateOpen(true)
}}
/>
</Pressable>
</Pressable>
</Modal>
<Modal
visible={createOpen}
animationType="fade"
transparent
onRequestClose={() => setCreateOpen(false)}
>
<Pressable style={styles.overlay} onPress={() => setCreateOpen(false)}>
<Pressable
style={[
styles.createSheet,
{ backgroundColor: colors.card, borderColor: colors.border },
]}
onPress={(event) => event.stopPropagation()}
>
<Text style={[styles.title, { color: colors.foreground }]}>
New Playlist
</Text>
<Input
value={newPlaylistName}
onChangeText={setNewPlaylistName}
placeholder="Playlist name"
autoFocus
/>
<View style={styles.createActions}>
<Button
title="Cancel"
variant="ghost"
onPress={() => setCreateOpen(false)}
/>
<Button
title="Create"
loading={submitting}
disabled={!newPlaylistName.trim()}
onPress={() => void handleCreatePlaylist()}
/>
</View>
</Pressable>
</Pressable>
</Modal>
</AddToPlaylistContext.Provider>
)
}
const styles = StyleSheet.create({
overlay: {
flex: 1,
backgroundColor: "rgba(0,0,0,0.45)",
justifyContent: "flex-end",
},
sheet: {
maxHeight: "60%",
borderTopLeftRadius: 16,
borderTopRightRadius: 16,
borderWidth: 1,
padding: 16,
gap: 12,
},
createSheet: {
margin: 24,
borderRadius: 16,
borderWidth: 1,
padding: 16,
gap: 12,
},
title: {
fontSize: 18,
fontWeight: "700",
},
list: {
maxHeight: 280,
},
row: {
paddingVertical: 14,
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: "#e4e4e7",
},
createActions: {
flexDirection: "row",
justifyContent: "flex-end",
gap: 8,
},
})
+42
View File
@@ -0,0 +1,42 @@
import { ConvexAuthProvider } from "@convex-dev/auth/react"
import { ConvexReactClient } from "convex/react"
import { useCallback, useMemo, useState, type ReactNode } from "react"
import { ConvexAuthSessionProvider } from "@/contexts/convex-auth-session"
import { useServerConfig } from "@/contexts/server-config"
import { clearStoredAuthTokens, secureStorage } from "@/lib/auth-storage"
export function ConvexAppProvider({ children }: { children: ReactNode }) {
const { config } = useServerConfig()
const [authEpoch, setAuthEpoch] = useState(0)
const client = useMemo(() => {
if (!config) return null
return new ConvexReactClient(config.convexUrl)
}, [config?.convexUrl, authEpoch])
const invalidateSession = useCallback(async () => {
if (!config) {
return
}
await clearStoredAuthTokens(config.convexUrl)
setAuthEpoch((epoch) => epoch + 1)
}, [config])
if (!client || !config) {
return <>{children}</>
}
return (
<ConvexAuthSessionProvider invalidateSession={invalidateSession}>
<ConvexAuthProvider
key={authEpoch}
client={client}
storage={secureStorage}
storageNamespace={config.convexUrl}
>
{children}
</ConvexAuthProvider>
</ConvexAuthSessionProvider>
)
}
@@ -0,0 +1,31 @@
import { createContext, useContext, type ReactNode } from "react"
type ConvexAuthSessionContextValue = {
invalidateSession: () => Promise<void>
}
const ConvexAuthSessionContext = createContext<ConvexAuthSessionContextValue | null>(
null
)
export function ConvexAuthSessionProvider({
children,
invalidateSession,
}: {
children: ReactNode
invalidateSession: () => Promise<void>
}) {
return (
<ConvexAuthSessionContext.Provider value={{ invalidateSession }}>
{children}
</ConvexAuthSessionContext.Provider>
)
}
export function useInvalidateAuthSession() {
const context = useContext(ConvexAuthSessionContext)
if (!context) {
throw new Error("useInvalidateAuthSession must be used within ConvexAppProvider")
}
return context
}
+249
View File
@@ -0,0 +1,249 @@
import { useMutation, useQuery } from "convex/react"
import {
createContext,
useCallback,
useContext,
useMemo,
type ReactNode,
} from "react"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { showError, showSuccess } from "@/lib/toast"
type FavoritesContextValue = {
isSongFavorite: (songId: string) => boolean
isAlbumFavorite: (albumId: string) => boolean
isArtistFavorite: (artistId: string) => boolean
toggleSongFavorite: (songId: Id<"songs">) => Promise<void>
toggleAlbumFavorite: (albumId: Id<"albums">) => Promise<void>
toggleArtistFavorite: (artistId: Id<"artists">) => Promise<void>
favoriteSongs: (songIds: Id<"songs">[]) => Promise<void>
}
const FavoritesContext = createContext<FavoritesContextValue | null>(null)
export function useFavorites() {
const context = useContext(FavoritesContext)
if (!context) {
throw new Error("useFavorites must be used within FavoritesProvider")
}
return context
}
export function FavoritesProvider({ children }: { children: ReactNode }) {
const favorites = useQuery(api.favorites.getUserFavorites)
const favoriteSong = useMutation(
api.favorites.favoriteSong
).withOptimisticUpdate((store, { songId }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (!current || current.favoriteSongs.includes(songId)) return
store.setQuery(
api.favorites.getUserFavorites,
{},
{
...current,
favoriteSongs: [...current.favoriteSongs, songId],
}
)
})
const unfavoriteSong = useMutation(
api.favorites.unfavoriteSong
).withOptimisticUpdate((store, { songId }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (!current) return
store.setQuery(
api.favorites.getUserFavorites,
{},
{
...current,
favoriteSongs: current.favoriteSongs.filter((id) => id !== songId),
}
)
})
const favoriteAlbum = useMutation(
api.favorites.favoriteAlbum
).withOptimisticUpdate((store, { albumId }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (!current || current.favoriteAlbums.includes(albumId)) return
store.setQuery(
api.favorites.getUserFavorites,
{},
{
...current,
favoriteAlbums: [...current.favoriteAlbums, albumId],
}
)
})
const unfavoriteAlbum = useMutation(
api.favorites.unfavoriteAlbum
).withOptimisticUpdate((store, { albumId }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (!current) return
store.setQuery(
api.favorites.getUserFavorites,
{},
{
...current,
favoriteAlbums: current.favoriteAlbums.filter((id) => id !== albumId),
}
)
})
const favoriteArtist = useMutation(
api.favorites.favoriteArtist
).withOptimisticUpdate((store, { artistId }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (!current || current.favoriteArtists.includes(artistId)) return
store.setQuery(
api.favorites.getUserFavorites,
{},
{
...current,
favoriteArtists: [...current.favoriteArtists, artistId],
}
)
})
const unfavoriteArtist = useMutation(
api.favorites.unfavoriteArtist
).withOptimisticUpdate((store, { artistId }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (!current) return
store.setQuery(
api.favorites.getUserFavorites,
{},
{
...current,
favoriteArtists: current.favoriteArtists.filter(
(id) => id !== artistId
),
}
)
})
const favoriteSongsMutation = useMutation(
api.favorites.favoriteSongs
).withOptimisticUpdate((store, { songIds }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (!current) return
store.setQuery(api.favorites.getUserFavorites, {}, {
...current,
favoriteSongs: [...new Set([...current.favoriteSongs, ...songIds])],
})
})
const songIds = useMemo(
() => new Set(favorites?.favoriteSongs.map(String) ?? []),
[favorites?.favoriteSongs]
)
const albumIds = useMemo(
() => new Set(favorites?.favoriteAlbums.map(String) ?? []),
[favorites?.favoriteAlbums]
)
const artistIds = useMemo(
() => new Set(favorites?.favoriteArtists.map(String) ?? []),
[favorites?.favoriteArtists]
)
const toggleSongFavorite = useCallback(
async (songId: Id<"songs">) => {
try {
if (songIds.has(songId)) {
await unfavoriteSong({ songId })
showSuccess("Removed from favorites")
} else {
await favoriteSong({ songId })
showSuccess("Added to favorites")
}
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to update favorites"
)
}
},
[songIds, favoriteSong, unfavoriteSong]
)
const toggleAlbumFavorite = useCallback(
async (albumId: Id<"albums">) => {
try {
if (albumIds.has(albumId)) {
await unfavoriteAlbum({ albumId })
showSuccess("Removed from favorites")
} else {
await favoriteAlbum({ albumId })
showSuccess("Added to favorites")
}
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to update favorites"
)
}
},
[albumIds, favoriteAlbum, unfavoriteAlbum]
)
const toggleArtistFavorite = useCallback(
async (artistId: Id<"artists">) => {
try {
if (artistIds.has(artistId)) {
await unfavoriteArtist({ artistId })
showSuccess("Removed from favorites")
} else {
await favoriteArtist({ artistId })
showSuccess("Added to favorites")
}
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to update favorites"
)
}
},
[artistIds, favoriteArtist, unfavoriteArtist]
)
const favoriteSongs = useCallback(
async (ids: Id<"songs">[]) => {
const unique = [...new Set(ids)]
if (unique.length === 0) return
try {
await favoriteSongsMutation({ songIds: unique })
showSuccess(
unique.length > 1
? `Favorited ${unique.length} songs`
: "Added to favorites"
)
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to update favorites"
)
}
},
[favoriteSongsMutation]
)
const value = useMemo(
() => ({
isSongFavorite: (songId: string) => songIds.has(songId),
isAlbumFavorite: (albumId: string) => albumIds.has(albumId),
isArtistFavorite: (artistId: string) => artistIds.has(artistId),
toggleSongFavorite,
toggleAlbumFavorite,
toggleArtistFavorite,
favoriteSongs,
}),
[
songIds,
albumIds,
artistIds,
toggleSongFavorite,
toggleAlbumFavorite,
toggleArtistFavorite,
favoriteSongs,
]
)
return (
<FavoritesContext.Provider value={value}>
{children}
</FavoritesContext.Provider>
)
}
File diff suppressed because it is too large. Load diff
+104
View File
@@ -0,0 +1,104 @@
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from "react"
import AsyncStorage from "@react-native-async-storage/async-storage"
import {
secureGetItem,
secureRemoveItem,
secureSetItem,
} from "@/lib/auth-storage"
import {
clearServerConfig,
loadServerConfig,
parseServerHostname,
saveServerConfig,
LEGACY_SERVER_CONFIG_KEY,
type ServerConfig,
} from "@/lib/server-config"
type ServerConfigContextValue = {
config: ServerConfig | null
isLoading: boolean
setServerHostname: (hostname: string) => Promise<boolean>
clearServer: () => Promise<void>
}
const ServerConfigContext = createContext<ServerConfigContextValue | null>(null)
export function ServerConfigProvider({ children }: { children: ReactNode }) {
const [config, setConfig] = useState<ServerConfig | null>(null)
const [isLoading, setIsLoading] = useState(true)
useEffect(() => {
let cancelled = false
void (async () => {
let loaded: ServerConfig | null = null
try {
loaded = await loadServerConfig(secureGetItem)
if (!loaded) {
const legacy = await AsyncStorage.getItem(LEGACY_SERVER_CONFIG_KEY)
if (legacy) {
try {
const parsed = JSON.parse(legacy) as ServerConfig
if (parsed.hostname && parsed.serverUrl && parsed.convexUrl) {
await saveServerConfig(secureSetItem, parsed)
await AsyncStorage.removeItem(LEGACY_SERVER_CONFIG_KEY)
loaded = parsed
}
} catch {
// Ignore invalid or inaccessible legacy data.
}
}
}
} catch {
// Storage failures should not leave startup blocked indefinitely.
}
if (!cancelled) {
setConfig(loaded)
setIsLoading(false)
}
})()
return () => {
cancelled = true
}
}, [])
const setServerHostname = useCallback(async (hostname: string) => {
const parsed = parseServerHostname(hostname)
if (!parsed) return false
await saveServerConfig(secureSetItem, parsed)
setConfig(parsed)
return true
}, [])
const clearServer = useCallback(async () => {
await clearServerConfig(secureRemoveItem)
setConfig(null)
}, [])
const value = useMemo(
() => ({ config, isLoading, setServerHostname, clearServer }),
[config, isLoading, setServerHostname, clearServer]
)
return (
<ServerConfigContext.Provider value={value}>
{children}
</ServerConfigContext.Provider>
)
}
export function useServerConfig() {
const context = useContext(ServerConfigContext)
if (!context) {
throw new Error("useServerConfig must be used within ServerConfigProvider")
}
return context
}
+21
View File
@@ -0,0 +1,21 @@
{
"cli": {
"version": ">= 18.12.3",
"appVersionSource": "remote"
},
"build": {
"development": {
"developmentClient": true,
"distribution": "internal"
},
"preview": {
"distribution": "internal"
},
"production": {
"autoIncrement": true
}
},
"submit": {
"production": {}
}
}
@@ -0,0 +1,58 @@
import { useEffect, useState } from "react"
import { getColors, type ImageColorsResult } from "react-native-image-colors"
import { withCoverImageSize } from "@/lib/urls"
function prominentColor(result: ImageColorsResult): string {
switch (result.platform) {
case "ios":
return result.primary || result.background
case "android":
return result.vibrant || result.dominant || result.average
case "web":
return result.vibrant || result.dominant
}
}
export function useCoverBackgroundColor(
uri: string,
hasCover: boolean,
fallback: string,
) {
const [backgroundColor, setBackgroundColor] = useState(fallback)
useEffect(() => {
let cancelled = false
if (!hasCover) {
setBackgroundColor(fallback)
return
}
setBackgroundColor(fallback)
const colorSourceUri = withCoverImageSize(uri, 64)
void getColors(colorSourceUri, {
fallback,
cache: true,
key: colorSourceUri,
quality: "low",
pixelSpacing: 8,
})
.then((result) => {
if (!cancelled) {
setBackgroundColor(prominentColor(result))
}
})
.catch(() => {
if (!cancelled) {
setBackgroundColor(fallback)
}
})
return () => {
cancelled = true
}
}, [fallback, hasCover, uri])
return backgroundColor
}
Loaded 100 of 315 files, more files were not shown because too many files have changed in this diff. Show more