Compare commits

..
135 changed files with 861 additions and 5855 deletions

No files matched your search

-70
View File
@@ -1,70 +0,0 @@
name: Desktop builds
on:
workflow_dispatch:
push:
tags:
- "v*"
jobs:
build:
# Both targets build in electronuserland/builder:wine. Wine lets
# electron-builder stamp the Windows executable; the Flatpak job adds
# flatpak-builder and needs a privileged container for its sandbox.
# See apps/desktop/README.md for the runner setup.
name: Desktop ${{ matrix.target }}
runs-on: ubuntu-latest
timeout-minutes: 90
strategy:
fail-fast: false
matrix:
include:
- target: windows
options: ""
- target: linux
options: --privileged
container:
image: electronuserland/builder:wine
options: ${{ matrix.options }}
env:
OTUNES_DESKTOP_REF: ${{ gitea.ref }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up pnpm
uses: pnpm/action-setup@v4
with:
version: 10.1.0
run_install: false
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: "24"
- name: Install Flatpak tools
if: matrix.target == 'linux'
run: |
apt-get update
apt-get install -y flatpak flatpak-builder
flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo
- name: Install desktop and web dependencies
run: pnpm --filter @otunes/desktop --filter @otunes/web... install --frozen-lockfile
- name: Check desktop scripts
run: pnpm --filter @otunes/desktop typecheck
- name: Build x64 and ARM64 installers
run: pnpm --filter @otunes/desktop build:${{ matrix.target }}
# Gitea's artifact service uses the v3 protocol, not GitHub's v4 service.
- name: Upload installers
uses: actions/upload-artifact@v3
with:
name: otunes-desktop-${{ matrix.target }}
path: |
apps/desktop/dist/*.exe
apps/desktop/dist/*.flatpak
if-no-files-found: error
+1 -12
View File
@@ -41,15 +41,4 @@ apps/web/next-env.d.ts
/.convex
/.cursor
/database
docker-compose.yml
**/credentials.json
**/credentials/
**/*.ipa
**/*.apk
# Electron desktop build artifacts
apps/desktop/.package/
apps/desktop/dist/
apps/web/.next-desktop/
apps/desktop/web/
docker-compose.yml
-5
View File
@@ -9,7 +9,6 @@ This project uses [pnpm workspaces](https://pnpm.io/workspaces):
| Package | Path | Description |
| --- | --- | --- |
| `@otunes/web` | `apps/web` | Next.js web app |
| `@otunes/desktop` | `apps/desktop` | Electron client for Windows and Linux |
| `@otunes/mobile` | `apps/mobile` | Expo React Native mobile app |
| `@otunes/convex` | `packages/convex` | Shared Convex backend and client types |
@@ -95,7 +94,3 @@ If Convex has to live somewhere else, set `PUBLIC_CONVEX_URL` on the container t
## Downloads
Check the releases tab for the latest downloads for apps: [Releases](https://git.abunchofknowitalls.com/joshuafhiggins/otunes/releases)
## Desktop builds
See [the desktop build guide](apps/desktop/README.md) to package the web player for Windows or Linux. The UI is bundled locally, and users choose their oTunes server before signing in.
-38
View File
@@ -1,38 +0,0 @@
# oTunes desktop
The Windows and Linux desktop app. It runs stock Electron and serves the web app's static export (`pnpm --filter @otunes/web build:export`) from `http://127.0.0.1:47836`. There is no bundled Node.js server: the UI talks to the selected oTunes server and its Convex backend directly. On first launch, enter the oTunes server domain, then sign in. The address and session are saved in the app's local storage, not compiled into the package.
For `music.example.com`, Convex connects to `https://convex.music.example.com`. Local hosts follow the mobile convention and use port 3210. The selected server streams audio and serves cover art and avatars. Streams and avatars pass the session token as a `token` query parameter, since the app is on another origin and has no cookie there. The desktop app does not bundle Convex, FFmpeg or a music library.
Use **Server > Change server** or **Change Server** in the account menu to select another server. Sessions are kept per server; switching clears the cached library data.
Stock Chromium cannot decode EAC-3, so the player's codec check reports no Dolby Atmos support and the server streams the regular track instead.
## Run and package
```sh
pnpm install
pnpm dev:desktop
# Or create installers for this OS, x64 and ARM64:
pnpm build:desktop
# Or a specific target from a Linux host:
pnpm --filter @otunes/desktop build:windows
pnpm --filter @otunes/desktop build:linux
```
All of these first build the static export and copy it to `apps/desktop/web`. `pnpm --filter @otunes/desktop build:web` does that step alone. A single instance owns port 47836, so the app's local storage keeps the same origin between launches.
Packaging writes to `apps/desktop/dist`: an NSIS installer per architecture for Windows, a Flatpak per architecture for Linux. To pick one architecture, pass it after the target: `node scripts/package.mjs linux x64`. Building Windows installers on Linux needs Wine. Flatpaks need flatpak-builder with Flathub added, and ARM64 Flatpaks on an x64 host need `qemu-user-static` registered with binfmt. Installers are unsigned unless you configure electron-builder's signing environment.
Flatpaks pin `org.freedesktop.Platform`, its SDK and `org.electronjs.Electron2.BaseApp` to `25.08`. Network, audio, graphics and display access are enabled. Home-directory access is not needed.
## Gitea builds
`.gitea/workflows/desktop-build.yml` runs manually and on `v*` tags, matching the Docker workflow. Both jobs run on the `ubuntu-latest` Docker runner and upload installers with `actions/upload-artifact@v3`. Tags set the installer version, so use semantic version tags such as `v1.2.3`. Manual runs use the desktop package version. Nothing is published.
Both jobs use the `electronuserland/builder:wine` container: `windows` builds x64 and ARM64 NSIS installers, and `linux` installs flatpak-builder from apt and builds x64 and ARM64 Flatpaks.
The Linux job needs two things from the runner host:
- Privileged job containers, since flatpak-builder sandboxes its build. Set `container.privileged: true` in the runner's config.
- An ARM64 binfmt handler. Register it once with `apt install qemu-user-static` on Debian/Ubuntu, which persists across reboots.
-144
View File
@@ -1,144 +0,0 @@
const { app, BrowserWindow, Menu, nativeTheme, session } = require("electron")
const { createServer } = require("node:http")
const { readFile } = require("node:fs/promises")
const path = require("node:path")
// The UI is the web app's static export, served on a fixed loopback origin so
// its localStorage (picked server, session) persists between launches. An
// http://127.0.0.1 page is a secure context that can still reach http servers
// on the local network.
const host = "127.0.0.1:47836"
const origin = `http://${host}`
const webRoot = path.join(
app.isPackaged ? process.resourcesPath : __dirname,
"web"
)
const contentTypes = {
".html": "text/html; charset=utf-8",
".txt": "text/plain; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json",
".webmanifest": "application/manifest+json",
".png": "image/png",
".svg": "image/svg+xml",
".ico": "image/x-icon",
".woff2": "font/woff2",
}
let window, server
// Resolves paths the way static hosts serve a Next.js export: /album is
// album.html, / is index.html, and anything missing is 404.html.
async function serveStatic(request, response) {
if (request.headers.host !== host) return response.writeHead(403).end()
if (request.method !== "GET" && request.method !== "HEAD")
return response.writeHead(405).end()
let pathname
try {
pathname = decodeURIComponent(new URL(request.url, origin).pathname)
} catch {
return response.writeHead(400).end()
}
const relative = pathname.replace(/^\/+|\/+$/g, "")
const candidates = relative
? [relative, `${relative}.html`, `${relative}/index.html`]
: ["index.html"]
for (const candidate of [...candidates, "404.html"]) {
const file = path.resolve(webRoot, candidate)
if (!file.startsWith(webRoot + path.sep)) continue
try {
const body = await readFile(file)
response.writeHead(candidate === "404.html" ? 404 : 200, {
"Content-Type":
contentTypes[path.extname(file)] ?? "application/octet-stream",
"Cache-Control": file.includes(`${path.sep}_next${path.sep}static`)
? "public, max-age=31536000, immutable"
: "no-cache",
})
return response.end(request.method === "HEAD" ? undefined : body)
} catch {
// Try the next candidate.
}
}
response.writeHead(404).end()
}
function openWindow() {
window = new BrowserWindow({
title: "oTunes",
width: 1280,
height: 850,
backgroundColor: nativeTheme.shouldUseDarkColors ? "#000000" : "#ffffff",
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: true,
webSecurity: true,
},
})
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }))
const restrictNavigation = (event, target) => {
if (new URL(target).origin !== origin) event.preventDefault()
}
window.webContents.on("will-navigate", restrictNavigation)
window.webContents.on("will-redirect", restrictNavigation)
session.defaultSession.setPermissionRequestHandler(
(_contents, _permission, callback) => callback(false)
)
session.defaultSession.setPermissionCheckHandler(() => false)
window.loadURL(`${origin}/`).catch(console.error)
window.on("closed", () => {
window = undefined
})
}
if (!app.requestSingleInstanceLock()) app.quit()
else {
app.on("second-instance", () => {
window?.show()
window?.focus()
})
app
.whenReady()
.then(async () => {
server = createServer((request, response) => {
serveStatic(request, response).catch(() => {
if (!response.headersSent) response.writeHead(500)
response.end()
})
})
await new Promise((resolve, reject) => {
server.once("error", reject)
server.listen(47836, "127.0.0.1", resolve)
})
Menu.setApplicationMenu(
Menu.buildFromTemplate([
...(process.platform === "darwin" ? [{ role: "appMenu" }] : []),
{
label: "Server",
submenu: [
{
label: "Change server…",
click: () => window?.loadURL(`${origin}/server`),
},
],
},
{ role: "editMenu" },
{ role: "viewMenu" },
{ role: "windowMenu" },
])
)
openWindow()
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) openWindow()
})
})
.catch((error) => {
console.error(error)
app.quit()
})
}
app.on("before-quit", () => server?.close())
app.on("window-all-closed", () => {
if (process.platform !== "darwin") app.quit()
})
-20
View File
@@ -1,20 +0,0 @@
{
"name": "@otunes/desktop",
"version": "0.0.1",
"private": true,
"description": "oTunes desktop client for Windows and Linux",
"author": "oTunes contributors",
"main": "main.cjs",
"scripts": {
"start": "pnpm build:web && electron .",
"build": "pnpm build:web && node scripts/package.mjs",
"build:windows": "pnpm build:web && node scripts/package.mjs windows",
"build:linux": "pnpm build:web && node scripts/package.mjs linux",
"build:web": "node scripts/build-web.mjs",
"typecheck": "node --check main.cjs && node --check scripts/build-web.mjs && node --check scripts/package.mjs"
},
"devDependencies": {
"electron": "45.3.4",
"electron-builder": "26.18.0"
}
}
-24
View File
@@ -1,24 +0,0 @@
import { execFileSync } from "node:child_process"
import { createRequire } from "node:module"
import { cp, rm } from "node:fs/promises"
import path from "node:path"
import { fileURLToPath } from "node:url"
// Builds the web app's static export and copies it to apps/desktop/web,
// which main.cjs serves and package.mjs ships.
const desktopRoot = fileURLToPath(new URL("../", import.meta.url))
const web = path.resolve(desktopRoot, "../web")
const webRequire = createRequire(path.join(web, "package.json"))
execFileSync(
process.execPath,
[webRequire.resolve("next/dist/bin/next"), "build"],
{
cwd: web,
stdio: "inherit",
env: { ...process.env, OTUNES_STATIC_EXPORT: "1" },
}
)
const destination = path.join(desktopRoot, "web")
await rm(destination, { recursive: true, force: true })
await cp(path.join(web, "out"), destination, { recursive: true })
-77
View File
@@ -1,77 +0,0 @@
import { build, Platform, Arch } from "electron-builder"
import { mkdir, copyFile, writeFile, rm, readFile } from "node:fs/promises"
import { createRequire } from "node:module"
import path from "node:path"
import { fileURLToPath } from "node:url"
// Packages stock Electron with the bundled UI from build-web.mjs.
// Usage: node scripts/package.mjs [windows|linux] [x64|arm64]
// Defaults to the host OS and both architectures. Linux hosts can build both
// targets: Windows needs Wine, ARM64 Flatpaks need qemu-user binfmt.
const desktopRoot = fileURLToPath(new URL("../", import.meta.url))
const hostTarget = { win32: "windows", linux: "linux" }[process.platform]
const [target = hostTarget, onlyArch] = process.argv.slice(2)
const platform = { windows: Platform.WINDOWS, linux: Platform.LINUX }[target]
if (!platform) throw new Error("Targets are windows or linux")
const architectures = onlyArch ? [onlyArch] : ["x64", "arm64"]
if (!architectures.every((arch) => arch === "x64" || arch === "arm64"))
throw new Error("Architectures are x64 or arm64")
const staging = path.join(desktopRoot, ".package")
await rm(staging, { recursive: true, force: true })
await mkdir(staging, { recursive: true })
await copyFile(
path.join(desktopRoot, "main.cjs"),
path.join(staging, "main.cjs")
)
const pkg = JSON.parse(
await readFile(path.join(desktopRoot, "package.json"), "utf8")
)
const ref = process.env.OTUNES_DESKTOP_REF ?? ""
if (ref.startsWith("refs/tags/"))
pkg.version = ref.slice("refs/tags/".length).replace(/^v/, "")
delete pkg.devDependencies
delete pkg.scripts
await writeFile(
path.join(staging, "package.json"),
JSON.stringify(pkg, null, 2)
)
const { version: electronVersion } = createRequire(import.meta.url)(
"electron/package.json"
)
// One build per architecture: a multi-arch NSIS build merges both into one installer.
for (const arch of architectures) {
await build({
targets: platform.createTarget(undefined, Arch[arch]),
config: {
appId: "com.otunes.desktop",
productName: "oTunes",
electronVersion,
artifactName: "oTunes-${version}-${os}-${arch}.${ext}",
icon: path.resolve(desktopRoot, "../web/public/logo.png"),
directories: { app: staging, output: path.join(desktopRoot, "dist") },
files: ["main.cjs", "package.json"],
extraResources: [
{ from: path.join(desktopRoot, "web"), to: "web", filter: ["**/*"] },
],
npmRebuild: false,
win: { target: ["nsis"] },
linux: { category: "AudioVideo", target: ["flatpak"] },
flatpak: {
runtimeVersion: "25.08",
baseVersion: "25.08",
finishArgs: [
"--socket=wayland",
"--socket=fallback-x11",
"--share=ipc",
"--device=dri",
"--socket=pulseaudio",
"--share=network",
],
},
publish: null,
},
publish: "never",
})
}
@@ -1,11 +1,7 @@
import { Stack } from "expo-router"
import { renderTabScreenContent } from "@/components/tab-screen-content"
import {
inlineTitleOptions,
tabStackScreenTitles,
useStackScreenOptions,
} from "@/lib/navigation"
import { useStackScreenOptions, tabStackScreenTitles } from "@/lib/navigation"
import { tabletSections, TabletSectionContext } from "@/lib/tablet-navigation"
export default function TabletSectionLayout({ segment }: { segment: string }) {
@@ -18,7 +14,6 @@ export default function TabletSectionLayout({ segment }: { segment: string }) {
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...options,
...inlineTitleOptions,
title:
route.name === "index"
? section?.title
+8 -8
View File
@@ -193,14 +193,6 @@ function TabsContent() {
<NativeTabs.Trigger.Icon sf="music.note" />
<NativeTabs.Trigger.Label>Songs</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger
name="(downloads)"
hidden={!(Platform.OS === "ios" && Platform.isPad)}
disableTransparentOnScrollEdge
>
<NativeTabs.Trigger.Icon sf="arrow.down.circle" />
<NativeTabs.Trigger.Label>Downloads</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger
name="(playlists)"
hidden={!(Platform.OS === "ios" && Platform.isPad)}
@@ -225,6 +217,14 @@ function TabsContent() {
<NativeTabs.Trigger.Icon sf="clock" />
<NativeTabs.Trigger.Label>Recently Played</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger
name="(downloads)"
hidden={!(Platform.OS === "ios" && Platform.isPad)}
disableTransparentOnScrollEdge
>
<NativeTabs.Trigger.Icon sf="arrow.down.circle" />
<NativeTabs.Trigger.Label>Downloads</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
</NativeTabs>
{!keyboardVisible ? <AndroidMiniPlayer /> : null}
{tabletLayout ? <TabletMiniPlayer /> : null}
@@ -2,11 +2,7 @@ import { renderTabScreenContent } from "@/components/tab-screen-content"
import { Stack } from "expo-router"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import {
inlineTitleOptions,
tabStackScreenTitles,
useStackScreenOptions,
} from "@/lib/navigation"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
export const unstable_settings = {
anchor: "index",
@@ -20,7 +16,6 @@ export default function HomeLayout() {
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...baseOptions,
...inlineTitleOptions,
title: tabStackScreenTitles[route.name] ?? "Home",
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
@@ -23,9 +23,9 @@ import {
} from "@/components/collection-list"
import { AudioFormatBadge } from "@/components/audio-format-badge"
import {
CollectionDownloadButton,
DownloadHeaderButton,
DownloadedQuality,
} from "@/components/collection-download-button"
} from "@/components/download-header-button"
import { useOpenedFromDownloads } from "@/lib/downloads-navigation"
import { downloadsQueueOrigin } from "@otunes/convex/download-quality"
import {
@@ -81,7 +81,8 @@ export default function AlbumScreen() {
const playOrigin = fromDownloads
? downloadsQueueOrigin(`album:${id}`)
: `album:${id}`
const { isSongFavorite } = useFavorites()
const { isAlbumFavorite, toggleAlbumFavorite, isSongFavorite } =
useFavorites()
const {
handleAlbumDetailAction,
handleAlbumTrackAction,
@@ -204,6 +205,7 @@ export default function AlbumScreen() {
}
const metadata = formatMetadata(album.genre, album.year)
const favorited = isAlbumFavorite(album.id)
return (
<>
@@ -224,35 +226,41 @@ export default function AlbumScreen() {
}
: {}),
headerRight: () => (
<MediaActionMenu
stationArtistId={album.artist.id}
selectedCount={album.tracks.length}
favorited={isAlbumFav(album.id)}
downloaded={albumDownloaded}
share={{ type: "album", albumId: album.id, title: album.title }}
onAction={(action) => {
if (action === "download") {
void requestDownload(downloadTarget)
} else if (action === "remove-download") {
void removeDownload(downloadTarget)
} else {
void handleAlbumDetailAction(
album.id as Id<"albums">,
songIds,
action,
album.artist.id as Id<"artists">
)
}
}}
>
<Pressable hitSlop={8}>
<Ionicons
name="ellipsis-horizontal"
size={22}
color={colors.foreground}
/>
</Pressable>
</MediaActionMenu>
<View style={styles.headerActions}>
<DownloadHeaderButton
target={downloadTarget}
color={colors.foreground}
/>
<MediaActionMenu
stationArtistId={album.artist.id}
selectedCount={album.tracks.length}
favorited={isAlbumFav(album.id)}
downloaded={albumDownloaded}
share={{ type: "album", albumId: album.id, title: album.title }}
onAction={(action) => {
if (action === "download") {
void requestDownload(downloadTarget)
} else if (action === "remove-download") {
void removeDownload(downloadTarget)
} else {
void handleAlbumDetailAction(
album.id as Id<"albums">,
songIds,
action,
album.artist.id as Id<"artists">
)
}
}}
>
<Pressable hitSlop={8}>
<Ionicons
name="ellipsis-horizontal"
size={22}
color={colors.foreground}
/>
</Pressable>
</MediaActionMenu>
</View>
),
}}
/>
@@ -299,6 +307,34 @@ export default function AlbumScreen() {
heroLayout.landscape && { flexDirection: "row-reverse" },
]}
>
<Pressable
onPress={() => void toggleAlbumFavorite(album.id)}
hitSlop={8}
style={[
styles.iconAction,
{ backgroundColor: palette.surface },
]}
>
<Ionicons
name={favorited ? "star" : "star-outline"}
size={24}
color={favorited ? palette.accent : palette.foreground}
/>
</Pressable>
<Button
title="Play"
icon="play"
onPress={() =>
void (fromDownloads
? playInOrder(songIds, playOrigin)
: playAlbum(album.id, songIds))
}
style={styles.playButton}
tint={{
background: palette.accent,
foreground: palette.accentForeground,
}}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
@@ -319,28 +355,6 @@ export default function AlbumScreen() {
color={palette.foreground}
/>
</Pressable>
<Button
title="Play"
icon="play"
onPress={() =>
void (fromDownloads
? playInOrder(songIds, playOrigin)
: playAlbum(album.id, songIds))
}
style={styles.playButton}
tint={{
background: palette.accent,
foreground: palette.accentForeground,
}}
/>
<CollectionDownloadButton
target={downloadTarget}
color={palette.foreground}
style={[
styles.iconAction,
{ backgroundColor: palette.surface },
]}
/>
</View>
}
>
@@ -590,6 +604,7 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
const styles = StyleSheet.create({
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
headerActions: { flexDirection: "row", alignItems: "center", gap: 16 },
cover: {
width: 220,
height: 220,
@@ -53,7 +53,7 @@ export default function AlbumsScreen() {
return (
<>
{searchBar}
<MediaGridSkeleton title="Albums" />
<MediaGridSkeleton />
</>
)
}
@@ -63,7 +63,6 @@ export default function AlbumsScreen() {
{searchBar}
<MediaGridList
title="Albums"
content={albums}
paddingBottom={contentBottomInset}
onEndReached={() => {
@@ -2,13 +2,12 @@ import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router"
import { memo, useCallback } from "react"
import {
type FlatList,
FlatList,
Pressable,
StyleSheet,
Text,
type ListRenderItemInfo,
} from "react-native"
import Animated from "react-native-reanimated"
import {
MediaContextMenu,
@@ -16,7 +15,6 @@ import {
} from "@/components/media-context-menu"
import { CoverImage } from "@/components/cover-image"
import { ArtistListSkeleton } from "@/components/skeletons"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { contentBottomInset } from "@/components/player"
import { useServerConfig } from "@/contexts/server-config"
import {
@@ -35,7 +33,6 @@ import { spacing, useThemeColors } from "@/lib/theme"
const PAGE_SIZE = 50
export default function ArtistsScreen() {
const { ref, scrollY } = useScreenTitleScroll<FlatList<BrowseArtist>>()
const { push } = useAppNavigation()
const colors = useThemeColors()
const { config } = useServerConfig()
@@ -97,7 +94,7 @@ export default function ArtistsScreen() {
return (
<>
{searchBar}
<ArtistListSkeleton title="Artists" />
<ArtistListSkeleton />
</>
)
}
@@ -106,11 +103,8 @@ export default function ArtistsScreen() {
<>
{searchBar}
<Animated.FlatList
<FlatList
{...longListProps}
ref={ref}
scrollEventThrottle={16}
ListHeaderComponent={<ScreenTitle title="Artists" scrollY={scrollY} />}
data={artists}
keyExtractor={artistKey}
renderItem={renderItem}
@@ -1,4 +1,3 @@
import { useContext } from "react"
import { Pressable } from "react-native"
import { MediaGridList } from "@/components/media-cards"
@@ -11,20 +10,19 @@ import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router"
import { SymbolView } from "expo-symbols"
import { useAddToPlaylist } from "@/contexts/add-to-playlist"
import { TabletSectionContext } from "@/lib/tablet-navigation"
export default function PlaylistsTabScreen() {
const colors = useThemeColors()
const playlists = useCachedQuery(api.playlists.listAllPlaylists)
const { openCreatePlaylist } = useAddToPlaylist()
const title = useContext(TabletSectionContext)?.title ?? "Playlists"
if (playlists === undefined) {
return (
<>
<Stack.Screen
options={{
title,
title: "Playlists",
headerLargeTitle: true,
headerRight: () => (
<Pressable
onPress={openCreatePlaylist}
@@ -40,7 +38,7 @@ export default function PlaylistsTabScreen() {
),
}}
/>
<MediaGridSkeleton title={title} />
<MediaGridSkeleton />
</>
)
}
@@ -49,7 +47,8 @@ export default function PlaylistsTabScreen() {
<>
<Stack.Screen
options={{
title,
title: "Playlists",
headerLargeTitle: true,
headerRight: () => (
<Pressable
onPress={openCreatePlaylist}
@@ -62,7 +61,6 @@ export default function PlaylistsTabScreen() {
}}
/>
<MediaGridList
title={title}
content={playlists}
paddingBottom={tabContentBottomInset}
/>
@@ -1,16 +1,10 @@
import { Stack } from "expo-router"
import { useCallback, useState } from "react"
import {
type FlatList,
StyleSheet,
type ListRenderItemInfo,
} from "react-native"
import Animated from "react-native-reanimated"
import { FlatList, StyleSheet, type ListRenderItemInfo } from "react-native"
import type { MediaAction } from "@/components/media-context-menu"
import { contentBottomInset, SongListRow } from "@/components/player"
import { SongListSkeleton } from "@/components/skeletons"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback"
import {
@@ -26,7 +20,6 @@ import { longListProps } from "@/lib/list"
const PAGE_SIZE = 50
export default function SongsScreen() {
const { ref, scrollY } = useScreenTitleScroll<FlatList<BrowseSong>>()
const { playFromLibrarySong } = usePlaybackActions()
const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions()
@@ -94,7 +87,7 @@ export default function SongsScreen() {
return (
<>
{searchBar}
<SongListSkeleton title="Songs" />
<SongListSkeleton />
</>
)
}
@@ -103,11 +96,8 @@ export default function SongsScreen() {
<>
{searchBar}
<Animated.FlatList
<FlatList
{...longListProps}
ref={ref}
scrollEventThrottle={16}
ListHeaderComponent={<ScreenTitle title="Songs" scrollY={scrollY} />}
data={songs}
keyExtractor={songKey}
renderItem={renderItem}
@@ -1,6 +1,6 @@
import { useMemo } from "react"
import {
type FlatList,
FlatList,
Pressable,
StyleSheet,
Text,
@@ -8,10 +8,8 @@ import {
type ListRenderItemInfo,
} from "react-native"
import { Stack } from "expo-router"
import Animated from "react-native-reanimated"
import { CoverImage } from "@/components/cover-image"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { tabContentBottomInset } from "@/components/player"
import {
FAVORITES_DOWNLOAD_ID,
@@ -55,7 +53,6 @@ export default function DownloadsScreen() {
const { push } = useAppNavigation()
const { columns, cardWidth, onLayout, horizontalPadding, gap } =
useMediaGridLayout()
const { ref, scrollY } = useScreenTitleScroll<FlatList<Card>>()
const cards = useMemo<Card[]>(() => {
if (!queue) return []
@@ -138,10 +135,8 @@ export default function DownloadsScreen() {
return (
<>
<Stack.Screen options={{ title: "Downloads" }} />
<Animated.FlatList
ref={ref}
scrollEventThrottle={16}
<Stack.Screen options={{ title: "Downloads", headerLargeTitle: true }} />
<FlatList
key={columns}
onLayout={onLayout}
data={cards}
@@ -154,20 +149,13 @@ export default function DownloadsScreen() {
numColumns={columns}
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{
paddingTop: spacing.lg,
paddingHorizontal: horizontalPadding,
paddingBottom: tabContentBottomInset,
gap,
}}
columnWrapperStyle={columns > 1 ? { gap } : undefined}
contentInsetAdjustmentBehavior="automatic"
ListHeaderComponent={
<ScreenTitle
title="Downloads"
scrollY={scrollY}
// The list padding already insets the title.
style={{ paddingHorizontal: 0 }}
/>
}
ListEmptyComponent={
<View style={styles.empty}>
<Text style={{ color: colors.mutedForeground }}>
@@ -1,17 +1,15 @@
import { useCallback, useMemo } from "react"
import {
type FlatList,
FlatList,
Pressable,
StyleSheet,
Text,
View,
type ListRenderItemInfo,
} from "react-native"
import Animated from "react-native-reanimated"
import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { useSwipeRowGroup } from "@/components/ios-swipe-to-remove-row"
import type { MediaAction } from "@/components/media-context-menu"
import { contentBottomInset, SongListRow } from "@/components/player"
@@ -54,7 +52,6 @@ export default function OtherDownloadsScreen() {
const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions()
const swipeGroup = useSwipeRowGroup()
const { ref, scrollY } = useScreenTitleScroll<FlatList<BrowseSong>>()
const handlePlaySong = useCallback(
(song: BrowseSong) => void playFromSong(song.id, playableIds, PLAY_ORIGIN),
@@ -93,11 +90,11 @@ export default function OtherDownloadsScreen() {
return (
<>
<Stack.Screen options={{ title: OTHER_DOWNLOADS_TITLE }} />
<Animated.FlatList
<Stack.Screen
options={{ title: OTHER_DOWNLOADS_TITLE, headerLargeTitle: false }}
/>
<FlatList
{...longListProps}
ref={ref}
scrollEventThrottle={16}
data={songs}
keyExtractor={(song) => song.id}
renderItem={renderItem}
@@ -106,32 +103,25 @@ export default function OtherDownloadsScreen() {
contentInsetAdjustmentBehavior="automatic"
onScrollBeginDrag={swipeGroup.closeOpenRow}
ListHeaderComponent={
<>
<ScreenTitle title={OTHER_DOWNLOADS_TITLE} scrollY={scrollY} />
{songs.length > 0 ? (
<View style={styles.actions}>
<Button
title="Play"
icon="play"
onPress={() => void playInOrder(playableIds, PLAY_ORIGIN)}
style={styles.play}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() => void playShuffled(playableIds, PLAY_ORIGIN)}
style={[styles.shuffle, { backgroundColor: colors.card }]}
>
<Ionicons
name="shuffle"
size={24}
color={colors.foreground}
/>
</Pressable>
</View>
) : null}
</>
songs.length > 0 ? (
<View style={styles.actions}>
<Button
title="Play"
icon="play"
onPress={() => void playInOrder(playableIds, PLAY_ORIGIN)}
style={styles.play}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() => void playShuffled(playableIds, PLAY_ORIGIN)}
style={[styles.shuffle, { backgroundColor: colors.card }]}
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
</View>
) : undefined
}
ListEmptyComponent={
<Text style={[styles.empty, { color: colors.mutedForeground }]}>
+4 -16
View File
@@ -1,10 +1,8 @@
import { memo } from "react"
import { type ScrollViewInstance, StyleSheet } from "react-native"
import Animated from "react-native-reanimated"
import { ScrollView, StyleSheet } from "react-native"
import { ContentCarousel } from "@/components/media-cards"
import { HomeSkeleton } from "@/components/skeletons"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { tabContentBottomInset } from "@/components/player"
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api"
@@ -40,7 +38,6 @@ const HomeCarousels = memo(function HomeCarousels({
export default function HomeScreen() {
const colors = useThemeColors()
const { ref, scrollY } = useScreenTitleScroll<ScrollViewInstance>()
const recentlyAdded = useCachedPaginatedQuery(
api.library.browseRecentlyAddedPaginated,
{},
@@ -56,16 +53,14 @@ export default function HomeScreen() {
(result) => result.status === "LoadingFirstPage" && !result.isCached
)
if (isLoading) {
return <HomeSkeleton title="Home" />
return <HomeSkeleton />
}
const added = recentlyAdded.results.slice(0, CAROUSEL_ITEM_LIMIT)
const played = recentlyPlayed.results.slice(0, CAROUSEL_ITEM_LIMIT)
return (
<Animated.ScrollView
ref={ref}
scrollEventThrottle={16}
<ScrollView
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={[
styles.content,
@@ -73,9 +68,8 @@ export default function HomeScreen() {
]}
contentInsetAdjustmentBehavior="automatic"
>
<ScreenTitle title="Home" scrollY={scrollY} style={styles.title} />
<HomeCarousels recentlyAdded={added} recentlyPlayed={played} />
</Animated.ScrollView>
</ScrollView>
)
}
@@ -84,10 +78,4 @@ const styles = StyleSheet.create({
padding: spacing.lg,
gap: spacing.xl,
},
// The content padding already insets the title.
title: {
paddingHorizontal: 0,
marginTop: -spacing.lg,
marginBottom: -spacing.md,
},
})
@@ -45,10 +45,9 @@ import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset, SongListRow } from "@/components/player"
import {
CollectionDownloadButton,
type CollectionDownloadTarget,
DownloadHeaderButton,
DownloadedQuality,
} from "@/components/collection-download-button"
} from "@/components/download-header-button"
import { useOpenedFromDownloads } from "@/lib/downloads-navigation"
import { downloadsQueueOrigin } from "@otunes/convex/download-quality"
import type { CollectionRef } from "@otunes/convex/client/download-queue"
@@ -350,26 +349,32 @@ function PlaylistContent({
}
: {}),
headerRight: () => (
<MediaActionMenu
selectedCount={songIds.length}
playlistLabel={PLAYLIST_LABEL}
downloaded={playlistDownloaded}
share={{
type: "playlist",
playlistId: playlistId ?? "favorites",
title: playlist?.title ?? "oTunes",
}}
includeActions={canEdit ? OWNER_MENU_ACTIONS : undefined}
onAction={handlePlaylistMenuAction}
>
<Pressable hitSlop={8}>
<Ionicons
name="ellipsis-horizontal"
size={22}
color={colors.foreground}
/>
</Pressable>
</MediaActionMenu>
<View style={styles.headerActions}>
<DownloadHeaderButton
target={downloadTarget}
color={colors.foreground}
/>
<MediaActionMenu
selectedCount={songIds.length}
playlistLabel={PLAYLIST_LABEL}
downloaded={playlistDownloaded}
share={{
type: "playlist",
playlistId: playlistId ?? "favorites",
title: playlist?.title ?? "oTunes",
}}
includeActions={canEdit ? OWNER_MENU_ACTIONS : undefined}
onAction={handlePlaylistMenuAction}
>
<Pressable hitSlop={8}>
<Ionicons
name="ellipsis-horizontal"
size={22}
color={colors.foreground}
/>
</Pressable>
</MediaActionMenu>
</View>
),
}
}, [
@@ -460,7 +465,7 @@ function PlaylistContent({
isSubscribed={isSubscribed}
showSubscribe={!playlist.isOwner && playlistId !== null}
onSubscribeToggle={handleSubscribeToggle}
downloadTarget={downloadTarget}
downloadRef={downloadRef}
onPlay={handlePlay}
onShuffle={handleShuffle}
/>
@@ -571,11 +576,11 @@ const PlaylistHero = memo(function PlaylistHero({
isSubscribed,
showSubscribe = false,
onSubscribeToggle,
downloadTarget,
downloadRef,
onPlay,
onShuffle,
}: {
downloadTarget: CollectionDownloadTarget
downloadRef: CollectionRef
entityId: string
coverUri: string
hasCover: boolean
@@ -643,15 +648,6 @@ const PlaylistHero = memo(function PlaylistHero({
/>
</Pressable>
) : null}
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={onShuffle}
style={[styles.iconAction, { backgroundColor: palette.surface }]}
>
<Ionicons name="shuffle" size={24} color={palette.foreground} />
</Pressable>
<Button
title="Play"
icon="play"
@@ -662,11 +658,15 @@ const PlaylistHero = memo(function PlaylistHero({
foreground: palette.accentForeground,
}}
/>
<CollectionDownloadButton
target={downloadTarget}
color={palette.foreground}
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={onShuffle}
style={[styles.iconAction, { backgroundColor: palette.surface }]}
/>
>
<Ionicons name="shuffle" size={24} color={palette.foreground} />
</Pressable>
</View>
}
>
@@ -688,7 +688,7 @@ const PlaylistHero = memo(function PlaylistHero({
{ownerName}
</Text>
<DownloadedQuality
collection={downloadTarget}
collection={downloadRef}
color={palette.secondaryForeground}
backgroundColor={palette.background}
/>
@@ -701,6 +701,7 @@ const PlaylistHero = memo(function PlaylistHero({
const styles = StyleSheet.create({
emptyResults: { padding: spacing.lg, textAlign: "center" },
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
headerActions: { flexDirection: "row", alignItems: "center", gap: 16 },
listContent: { paddingBottom: contentBottomInset },
cover: {
width: 200,
@@ -17,10 +17,9 @@ import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset, SongListRow } from "@/components/player"
import {
CollectionDownloadButton,
type CollectionDownloadTarget,
DownloadHeaderButton,
DownloadedQuality,
} from "@/components/collection-download-button"
} from "@/components/download-header-button"
import { useOpenedFromDownloads } from "@/lib/downloads-navigation"
import { downloadsQueueOrigin } from "@otunes/convex/download-quality"
import { FAVORITES_DOWNLOAD_ID } from "@/contexts/downloads"
@@ -54,13 +53,22 @@ export default function FavoritesScreen() {
const playOrigin = fromDownloads
? downloadsQueueOrigin("playlist:favorites")
: undefined
const downloadTarget = useMemo(
const screenOptions = useMemo(
() => ({
...DOWNLOAD_REF,
title: favorites?.title ?? "Favorites",
songIds,
...SCREEN_OPTIONS,
headerRight: () => (
<DownloadHeaderButton
target={{
kind: "playlist",
id: FAVORITES_DOWNLOAD_ID,
title: favorites?.title ?? "Favorites",
songIds,
}}
color={colors.foreground}
/>
),
}),
[favorites?.title, songIds]
[colors.foreground, favorites?.title, songIds]
)
const { filteredSongs, onQueryChange, onSearchSubmit } =
usePlaylistSearch(songs)
@@ -126,7 +134,7 @@ export default function FavoritesScreen() {
return (
<>
<Stack.Screen options={SCREEN_OPTIONS} />
<Stack.Screen options={screenOptions} />
<PlaylistSearchBar
onQueryChange={onQueryChange}
onSearchSubmit={onSearchSubmit}
@@ -149,7 +157,6 @@ export default function FavoritesScreen() {
ListHeaderComponent={
<FavoritesHero
title={favorites.title}
downloadTarget={downloadTarget}
onPlay={handlePlay}
onShuffle={handleShuffle}
/>
@@ -165,12 +172,10 @@ function songKey(song: BrowseSong) {
const FavoritesHero = memo(function FavoritesHero({
title,
downloadTarget,
onPlay,
onShuffle,
}: {
title: string
downloadTarget: CollectionDownloadTarget
onPlay: () => void
onShuffle: () => void
}) {
@@ -197,6 +202,12 @@ const FavoritesHero = memo(function FavoritesHero({
backgroundColor={colors.background}
/>
<View style={styles.actions}>
<Button
title="Play"
icon="play"
onPress={onPlay}
style={styles.playButton}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
@@ -206,17 +217,6 @@ const FavoritesHero = memo(function FavoritesHero({
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
<Button
title="Play"
icon="play"
onPress={onPlay}
style={styles.playButton}
/>
<CollectionDownloadButton
target={downloadTarget}
color={colors.foreground}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
/>
</View>
</View>
<CollectionDivider />
@@ -14,12 +14,11 @@ export default function RecentlyAddedScreen() {
)
if (status === "LoadingFirstPage" && !isCached) {
return <MediaGridSkeleton title="Recently Added" />
return <MediaGridSkeleton />
}
return (
<MediaGridList
title="Recently Added"
content={results}
paddingBottom={contentBottomInset}
onEndReached={() => {
@@ -14,12 +14,11 @@ export default function RecentlyPlayedScreen() {
)
if (status === "LoadingFirstPage" && !isCached) {
return <MediaGridSkeleton title="Recently Played" />
return <MediaGridSkeleton />
}
return (
<MediaGridList
title="Recently Played"
content={results}
paddingBottom={contentBottomInset}
onEndReached={() => {
@@ -3,11 +3,7 @@ import { renderTabScreenContent } from "@/components/tab-screen-content"
import { Stack } from "expo-router"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import {
inlineTitleOptions,
tabStackScreenTitles,
useStackScreenOptions,
} from "@/lib/navigation"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
export const unstable_settings = {
anchor: "index",
@@ -22,7 +18,6 @@ export default function LibraryLayout() {
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...baseOptions,
...inlineTitleOptions,
title:
tabStackScreenTitles[route.name] ??
(tabletLayout ? "Recently Added" : "Library"),
+6 -14
View File
@@ -24,17 +24,17 @@ const links = [
{ 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: "Downloads",
href: "/downloads",
icon: "arrow.down.circle" as const,
},
{
title: "Recently Played",
href: "/recently-played",
icon: "clock" as const,
},
{ title: "Favorites", href: "/playlist/favorites", icon: "star" as const },
{
title: "Downloads",
href: "/downloads",
icon: "arrow.down.circle" as const,
},
]
function LibraryIcon({ name }: { name: (typeof links)[number]["icon"] }) {
@@ -72,7 +72,6 @@ export default function LibraryScreen() {
const { push } = useAppNavigation()
const isTablet = tabletLayout
const colors = useThemeColors()
const title = isTablet ? "Recently Added" : "Library"
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
api.library.browseRecentlyAddedPaginated,
{},
@@ -125,18 +124,11 @@ export default function LibraryScreen() {
)
if (status === "LoadingFirstPage" && !isCached) {
return (
<MediaGridSkeleton
title={title}
contentInset={false}
header={listHeader}
/>
)
return <MediaGridSkeleton contentInset={false} header={listHeader} />
}
return (
<MediaGridList
title={title}
content={results}
paddingBottom={tabContentBottomInset}
contentInset={false}
@@ -2,11 +2,7 @@ import { renderTabScreenContent } from "@/components/tab-screen-content"
import { Stack } from "expo-router"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import {
inlineTitleOptions,
tabStackScreenTitles,
useStackScreenOptions,
} from "@/lib/navigation"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
export const unstable_settings = {
anchor: "index",
@@ -20,7 +16,6 @@ export default function SearchLayout() {
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...baseOptions,
...inlineTitleOptions,
title: tabStackScreenTitles[route.name] ?? "Search",
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
@@ -35,7 +35,7 @@ export default function SearchScreen() {
: {})}
/>
<SearchResults searchQuery={searchQuery} title="Search" />
<SearchResults searchQuery={searchQuery} />
</>
)
}
+15 -52
View File
@@ -1,8 +1,5 @@
import { useTabletLayout } from "@/hooks/use-tablet-layout"
import {
TabletNowPlaying,
type PlayerPanel,
} from "@/components/tablet-now-playing"
import { TabletNowPlaying } from "@/components/tablet-now-playing"
import { atmosEnabled } from "@/lib/playback-capabilities"
import { NavigationBar } from "expo-navigation-bar"
import { MusicEntityView } from "@/components/music-entity-view"
@@ -54,9 +51,7 @@ import { PlayerSymbol } from "@/components/player-symbol"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { LyricsView } from "@/components/lyrics-view"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { useLyrics } from "@/hooks/use-lyrics"
import { useCoverPalette } from "@/hooks/use-cover-palette"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { useSystemVolume } from "@/hooks/use-system-volume"
@@ -98,14 +93,8 @@ export default function PlayerScreen() {
queueSongIds,
} = usePlaybackQueue()
const { setIsPlaying, skipNext, skipPrevious } = usePlaybackActions()
const params = useLocalSearchParams<{ queue?: string; lyrics?: string }>()
// The queue or lyrics, shown in place of the artwork.
const [panel, setPanel] = useState<PlayerPanel | null>(
params.queue === "1" ? "queue" : params.lyrics === "1" ? "lyrics" : null
)
const showQueue = panel === "queue"
const showLyrics = panel === "lyrics"
const lyrics = useLyrics(currentSong?.id ?? null)
const { queue } = useLocalSearchParams<{ queue?: string }>()
const [showQueue, setShowQueue] = useState(queue === "1")
const [isDismissing, setIsDismissing] = useState(false)
const [stageHeight, setStageHeight] = useState(0)
const user = useCachedQuery(api.auth.currentUser)
@@ -198,8 +187,8 @@ export default function PlayerScreen() {
const handleGesture = useMemo(makeDismissGesture, [makeDismissGesture])
const controlsGesture = useMemo(makeDismissGesture, [makeDismissGesture])
const stageGesture = useMemo(
() => makeDismissGesture().enabled(panel === null),
[makeDismissGesture, panel]
() => makeDismissGesture().enabled(!showQueue),
[makeDismissGesture, showQueue]
)
const hasCover = currentSong ? currentSong.album.cover != null : false
@@ -254,9 +243,9 @@ export default function PlayerScreen() {
setIsPlaying(!isPlaying)
}
function togglePanel(next: PlayerPanel) {
function toggleQueue() {
void Haptics.selectionAsync()
setPanel((value) => (value === next ? null : next))
setShowQueue((value) => !value)
}
if (isTablet) {
@@ -267,9 +256,8 @@ export default function PlayerScreen() {
backgroundStyle={backgroundStyle}
dismissStyle={dismissStyle}
dismissGestures={{ handle: handleGesture, artwork: controlsGesture }}
panel={panel}
togglePanel={togglePanel}
lyrics={lyrics}
showQueue={showQueue}
toggleQueue={toggleQueue}
metadata={songMeta}
/>
</MusicEntityView>
@@ -334,20 +322,6 @@ export default function PlayerScreen() {
/>
</Animated.View>
) : null
) : showLyrics ? (
<Animated.View
key="lyrics"
entering={MODE_FADE_IN}
exiting={MODE_FADE_OUT}
style={[styles.fill, styles.artworkMode]}
>
{queueHeader}
<LyricsView
key={currentSong.id}
lyrics={lyrics}
colors={colors}
/>
</Animated.View>
) : (
<Animated.View
key="artwork"
@@ -435,29 +409,18 @@ export default function PlayerScreen() {
<View style={styles.footer}>
<Pressable
onPress={() => togglePanel("lyrics")}
disabled={!lyrics && !showLyrics}
hitSlop={8}
disabled
accessibilityRole="button"
accessibilityLabel={showLyrics ? "Hide lyrics" : "Show lyrics"}
accessibilityState={{
selected: showLyrics,
disabled: !lyrics && !showLyrics,
}}
style={[
styles.queueButton,
!lyrics && !showLyrics && styles.unavailable,
showLyrics && { backgroundColor: colors.selected },
]}
accessibilityLabel="Lyrics"
accessibilityState={{ disabled: true }}
style={[styles.queueButton, styles.unavailable]}
>
<PlayerSymbol
name="quote.bubble"
fallback={{ material: "lyrics" }}
size={27}
weight="semibold"
color={
showLyrics ? colors.selectedForeground : colors.foreground
}
color={colors.foreground}
/>
</Pressable>
<AudioOutputButton
@@ -465,7 +428,7 @@ export default function PlayerScreen() {
style={styles.queueButton}
/>
<Pressable
onPress={() => togglePanel("queue")}
onPress={toggleQueue}
hitSlop={8}
accessibilityRole="button"
accessibilityLabel={showQueue ? "Hide queue" : "Show queue"}
@@ -1,13 +1,5 @@
import { Ionicons } from "@expo/vector-icons"
import {
Alert,
Pressable,
StyleSheet,
Text,
View,
type StyleProp,
type ViewStyle,
} from "react-native"
import { Alert, Pressable, StyleSheet, Text, View } from "react-native"
import Svg, { Circle, Rect } from "react-native-svg"
import { AudioFormatBadge } from "@/components/audio-format-badge"
@@ -59,20 +51,13 @@ function ProgressRing({
)
}
export type CollectionDownloadTarget = Exclude<
DownloadTarget,
{ kind: "songs" }
>
/** Download, progress, and downloaded states for an album or playlist hero, beside Play. */
export function CollectionDownloadButton({
/** Download, progress, and downloaded states for an album or playlist header. */
export function DownloadHeaderButton({
target,
color,
style,
}: {
target: CollectionDownloadTarget
target: Exclude<DownloadTarget, { kind: "songs" }>
color: string
style?: StyleProp<ViewStyle>
}) {
const { queue, requestDownload, removeDownload } = useDownloads()
useDownloadsVersion()
@@ -111,7 +96,6 @@ export function CollectionDownloadButton({
}
disabled={target.songIds.length === 0}
onPress={handlePress}
style={style}
>
{inProgress && status ? (
<ProgressRing
@@ -120,8 +104,8 @@ export function CollectionDownloadButton({
/>
) : (
<Ionicons
name={done ? "checkmark" : "arrow-down"}
size={24}
name={done ? "checkmark-circle" : "arrow-down-circle-outline"}
size={SIZE + 2}
color={color}
/>
)}
-370
View File
@@ -1,370 +0,0 @@
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"
import {
Pressable,
ScrollView,
StyleSheet,
Text,
View,
type ScrollViewInstance,
} from "react-native"
import Animated, {
cancelAnimation,
Easing,
useAnimatedStyle,
useSharedValue,
withTiming,
type SharedValue,
} from "react-native-reanimated"
import {
usePlaybackActions,
usePlaybackProgress,
usePlaybackQueue,
} from "@/contexts/playback"
import { useLyricsTime } from "@/hooks/use-lyrics"
import type { NowPlayingColors } from "@/lib/now-playing-colors"
import {
activeLineIndex,
type LyricLine,
type LyricWord,
type Lyrics,
} from "@otunes/convex/client/lyrics"
/** How long a manual scroll keeps the view from following the song. */
const MANUAL_SCROLL_HOLD_MS = 3000
/** Where the playing line sits, as a share of the view's height from the top. */
const ACTIVE_LINE_POSITION = 0.12
/** Blur radius by distance from the playing line; farther lines share the last. */
const LINE_BLUR = [0, 1, 2, 3]
/**
* Lyrics in the player's own colors. Synced lines follow playback and seek
* when tapped; `null` lyrics show a short note instead.
*/
export function LyricsView({
lyrics,
colors,
fontSize = 30,
}: {
lyrics: Lyrics | null | undefined
colors: NowPlayingColors
fontSize?: number
}) {
if (lyrics === undefined) return null
if (lyrics === null) {
return (
<View style={styles.empty}>
<Text style={[styles.emptyText, { color: colors.secondaryForeground }]}>
No lyrics
</Text>
</View>
)
}
return <LyricsLines lyrics={lyrics} colors={colors} fontSize={fontSize} />
}
function LyricsLines({
lyrics,
colors,
fontSize,
}: {
lyrics: Lyrics
colors: NowPlayingColors
fontSize: number
}) {
const { currentTime } = usePlaybackProgress()
const { isPlaying } = usePlaybackQueue()
const { seekTo, setIsPlaying } = usePlaybackActions()
const time = useLyricsTime(lyrics, currentTime, isPlaying)
const active = activeLineIndex(lyrics, time)
const synced = lyrics.synced !== "none"
const scrollRef = useRef<ScrollViewInstance>(null)
const lineOffsets = useRef<number[]>([])
const [height, setHeight] = useState(0)
// While the listener scrolls, lines stay sharp and the view stays put.
const [browsing, setBrowsing] = useState(false)
const browseTimer = useRef<ReturnType<typeof setTimeout>>(undefined)
useEffect(() => () => clearTimeout(browseTimer.current), [])
const scrollToLine = useCallback(
(index: number) => {
const y = lineOffsets.current[Math.max(index, 0)]
if (y === undefined || !synced || height === 0 || browsing) return
scrollRef.current?.scrollTo({
y: Math.max(0, y - height * ACTIVE_LINE_POSITION),
animated: true,
})
},
[height, synced, browsing]
)
useEffect(() => {
scrollToLine(active)
}, [active, scrollToLine])
const activeRef = useRef(active)
useEffect(() => {
activeRef.current = active
}, [active])
const handleLineLayout = useCallback(
(index: number, y: number) => {
lineOffsets.current[index] = y
// Opening mid-song: jump once the playing line has been measured.
if (index === Math.max(activeRef.current, 0)) scrollToLine(index)
},
[scrollToLine]
)
const playFrom = useCallback(
(seconds: number) => {
seekTo(seconds)
setIsPlaying(true)
clearTimeout(browseTimer.current)
setBrowsing(false)
},
[seekTo, setIsPlaying]
)
const releaseScroll = () => {
clearTimeout(browseTimer.current)
browseTimer.current = setTimeout(
() => setBrowsing(false),
MANUAL_SCROLL_HOLD_MS
)
}
const lineStyle = useMemo(
() => ({ fontSize, lineHeight: Math.round(fontSize * 1.18) }),
[fontSize]
)
return (
<ScrollView
ref={scrollRef}
style={styles.fill}
contentContainerStyle={{
paddingTop: height * ACTIVE_LINE_POSITION,
paddingBottom: height * 0.7,
}}
showsVerticalScrollIndicator={false}
onLayout={(event) => setHeight(event.nativeEvent.layout.height)}
onScrollBeginDrag={() => {
clearTimeout(browseTimer.current)
setBrowsing(true)
}}
// Hold from when the scroll settles, not when the finger lifted.
onScrollEndDrag={releaseScroll}
onMomentumScrollEnd={releaseScroll}
>
{lyrics.lines.map((line, index) =>
synced ? (
<SyncedLine
key={index}
index={index}
line={line}
distance={
browsing
? 0
: Math.min(Math.abs(index - active), LINE_BLUR.length - 1)
}
active={index === active}
time={index === active ? time : null}
isPlaying={isPlaying}
colors={colors}
textStyle={lineStyle}
onSelect={playFrom}
onLayoutY={handleLineLayout}
/>
) : (
<Text
key={index}
style={[
styles.plainLine,
{
color: colors.foreground,
fontSize: fontSize * 0.75,
lineHeight: Math.round(fontSize * 0.75 * 1.25),
},
line.text === "" && styles.stanzaGap,
]}
>
{line.text}
</Text>
)
)}
</ScrollView>
)
}
/**
* One timed line, blurred by its `distance` from the playing line. Only the
* playing line gets the time, so the others skip re-rendering as the song
* plays.
*/
const SyncedLine = memo(function SyncedLine({
index,
line,
distance,
active,
time,
isPlaying,
colors,
textStyle,
onSelect,
onLayoutY,
}: {
index: number
line: LyricLine
distance: number
active: boolean
time: number | null
isPlaying: boolean
colors: NowPlayingColors
textStyle: { fontSize: number; lineHeight: number }
onSelect: (seconds: number) => void
onLayoutY: (index: number, y: number) => void
}) {
const blur = LINE_BLUR[distance]
return (
<Pressable
onPress={() => onSelect(line.start ?? 0)}
onLayout={(event) => onLayoutY(index, event.nativeEvent.layout.y)}
accessibilityRole="button"
accessibilityHint="Plays from this line"
style={[styles.line, blur > 0 && { filter: [{ blur }] }]}
>
{active && line.words && time !== null ? (
<FilledWords
words={line.words}
time={time}
isPlaying={isPlaying}
colors={colors}
textStyle={textStyle}
/>
) : (
<Text
style={[
styles.lineText,
textStyle,
{
color:
active && !line.words
? colors.foreground
: colors.lyricsInactive,
},
]}
>
{line.text}
</Text>
)}
</Pressable>
)
})
/**
* The playing line's words, each wiping from dim to bright as it is sung.
* Reanimated runs the wipe; playback updates only re-anchor it.
*/
function FilledWords({
words,
time,
isPlaying,
colors,
textStyle,
}: {
words: LyricWord[]
time: number
isPlaying: boolean
colors: NowPlayingColors
textStyle: { fontSize: number; lineHeight: number }
}) {
const sung = useSharedValue(time)
const end = words.at(-1)?.end ?? time
useEffect(() => {
cancelAnimation(sung)
sung.value = time
if (isPlaying && end > time) {
sung.value = withTiming(end, {
duration: (end - time) * 1000,
easing: Easing.linear,
})
}
}, [sung, time, isPlaying, end])
return (
<View style={[styles.words, { columnGap: textStyle.fontSize * 0.25 }]}>
{words.map((word, index) => (
<FilledWord
key={index}
word={word}
sung={sung}
colors={colors}
textStyle={textStyle}
/>
))}
</View>
)
}
function FilledWord({
word,
sung,
colors,
textStyle,
}: {
word: LyricWord
sung: SharedValue<number>
colors: NowPlayingColors
textStyle: { fontSize: number; lineHeight: number }
}) {
const [width, setWidth] = useState(0)
const text = word.text.trim()
const wipe = useAnimatedStyle(() => {
const progress =
(sung.value - word.start) / Math.max(word.end - word.start, 0.05)
return { width: width * Math.min(Math.max(progress, 0), 1) }
})
return (
<View>
<Text
style={[styles.lineText, textStyle, { color: colors.lyricsUnsung }]}
onLayout={(event) => setWidth(event.nativeEvent.layout.width)}
>
{text}
</Text>
<Animated.View style={[styles.wipe, wipe]}>
<Text
numberOfLines={1}
style={[
styles.lineText,
textStyle,
{ color: colors.foreground, width },
]}
>
{text}
</Text>
</Animated.View>
</View>
)
}
const styles = StyleSheet.create({
fill: { flex: 1 },
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
emptyText: { fontSize: 17, fontWeight: "600" },
line: { paddingVertical: 9 },
lineText: { fontWeight: "800" },
words: { flexDirection: "row", flexWrap: "wrap" },
wipe: {
position: "absolute",
top: 0,
bottom: 0,
left: 0,
overflow: "hidden",
},
plainLine: { fontWeight: "700", paddingVertical: 2 },
stanzaGap: { height: 18 },
})
+2 -25
View File
@@ -4,7 +4,6 @@ import { tabletLayoutTransition } from "@/lib/tablet-motion"
import { TabletMediaGrid } from "@/components/tablet-media-grid"
import { useMediaGridLayout } from "@/hooks/use-media-grid-layout"
import { MusicEntityView } from "@/components/music-entity-view"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { Link } from "expo-router"
import { Ionicons } from "@expo/vector-icons"
import { memo, useCallback, type ReactElement } from "react"
@@ -301,21 +300,17 @@ export function MediaGridList({
onEndReached,
ListHeaderComponent,
contentInset = true,
title,
}: {
content: MediaItem[]
paddingBottom: number
onEndReached?: () => void
ListHeaderComponent?: ReactElement
contentInset?: boolean
/** iOS `ScreenTitle` shown above the grid; it replaces the top inset. */
title?: string
}) {
const tabletLayout = useTabletLayout()
const { columns, cardWidth, onLayout, horizontalPadding, gap } =
useMediaGridLayout()
const colors = useThemeColors()
const { ref, scrollY } = useScreenTitleScroll<FlatList<MediaItem>>()
const renderItem = useCallback(
({ item }: ListRenderItemInfo<MediaItem>) => (
<View style={{ width: cardWidth }}>
@@ -333,30 +328,13 @@ export function MediaGridList({
onEndReached={onEndReached}
ListHeaderComponent={ListHeaderComponent}
contentInset={contentInset}
title={title}
renderCard={renderTabletCard}
/>
)
}
const header = title ? (
<View>
<ScreenTitle
title={title}
scrollY={scrollY}
// Inset grids already pad the whole list horizontally.
style={{ paddingHorizontal: contentInset ? 0 : horizontalPadding }}
/>
{ListHeaderComponent}
</View>
) : (
ListHeaderComponent
)
return (
<Animated.FlatList
ref={ref}
scrollEventThrottle={16}
<FlatList
key={columns}
onLayout={onLayout}
data={content}
@@ -373,7 +351,6 @@ export function MediaGridList({
paddingBottom,
gap,
...(contentInset ? { paddingHorizontal: horizontalPadding } : {}),
...(title ? { paddingTop: 0 } : {}),
},
]}
columnWrapperStyle={[
@@ -382,7 +359,7 @@ export function MediaGridList({
{ gap },
]}
contentInsetAdjustmentBehavior="automatic"
ListHeaderComponent={header}
ListHeaderComponent={ListHeaderComponent}
onEndReached={onEndReached}
onEndReachedThreshold={0.5}
/>
+21 -10
View File
@@ -77,39 +77,44 @@ const QUEUE_ACTIONS: MediaAction[] = ["play-next", "play-last", "shuffle"]
const MEDIA_ACTION_ITEMS: {
action: MediaAction
label: (favorited: boolean | undefined, playlistLabel: string) => string
label: (
countSuffix: string,
favorited: boolean | undefined,
playlistLabel: string
) => string
image: NonNullable<MenuAction["image"]> & string
destructive?: boolean
}[] = [
{
action: "playlist",
label: (_favorited, playlistLabel) => playlistLabel,
label: (countSuffix, _favorited, playlistLabel) =>
`${playlistLabel}${countSuffix}`,
image: "text.badge.plus",
},
{
action: "download",
label: () => "Download",
label: (countSuffix) => `Download${countSuffix}`,
image: "arrow.down.circle",
},
{
action: "remove-download",
label: () => "Remove Download",
label: (countSuffix) => `Remove Download${countSuffix}`,
image: "xmark.circle",
destructive: true,
},
{
action: "play-next",
label: () => "Play Next",
label: (countSuffix) => `Play Next${countSuffix}`,
image: "text.line.first.and.arrowtriangle.forward",
},
{
action: "play-last",
label: () => "Play Last",
label: (countSuffix) => `Play Last${countSuffix}`,
image: "text.line.last.and.arrowtriangle.forward",
},
{
action: "shuffle",
label: () => "Shuffle",
label: (countSuffix) => `Shuffle${countSuffix}`,
image: "shuffle",
},
{
@@ -129,7 +134,8 @@ const MEDIA_ACTION_ITEMS: {
},
{
action: "favorite",
label: (favorited) => (favorited ? "Unfavorite" : "Favorite"),
label: (countSuffix, favorited) =>
`${favorited ? "Unfavorite" : "Favorite"}${countSuffix}`,
image: "star",
},
{
@@ -200,7 +206,12 @@ function isActionIncluded(
export function buildMediaMenuActions(
config: Omit<MediaMenuConfig, "onAction">
): MenuAction[] {
const { favorited, playlistLabel = "Add to Playlist" } = config
const {
selectedCount = 1,
favorited,
playlistLabel = "Add to Playlist",
} = config
const countSuffix = selectedCount > 1 ? ` (${selectedCount})` : ""
const actions: MenuAction[] = []
@@ -219,7 +230,7 @@ export function buildMediaMenuActions(
actions.push({
id: item.action,
title: item.label(favorited, playlistLabel),
title: item.label(countSuffix, favorited, playlistLabel),
image: item.action === "favorite" && favorited ? "star.fill" : item.image,
...(item.destructive ? { attributes: { destructive: true } } : {}),
})
-109
View File
@@ -1,109 +0,0 @@
import { Ionicons } from "@expo/vector-icons"
import {
connectivityStore,
type PlatformNetwork,
} from "@otunes/convex/client/connectivity"
import { useConvex } from "convex/react"
import {
addNetworkStateListener,
getNetworkStateAsync,
type NetworkState,
} from "expo-network"
import { useTheme } from "expo-router"
import { useContext, useSyncExternalStore } from "react"
import { Pressable, StyleSheet, Text, View } from "react-native"
import { useAppNavigation } from "@/lib/app-navigation"
import { TabletSectionContext } from "@/lib/tablet-navigation"
import { spacing, useThemeColors } from "@/lib/theme"
let deviceOnline = true
/** The device's network state. Unknown reachability counts as online. */
const deviceNetwork: PlatformNetwork = {
isOnline: () => deviceOnline,
subscribe(onChange) {
const apply = (state: NetworkState) => {
deviceOnline =
state.isConnected !== false && state.isInternetReachable !== false
onChange()
}
const subscription = addNetworkStateListener(apply)
void getNetworkStateAsync().then(apply)
return () => subscription.remove()
},
}
/** True while the device has no network or the server can't be reached. */
export function useIsOffline() {
const store = connectivityStore(useConvex(), deviceNetwork)
return useSyncExternalStore(store.subscribe, store.getSnapshot)
}
type ScreenRoute = { name: string; params?: object }
/** Downloads screens, and albums and playlists opened from them, stay usable offline. */
function worksOffline(route: ScreenRoute, tabletSection: string | undefined) {
if (route.name.startsWith("downloads/")) return true
if (route.name === "index" && tabletSection === "downloads") return true
// Settings stays reachable so an unreachable server can be changed.
if (route.name === "settings") return true
return (route.params as { from?: string } | undefined)?.from === "downloads"
}
/**
* Covers a tab screen with a no-connection message while offline. The screen
* stays mounted underneath so it picks up where it was once the server is back.
*/
export function OfflineOverlay({ route }: { route: ScreenRoute }) {
const offline = useIsOffline()
const tabletSection = useContext(TabletSectionContext)?.name
const { push } = useAppNavigation()
const { colors: routerColors } = useTheme()
const colors = useThemeColors()
if (!offline || worksOffline(route, tabletSection)) return null
return (
<View
style={[
StyleSheet.absoluteFill,
styles.overlay,
{ backgroundColor: routerColors.background },
]}
>
<Ionicons
name="cloud-offline-outline"
size={28}
color={colors.mutedForeground}
/>
<Text style={[styles.title, { color: routerColors.text }]}>
No connection
</Text>
<Text style={[styles.body, { color: colors.mutedForeground }]}>
Your downloads still play.
</Text>
<Pressable
accessibilityRole="link"
hitSlop={spacing.sm}
onPress={() => push("/downloads")}
>
<Text style={[styles.link, { color: colors.primary }]}>
Go to Downloads
</Text>
</Pressable>
</View>
)
}
const styles = StyleSheet.create({
overlay: {
alignItems: "center",
justifyContent: "center",
gap: spacing.sm,
padding: spacing.lg,
},
title: { fontSize: 17, fontWeight: "600", marginTop: spacing.xs },
body: { fontSize: 15, textAlign: "center" },
link: { fontSize: 15, fontWeight: "600", marginTop: spacing.xs },
})
+3 -12
View File
@@ -10,7 +10,7 @@ import {
} from "@/contexts/downloads"
import type { DownloadSource } from "@otunes/convex/client/download-queue"
import { useServerConfig } from "@/contexts/server-config"
import type { BrowseSong, SearchSong } from "@otunes/convex/types"
import type { BrowseSong } from "@otunes/convex/types"
import type { CoverPalette } from "@/lib/cover-palette"
import { formatDuration } from "@/lib/format"
import { albumCoverUrl } from "@/lib/urls"
@@ -41,8 +41,7 @@ export const SongRow = memo(function SongRow({
swipe,
downloadFrom,
}: {
/** Search results also show the lyrics line they matched. */
song: SearchSong
song: BrowseSong
onPress?: () => void
contextMenu?: Omit<MediaMenuConfig, "onAction"> & {
onAction: MediaMenuConfig["onAction"]
@@ -88,14 +87,6 @@ export const SongRow = memo(function SongRow({
>
{song.artist.name} · {song.album.title}
</Text>
{song.lyricsSnippet ? (
<Text
style={[styles.rowSubtitle, { color: secondaryForeground }]}
numberOfLines={1}
>
Lyrics: “{song.lyricsSnippet}”
</Text>
) : null}
</View>
{downloaded || downloadState === "device" ? (
<Ionicons
@@ -190,7 +181,7 @@ export const SongListRow = memo(function SongListRow({
onPlay,
onAction,
}: {
song: SearchSong
song: BrowseSong
favorited: boolean
playlistLabel?: string
palette?: Pick<CoverPalette, "foreground" | "secondaryForeground" | "divider">
@@ -2,23 +2,16 @@ import { useCallback, useMemo } from "react"
import { Platform } from "react-native"
import { Stack } from "expo-router"
import { useQuery } from "convex/react"
import { useDebouncedSearch } from "@/hooks/use-debounced-search"
import { api } from "@otunes/convex/_generated/api"
import { useThemeColors } from "@/lib/theme"
import { filterSongs } from "@otunes/convex/client/song-search"
import type { BrowseSong } from "@otunes/convex/types"
export function usePlaylistSearch(songs: BrowseSong[]) {
const search = useDebouncedSearch()
const lyricsMatches = useQuery(
api.lyrics.matchingSongIds,
search.searchQuery.trim() ? { query: search.searchQuery } : "skip"
)
const filteredSongs = useMemo(
() => filterSongs(songs, search.searchQuery, lyricsMatches),
[songs, search.searchQuery, lyricsMatches]
() => filterSongs(songs, search.searchQuery),
[songs, search.searchQuery]
)
return { ...search, filteredSongs }
-84
View File
@@ -1,84 +0,0 @@
import { useHeaderHeight } from "expo-router/react-navigation"
import type { Component } from "react"
import {
Platform,
StyleSheet,
type ScrollViewInstance,
type StyleProp,
type TextStyle,
} from "react-native"
import Animated, {
useAnimatedRef,
useAnimatedStyle,
useScrollOffset,
type SharedValue,
} from "react-native-reanimated"
import { spacing, useThemeColors } from "@/lib/theme"
/**
* Tracks the scroll view that renders a `ScreenTitle`. Attach `ref` to that
* Reanimated `Animated.ScrollView` / `Animated.FlatList` and pass `scrollY`
* to the title.
*/
export function useScreenTitleScroll<
TScrollView extends Component | ScrollViewInstance,
>() {
const ref = useAnimatedRef<TScrollView>()
const scrollY = useScrollOffset(ref)
return { ref, scrollY }
}
/**
* iOS screen title rendered as the first item of a screen's scroll content,
* in place of the native large title (Apple Music style): it scrolls away
* with the content, never collapses into the bar, and stays put on
* pull-down. Android keeps its native header title, so this renders nothing.
*/
export function ScreenTitle({
title,
scrollY,
style,
}: {
title: string
/** From `useScreenTitleScroll`; omit for screens that never scroll. */
scrollY?: SharedValue<number>
style?: StyleProp<TextStyle>
}) {
const colors = useThemeColors()
// At rest the scroll offset is minus the automatic header inset, so any
// offset below that is overscroll the title should cancel out.
const headerHeight = useHeaderHeight()
const pinStyle = useAnimatedStyle(() => ({
transform: [
{
translateY: scrollY ? Math.min(0, scrollY.value + headerHeight) : 0,
},
],
}))
if (Platform.OS !== "ios") return null
return (
<Animated.Text
accessibilityRole="header"
numberOfLines={2}
style={[styles.title, { color: colors.foreground }, style, pinStyle]}
>
{title}
</Animated.Text>
)
}
// Matches UIKit's large title metrics: 34pt bold in a 52pt tall area.
const styles = StyleSheet.create({
title: {
fontSize: 34,
lineHeight: 41,
fontWeight: "700",
letterSpacing: 0.37,
paddingHorizontal: spacing.lg,
paddingTop: 3,
paddingBottom: 8,
},
})
+15 -24
View File
@@ -1,15 +1,13 @@
import { memo, useCallback, useMemo } from "react"
import {
type FlatList,
FlatList,
StyleSheet,
Text,
View,
type ListRenderItemInfo,
} from "react-native"
import Animated from "react-native-reanimated"
import { ContentCarousel } from "@/components/media-cards"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import type { MediaAction } from "@/components/media-context-menu"
import { tabContentBottomInset, SongListRow } from "@/components/player"
import { SongListSkeleton } from "@/components/skeletons"
@@ -18,19 +16,11 @@ import { usePlaybackActions } from "@/contexts/playback"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api"
import type { BrowseSong, SearchSong } from "@otunes/convex/types"
import type { BrowseSong } from "@otunes/convex/types"
import { spacing, useThemeColors } from "@/lib/theme"
function SearchResultsBody({
searchQuery,
title,
}: {
searchQuery: string
/** iOS `ScreenTitle`, shown above the results and while idle. */
title: string
}) {
function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
const colors = useThemeColors()
const { ref, scrollY } = useScreenTitleScroll<FlatList<BrowseSong>>()
const { playFromSong } = usePlaybackActions()
const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions()
@@ -74,7 +64,7 @@ function SearchResultsBody({
[handleSongAction]
)
const renderItem = useCallback(
({ item: song }: ListRenderItemInfo<SearchSong>) => (
({ item: song }: ListRenderItemInfo<BrowseSong>) => (
<SongListRow
song={song}
favorited={isSongFavorite(song.id)}
@@ -86,14 +76,16 @@ function SearchResultsBody({
)
if (isSearching) {
return <SongListSkeleton title={title} />
return <SongListSkeleton />
}
if (!hasQuery) {
return <></>
}
return (
<Animated.FlatList
ref={ref}
scrollEventThrottle={16}
data={hasQuery ? (results?.songs ?? []) : []}
<FlatList
data={results?.songs ?? []}
keyExtractor={(song) => song.id}
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{ paddingBottom: tabContentBottomInset }}
@@ -101,8 +93,7 @@ function SearchResultsBody({
keyboardShouldPersistTaps="handled"
ListHeaderComponent={
<>
<ScreenTitle title={title} scrollY={scrollY} />
{hasQuery && !hasResults ? (
{!hasResults ? (
<View style={styles.empty}>
<Text
style={[styles.emptyText, { color: colors.mutedForeground }]}
@@ -112,13 +103,13 @@ function SearchResultsBody({
</View>
) : null}
{hasQuery && results?.artists.length ? (
{results?.artists.length ? (
<View style={styles.section}>
<ContentCarousel title="Artists" content={results.artists} />
</View>
) : null}
{hasQuery && results?.albums.length ? (
{results?.albums.length ? (
<View style={styles.section}>
<ContentCarousel title="Albums" content={results.albums} />
</View>
@@ -127,7 +118,7 @@ function SearchResultsBody({
}
renderItem={renderItem}
ListFooterComponent={
hasQuery && playlistResults && playlistResults.length > 0 ? (
playlistResults && playlistResults.length > 0 ? (
<View style={styles.section}>
<ContentCarousel title="Playlists" content={playlistResults} />
</View>
+5 -49
View File
@@ -9,7 +9,6 @@ import {
collectionInset,
} from "@/components/collection-list"
import { tabletCardTextHeight } from "@/components/tablet-media-grid"
import { ScreenTitle } from "@/components/screen-title"
import { Link } from "expo-router"
import { useHeaderHeight } from "expo-router/react-navigation"
import Reanimated from "react-native-reanimated"
@@ -152,16 +151,9 @@ function SongRows({ rows, inset }: { rows: number; inset?: boolean }) {
))
}
export function SongListSkeleton({
rows = 10,
title,
}: {
rows?: number
title?: string
}) {
export function SongListSkeleton({ rows = 10 }: { rows?: number }) {
return (
<SkeletonScreen>
{title ? <ScreenTitle title={title} /> : null}
<SongRows rows={rows} />
</SkeletonScreen>
)
@@ -242,45 +234,23 @@ export function MediaGridSkeleton({
items = 6,
contentInset = true,
header,
title,
}: {
items?: number
contentInset?: boolean
/** The loaded list's `ListHeaderComponent`, so it keeps its position. */
header?: ReactNode
/** The loaded list's `ScreenTitle`, which replaces its top inset. */
title?: string
}) {
return (
<SkeletonScreen>
<MediaGridContent
items={items}
contentInset={contentInset && !title}
header={
title ? (
<>
<MediaGridTitle title={title} />
{header}
</>
) : (
header
)
}
contentInset={contentInset}
header={header}
/>
</SkeletonScreen>
)
}
function MediaGridTitle({ title }: { title: string }) {
const { horizontalPadding } = useMediaGridLayout()
return (
<ScreenTitle
title={title}
style={{ paddingHorizontal: horizontalPadding }}
/>
)
}
export function CarouselSkeleton() {
return (
<View style={styles.carousel}>
@@ -294,11 +264,10 @@ export function CarouselSkeleton() {
)
}
export function HomeSkeleton({ title }: { title: string }) {
export function HomeSkeleton() {
return (
<SkeletonScreen>
<View style={styles.home}>
<ScreenTitle title={title} style={styles.homeTitle} />
<CarouselSkeleton />
<CarouselSkeleton />
</View>
@@ -419,17 +388,10 @@ export function CollectionDetailSkeleton({
)
}
export function ArtistListSkeleton({
rows = 12,
title,
}: {
rows?: number
title?: string
}) {
export function ArtistListSkeleton({ rows = 12 }: { rows?: number }) {
const colors = useThemeColors()
return (
<SkeletonScreen>
{title ? <ScreenTitle title={title} /> : null}
{Array.from({ length: rows }, (_, index) => (
<View
key={index}
@@ -494,12 +456,6 @@ const styles = StyleSheet.create({
carousel: { gap: spacing.md, overflow: "hidden" },
carouselRow: { flexDirection: "row", gap: spacing.md },
home: { padding: spacing.lg, gap: spacing.xl },
// Mirrors the home screen's title spacing.
homeTitle: {
paddingHorizontal: 0,
marginTop: -spacing.lg,
marginBottom: -spacing.md,
},
centeredHero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm },
actions: {
flexDirection: "row",
+5 -42
View File
@@ -5,46 +5,16 @@ import type { ReactNode } from "react"
import { useTabletBackgroundStyle } from "@/contexts/android-tab-theme"
import { TabletPlayerLayoutSync } from "@/contexts/tablet-player-layout"
import { OfflineOverlay } from "@/components/offline-overlay"
import { TabletSidebar } from "@/components/tablet-sidebar"
type ScreenRoute = { name: string; params?: object }
/**
* Screen content with the no-connection overlay layered on top. A fragment
* keeps the scroll view as the screen's first subview for large titles.
*/
function ScreenBody({
route,
children,
}: {
route: ScreenRoute
children: ReactNode
}) {
return (
<>
{children}
<OfflineOverlay route={route} />
</>
)
}
/** Apply sidebar insets natively, before Yoga measures the content pane. */
export function TabScreenContent({
route,
children,
}: {
route: ScreenRoute
children: ReactNode
}) {
export function TabScreenContent({ children }: { children: ReactNode }) {
const backgroundStyle = useTabletBackgroundStyle()
if (Platform.OS !== "ios" || !Platform.isPad) {
return <ScreenBody route={route}>{children}</ScreenBody>
}
if (Platform.OS !== "ios" || !Platform.isPad) return <>{children}</>
return (
<Animated.View style={[{ flex: 1 }, backgroundStyle]}>
<SafeAreaView edges={["left", "right"]} style={{ flex: 1 }}>
<ScreenBody route={route}>{children}</ScreenBody>
{children}
</SafeAreaView>
<TabletSidebar />
<TabletPlayerLayoutSync />
@@ -52,13 +22,6 @@ export function TabScreenContent({
)
}
/** `screenLayout` for every tab stack. */
export function renderTabScreenContent({
route,
children,
}: {
route: ScreenRoute
children: ReactNode
}) {
return <TabScreenContent route={route}>{children}</TabScreenContent>
export function renderTabScreenContent({ children }: { children: ReactNode }) {
return <TabScreenContent>{children}</TabScreenContent>
}
+5 -20
View File
@@ -6,7 +6,7 @@ import {
type ReactElement,
} from "react"
import {
type ScrollViewInstance,
ScrollView,
View,
type NativeSyntheticEvent,
type NativeScrollEvent,
@@ -15,7 +15,6 @@ import Animated from "react-native-reanimated"
import { useSafeAreaInsets } from "react-native-safe-area-context"
import type { MediaItem } from "@/components/media-cards"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { useMediaGridLayout } from "@/hooks/use-media-grid-layout"
import { tabletLayoutTransition } from "@/lib/tablet-motion"
import { useThemeColors } from "@/lib/theme"
@@ -29,8 +28,6 @@ type GridProps = {
onEndReached?: () => void
ListHeaderComponent?: ReactElement
contentInset?: boolean
/** iOS `ScreenTitle` shown above the grid; it replaces the top inset. */
title?: string
renderCard: (item: MediaItem, width: number) => ReactElement
}
@@ -44,12 +41,9 @@ export function TabletMediaGrid({
onEndReached,
ListHeaderComponent,
contentInset = true,
title,
renderCard,
}: GridProps) {
const colors = useThemeColors()
const { ref, scrollY: titleScrollY } =
useScreenTitleScroll<ScrollViewInstance>()
const insets = useSafeAreaInsets()
const { columns, cardWidth, onLayout, horizontalPadding, gap, ready } =
useMediaGridLayout()
@@ -108,27 +102,18 @@ export function TabletMediaGrid({
setViewportHeight(event.nativeEvent.layout.height)
}}
>
<Animated.ScrollView
ref={ref}
<ScrollView
onScroll={onScroll}
// Every frame, so the title pins smoothly on pull-down.
scrollEventThrottle={16}
scrollEventThrottle={32}
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={{
paddingTop: contentInset && !title ? horizontalPadding : 0,
paddingTop: contentInset ? horizontalPadding : 0,
paddingBottom: paddingBottom + insets.bottom,
}}
>
<View
onLayout={(event) => setHeaderHeight(event.nativeEvent.layout.height)}
>
{title ? (
<ScreenTitle
title={title}
scrollY={titleScrollY}
style={{ paddingHorizontal: horizontalPadding }}
/>
) : null}
{ListHeaderComponent}
</View>
<View style={{ height: gridHeight }}>
@@ -151,7 +136,7 @@ export function TabletMediaGrid({
)
})}
</View>
</Animated.ScrollView>
</ScrollView>
</Animated.View>
)
}
+4 -12
View File
@@ -23,7 +23,6 @@ import { PlayerSymbol } from "@/components/player-symbol"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { useLyrics } from "@/hooks/use-lyrics"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { tabletMiniPlayerHeight } from "@/lib/theme"
import { albumCoverUrl } from "@/lib/urls"
@@ -59,7 +58,6 @@ export function TabletMiniPlayer() {
const { handleSongAction } = useMediaMenuActions()
const { isSongFavorite } = useFavorites()
const roomy = width - insets.left - insets.right >= 650
const lyrics = useLyrics(roomy ? (currentSong?.id ?? null) : null)
if (!focused || !config || !currentSong || queueSongIds.length === 0)
return null
@@ -168,22 +166,16 @@ export function TabletMiniPlayer() {
{roomy ? (
<Pressable
style={styles.control}
disabled={!lyrics}
onPress={() =>
router.push({
pathname: "/(app)/player",
params: { lyrics: "1" },
})
}
disabled
accessibilityRole="button"
accessibilityLabel="Show lyrics"
accessibilityState={{ disabled: !lyrics }}
accessibilityLabel="Lyrics"
accessibilityState={{ disabled: true }}
>
<PlayerSymbol
name="quote.bubble"
fallback="chatbox-outline"
size={23}
color={lyrics ? color : inactive}
color={inactive}
/>
</Pressable>
) : null}
+21 -46
View File
@@ -15,7 +15,6 @@ import { StatusBar } from "expo-status-bar"
import { AudioOutputButton } from "@/components/audio-output-button"
import { CoverImage } from "@/components/cover-image"
import { LyricsView } from "@/components/lyrics-view"
import { NowPlayingQueue } from "@/components/now-playing-queue"
import { PlayerProgress } from "@/components/player-progress"
import { PlayerSlider } from "@/components/player-slider"
@@ -25,10 +24,6 @@ import { useServerConfig } from "@/contexts/server-config"
import { useSystemVolume } from "@/hooks/use-system-volume"
import type { NowPlayingColors } from "@/lib/now-playing-colors"
import { albumCoverUrl } from "@/lib/urls"
import type { Lyrics } from "@otunes/convex/client/lyrics"
/** What the Now Playing screen shows beside or instead of the artwork. */
export type PlayerPanel = "queue" | "lyrics"
const queueMotion = {
duration: 420,
@@ -36,18 +31,14 @@ const queueMotion = {
reduceMotion: ReduceMotion.System,
}
/**
* Tablet player keeps transport controls visible while the queue or lyrics
* open beside them.
*/
/** Tablet player keeps transport controls visible while the queue opens beside them. */
export function TabletNowPlaying({
colors,
backgroundStyle,
dismissStyle,
dismissGestures,
panel,
togglePanel,
lyrics,
showQueue,
toggleQueue,
metadata,
}: {
colors: NowPlayingColors
@@ -57,9 +48,8 @@ export function TabletNowPlaying({
handle: ReturnType<typeof Gesture.Pan>
artwork: ReturnType<typeof Gesture.Pan>
}
panel: PlayerPanel | null
togglePanel: (panel: PlayerPanel) => void
lyrics: Lyrics | null | undefined
showQueue: boolean
toggleQueue: () => void
metadata: ReactNode
}) {
const router = useRouter()
@@ -73,9 +63,7 @@ export function TabletNowPlaying({
const { volume, setVolume, available: volumeAvailable } = useSystemVolume()
const [queueHeight, setQueueHeight] = useState(0)
const wideLayout = width >= 700
const showQueue = panel === "queue"
const showLyrics = panel === "lyrics"
const sideBySide = panel !== null && wideLayout
const sideBySide = showQueue && wideLayout
const progress = useSharedValue(sideBySide ? 1 : 0)
useEffect(() => {
progress.value = withTiming(sideBySide ? 1 : 0, queueMotion)
@@ -136,14 +124,7 @@ export function TabletNowPlaying({
/>
</Pressable>
)
const panelContent = showLyrics ? (
<LyricsView
key={currentSong.id}
lyrics={lyrics}
colors={colors}
fontSize={34}
/>
) : (
const queue = (
<NowPlayingQueue
tablet
colors={colors}
@@ -260,18 +241,20 @@ export function TabletNowPlaying({
</Animated.View>
{wideLayout ? (
<Animated.View
pointerEvents={panel ? "auto" : "none"}
accessibilityElementsHidden={!panel}
importantForAccessibility={panel ? "auto" : "no-hide-descendants"}
pointerEvents={showQueue ? "auto" : "none"}
accessibilityElementsHidden={!showQueue}
importantForAccessibility={
showQueue ? "auto" : "no-hide-descendants"
}
style={[styles.queue, queueStyle]}
onLayout={(event) =>
setQueueHeight(event.nativeEvent.layout.height)
}
>
{queueHeight > 0 ? panelContent : null}
{queueHeight > 0 ? queue : null}
</Animated.View>
) : null}
{panel && !sideBySide ? (
{showQueue && !sideBySide ? (
<View
style={[
styles.portraitQueue,
@@ -281,7 +264,7 @@ export function TabletNowPlaying({
setQueueHeight(event.nativeEvent.layout.height)
}
>
{queueHeight > 0 ? panelContent : null}
{queueHeight > 0 ? queue : null}
</View>
) : null}
</View>
@@ -297,29 +280,21 @@ export function TabletNowPlaying({
/>
<View style={styles.footerActions}>
<Pressable
onPress={() => togglePanel("lyrics")}
disabled={!lyrics && !showLyrics}
disabled
accessibilityRole="button"
accessibilityLabel={showLyrics ? "Hide lyrics" : "Show lyrics"}
accessibilityState={{
selected: showLyrics,
disabled: !lyrics && !showLyrics,
}}
style={[
styles.footerButton,
!lyrics && !showLyrics && { opacity: 0.4 },
showLyrics && { backgroundColor: colors.selected },
]}
accessibilityLabel="Lyrics"
accessibilityState={{ disabled: true }}
style={[styles.footerButton, { opacity: 0.4 }]}
>
<PlayerSymbol
name="quote.bubble"
fallback="chatbox-outline"
size={25}
color={showLyrics ? colors.selectedForeground : colors.foreground}
color={colors.foreground}
/>
</Pressable>
<Pressable
onPress={() => togglePanel("queue")}
onPress={toggleQueue}
accessibilityRole="button"
accessibilityLabel={showQueue ? "Hide queue" : "Show queue"}
accessibilityState={{ selected: showQueue }}
+22 -14
View File
@@ -198,8 +198,7 @@ function optionDetail(option: SizedDownloadOption, songCount: number) {
return `${included} of ${songCount} songs, ${option.fallbackCount} in High`
}
/** Centered popup asking which quality to download a target at. */
function DownloadQualityPopup({
function DownloadQualitySheet({
pending,
onClose,
onPick,
@@ -215,7 +214,7 @@ function DownloadQualityPopup({
return (
<Modal
visible={pending !== null}
animationType="fade"
animationType="slide"
transparent
onRequestClose={onClose}
>
@@ -223,11 +222,14 @@ function DownloadQualityPopup({
<Pressable style={styles.overlay} onPress={onClose}>
<Pressable
style={[
styles.popup,
styles.sheet,
{ backgroundColor: colors.card, borderColor: colors.border },
]}
onPress={(event) => event.stopPropagation()}
>
<View
style={[styles.grabber, { backgroundColor: colors.border }]}
/>
<Text style={[styles.title, { color: colors.foreground }]}>
Download Quality
</Text>
@@ -431,7 +433,7 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
<DownloadsContext.Provider value={value}>
{children}
{queue ? <DownloadSync queue={queue} /> : null}
<DownloadQualityPopup
<DownloadQualitySheet
pending={pending}
onClose={() => setPending(null)}
onPick={handlePick}
@@ -443,17 +445,23 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
const styles = StyleSheet.create({
overlay: {
flex: 1,
backgroundColor: "rgba(0,0,0,0.6)",
justifyContent: "center",
alignItems: "center",
padding: 24,
backgroundColor: "rgba(0,0,0,0.45)",
justifyContent: "flex-end",
},
popup: {
width: "100%",
maxWidth: 420,
borderRadius: 16,
sheet: {
borderTopLeftRadius: 16,
borderTopRightRadius: 16,
borderWidth: 1,
padding: 16,
paddingHorizontal: 16,
paddingTop: 8,
paddingBottom: 24,
},
grabber: {
width: 36,
height: 4,
borderRadius: 2,
alignSelf: "center",
marginBottom: 12,
},
title: { fontSize: 18, fontWeight: "700" },
subtitle: { fontSize: 13, marginBottom: 4 },
+2 -4
View File
@@ -9,15 +9,13 @@
"APP_VARIANT": "development"
},
"developmentClient": true,
"distribution": "internal",
"credentialsSource": "local"
"distribution": "internal"
},
"preview": {
"env": {
"APP_VARIANT": "preview"
},
"distribution": "internal",
"credentialsSource": "local"
"distribution": "internal"
},
"production": {
"env": {
-109
View File
@@ -1,109 +0,0 @@
import { File } from "expo-file-system"
import { useEffect, useMemo, useState, useSyncExternalStore } from "react"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import {
followLyrics,
parseLyrics,
type Lyrics,
} from "@otunes/convex/client/lyrics"
import { readLyricsTag } from "@otunes/convex/client/lyrics-tags"
import { useDownloads } from "@/contexts/downloads"
import { useServerConfig } from "@/contexts/server-config"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { downloadedAudioUri } from "@/lib/downloads"
// Lyrics read from downloaded files, by file. Files do not change once saved.
const localLyrics = new Map<string, Promise<string | null>>()
async function readFileLyrics(uri: string) {
const handle = new File(uri).open()
try {
const text = await readLyricsTag({
size: handle.size ?? 0,
read: (offset, length) => {
handle.offset = offset
return handle.readBytes(length)
},
})
return text?.trim() || null
} finally {
handle.close()
}
}
function readLocalLyrics(uri: string) {
let lyrics = localLyrics.get(uri)
if (!lyrics) {
lyrics = readFileLyrics(uri).catch(() => null)
localLyrics.set(uri, lyrics)
}
return lyrics
}
const noopSubscribe = () => () => {}
/**
* A song's lyrics: from its downloaded file when there is one, otherwise from
* the server. `undefined` while loading, `null` when the song has none.
*/
export function useLyrics(songId: Id<"songs"> | null) {
const { config } = useServerConfig()
const { queue } = useDownloads()
const fileUri = useSyncExternalStore(queue?.subscribe ?? noopSubscribe, () =>
songId && config && queue?.getDownloaded(songId)
? downloadedAudioUri(config, songId)
: null
)
const [local, setLocal] = useState<{ uri: string; text: string | null }>()
useEffect(() => {
if (!fileUri) return
let current = true
void readLocalLyrics(fileUri).then((text) => {
if (current) setLocal({ uri: fileUri, text })
})
return () => {
current = false
}
}, [fileUri])
const localText = fileUri && local?.uri === fileUri ? local.text : undefined
// Songs without a downloaded copy, or whose copy has no lyrics tag.
const remote = useCachedQuery(
api.lyrics.forSong,
songId && (!fileUri || localText === null) ? { id: songId } : "skip"
)
const text = localText || remote
return useMemo<Lyrics | null | undefined>(() => {
if (!songId) return null
if (text === undefined) return undefined
return text ? parseLyrics(text) : null
}, [songId, text])
}
/**
* The playback time for highlighting lyrics: the player's `currentTime`,
* advanced by `followLyrics` between its progress updates.
*/
export function useLyricsTime(
lyrics: Lyrics | null | undefined,
currentTime: number,
isPlaying: boolean
) {
// Time reached since the player last reported `from`.
const [advanced, setAdvanced] = useState<{ from: number; time: number }>()
useEffect(() => {
if (!lyrics || !isPlaying) return
return followLyrics(lyrics, currentTime, (time) =>
setAdvanced({ from: currentTime, time })
)
}, [lyrics, currentTime, isPlaying])
return isPlaying && advanced?.from === currentTime
? advanced.time
: currentTime
}
+1 -8
View File
@@ -17,20 +17,13 @@ export const tabStackScreenTitles: Record<string, string> = {
"downloads/other": "Other Downloaded Songs",
}
/**
* iOS tab stacks render their titles in the scroll content with
* `ScreenTitle`, so the bar keeps the title (for back menus) but hides it.
*/
export const inlineTitleOptions: StackScreenOptions =
Platform.OS === "ios" ? { headerTitleStyle: { color: "transparent" } } : {}
export function useStackScreenOptions(
overrides?: StackScreenOptions
): StackScreenOptions {
const theme = useThemeColors()
return {
headerLargeTitle: false,
headerLargeTitle: true,
headerTransparent: true,
headerTintColor: theme.foreground,
headerLargeTitleStyle: { color: theme.foreground },
-6
View File
@@ -12,10 +12,6 @@ export type NowPlayingColors = {
selected: string
selectedForeground: string
highlight: string
/** Lyrics lines other than the one playing. */
lyricsInactive: string
/** Words of the playing line not yet sung. */
lyricsUnsung: string
isDark: boolean
}
@@ -32,8 +28,6 @@ export function nowPlayingColors(palette: CoverPalette): NowPlayingColors {
selected: withAlpha(foreground, 0.8),
selectedForeground: palette.background,
highlight: withAlpha(foreground, 0.1),
lyricsInactive: withAlpha(foreground, 0.35),
lyricsUnsung: withAlpha(foreground, 0.55),
isDark: palette.isDark,
}
}
+36 -5
View File
@@ -1,13 +1,44 @@
import type { ServerConfig } from "@otunes/convex/server-url"
import { buildConvexUrl, isLocalHost } from "@otunes/convex/server-url"
export {
parseServerHostname,
type ServerConfig,
} from "@otunes/convex/server-url"
export type ServerConfig = {
/** Raw hostname the user entered, e.g. `music.example.com` or `192.168.86.25:3000` */
hostname: string
/** Base URL for the Next.js server, e.g. `https://music.example.com` */
serverUrl: string
/** Convex deployment URL, e.g. `https://convex.music.example.com` */
convexUrl: string
}
const SERVER_CONFIG_KEY = "otunes.server-config"
const LEGACY_SERVER_CONFIG_KEY = "otunes:server-config"
function normalizeHostnameInput(input: string): string {
return input
.trim()
.replace(/^https?:\/\//i, "")
.replace(/\/+$/, "")
}
function buildServerUrl(hostname: string): string {
const protocol = isLocalHost(hostname) ? "http" : "https"
return `${protocol}://${hostname}`
}
export function parseServerHostname(input: string): ServerConfig | null {
const hostname = normalizeHostnameInput(input)
if (!hostname) return null
try {
const serverUrl = buildServerUrl(hostname)
const convexUrl = buildConvexUrl(hostname)
new URL(serverUrl)
new URL(convexUrl)
return { hostname, serverUrl, convexUrl }
} catch {
return null
}
}
export async function loadServerConfig(
getItem: (key: string) => Promise<string | null>
): Promise<ServerConfig | null> {
+1 -1
View File
@@ -4,10 +4,10 @@ export const tabletSections = [
{ name: "albums", group: "(albums)", title: "Albums" },
{ name: "artists", group: "(artists)", title: "Artists" },
{ name: "songs", group: "(songs)", title: "Songs" },
{ name: "downloads", group: "(downloads)", title: "Downloads" },
{ name: "playlists", group: "(playlists)", title: "All Playlists" },
{ name: "favorites", group: "(favorites)", title: "Favorites" },
{ name: "recent", group: "(recent)", title: "Recently Played" },
{ name: "downloads", group: "(downloads)", title: "Downloads" },
] as const
export const TabletSectionContext = createContext<
+3 -5
View File
@@ -44,9 +44,7 @@ final class TabletSidebarView: ExpoView {
let onPlaylistPress = EventDispatcher()
var playlists: [SidebarPlaylist] = []
private let selectionProxy = SidebarSelectionProxy()
/// Playlist rows by identifier. Typed loosely because stored properties
/// can't be gated to iOS 18, where `UITab` arrives; values are always `UITab`.
private var playlistTabs: [String: NSObject] = [:]
private var playlistTabs: [String: UITab] = [:]
private var coverImages: [String: UIImage] = [:]
private var coverTasks: [String: URLSessionDataTask] = [:]
var accountName = ""
@@ -203,7 +201,7 @@ extension TabletSidebarView {
var rows: [UITab] = []
for playlist in playlists {
let identifier = playlistTabPrefix + playlist.id
let tab = playlistTabs[identifier] as? UITab ?? UITab(
let tab = playlistTabs[identifier] ?? UITab(
title: playlist.title, image: nil, identifier: identifier,
viewControllerProvider: { _ in UIViewController() })
playlistTabs[identifier] = tab
@@ -235,7 +233,7 @@ extension TabletSidebarView {
guard let self else { return }
self.coverTasks[url] = nil
self.coverImages[url] = roundedIcon(image)
if let tab = self.playlistTabs[identifier] as? UITab { tab.image = self.coverImages[url] }
if let tab = self.playlistTabs[identifier] { tab.image = self.coverImages[url] }
}
}
coverTasks[url] = task
-1
View File
@@ -37,7 +37,6 @@
"expo-image-picker": "~58.0.10",
"expo-linking": "~58.0.14",
"expo-navigation-bar": "~58.0.4",
"expo-network": "~58.0.5",
"expo-router": "~58.0.25",
"expo-secure-store": "~58.0.2",
"expo-sharing": "~58.0.20",
@@ -23,7 +23,7 @@ export default function Page() {
</p>
<div className="mt-6 flex flex-wrap justify-center gap-2">
<Button asChild>
<Link href="/">
<Link href="/public">
<Home />
Home
</Link>
@@ -1,5 +1,3 @@
// Share links (/album/<id>) land here on the server build, which adds
// link-preview metadata. The app itself links to /album?id=<id>.
import { AlbumPage } from "@/components/album-page"
import { api } from "@otunes/convex/_generated/api"
import { fetchQuery } from "convex/nextjs"
-19
View File
@@ -1,19 +0,0 @@
"use client"
import { useSearchParams } from "next/navigation"
import { AlbumPage } from "@/components/album-page"
import { PageMessage } from "@/components/page-message"
import type { Id } from "@otunes/convex/_generated/dataModel"
export default function Page() {
const searchParams = useSearchParams()
const id = searchParams.get("id")
if (!id) return <PageMessage>Album not found.</PageMessage>
return (
<AlbumPage
albumId={id as Id<"albums">}
highlightedSongId={searchParams.get("s") ?? undefined}
/>
)
}
@@ -1,5 +1,3 @@
// Share links (/artist/<id>) land here on the server build, which adds
// link-preview metadata. The app itself links to /artist?id=<id>.
import { fetchQuery } from "convex/nextjs"
import { convexServerOptions } from "@/lib/convex-server"
import { ArtistPage } from "@/components/artist-page"
-13
View File
@@ -1,13 +0,0 @@
"use client"
import { useSearchParams } from "next/navigation"
import { ArtistPage } from "@/components/artist-page"
import { PageMessage } from "@/components/page-message"
import type { Id } from "@otunes/convex/_generated/dataModel"
export default function Page() {
const id = useSearchParams().get("id")
if (!id) return <PageMessage>Artist not found.</PageMessage>
return <ArtistPage artistId={id as Id<"artists">} />
}
+1 -8
View File
@@ -1,8 +1,6 @@
import { AuthRedirect } from "@/components/auth-redirect"
import { AddToPlaylistProvider } from "@/components/add-to-playlist-provider"
import { DownloadsProvider } from "@/components/downloads-provider"
import { FavoritesProvider } from "@/components/favorites-provider"
import { OfflineGate } from "@/components/offline-gate"
import { PlaybackProvider } from "@/components/playback-provider"
import { PlayerBar } from "@/components/player-bar"
import { LazyQueuePanel } from "@/components/lazy-queue-panel"
@@ -22,16 +20,11 @@ export default function AppLayout({
<AddToPlaylistProvider>
<DownloadsProvider>
<FavoritesProvider>
{process.env.OTUNES_STATIC_EXPORT === "1" && (
<AuthRedirect area="app" />
)}
<AppSidebar />
<div className="flex min-h-svh min-w-0 flex-1">
<SidebarInset className="min-w-0 flex-1">
<Suspense>
<ScrollRestoration>
<OfflineGate>{children}</OfflineGate>
</ScrollRestoration>
<ScrollRestoration>{children}</ScrollRestoration>
</Suspense>
</SidebarInset>
<LazyQueuePanel />
@@ -0,0 +1,40 @@
import { fetchQuery } from "convex/nextjs"
import { convexServerOptions } from "@/lib/convex-server"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { Metadata } from "next"
interface PageProps {
params: Promise<{ id: string }>
}
export async function generateMetadata({
params,
}: PageProps): Promise<Metadata> {
const { id } = await params
const detail = await fetchQuery(
api.library.browseArtistDetail,
{ id: id as Id<"artists"> },
convexServerOptions()
).catch(() => null)
const selectedArtist = detail?.artist
return {
title: `${selectedArtist ? `${selectedArtist.name}` : "oTunes"}`,
openGraph: {
title: `${selectedArtist ? `${selectedArtist.name}` : "oTunes"}`,
description: "oTunes",
images: selectedArtist
? {
url: `/api/artist/${selectedArtist.id}/cover`,
width: 512,
height: 512,
}
: [],
},
}
}
export default function Page() {
return null
}
@@ -1,5 +1,3 @@
// Share links (/playlist/<id>) land here on the server build, which adds
// link-preview metadata. The app itself links to /playlist?id=<id>.
import { PlaylistPage } from "@/components/playlist-page"
import { api } from "@otunes/convex/_generated/api"
import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server"
-13
View File
@@ -1,13 +0,0 @@
"use client"
import { useSearchParams } from "next/navigation"
import { PageMessage } from "@/components/page-message"
import { PlaylistPage } from "@/components/playlist-page"
import type { Id } from "@otunes/convex/_generated/dataModel"
export default function Page() {
const id = useSearchParams().get("id")
if (!id) return <PageMessage>Playlist not found.</PageMessage>
return <PlaylistPage playlistId={id as Id<"playlists">} />
}
-2
View File
@@ -1,4 +1,3 @@
import { AuthRedirect } from "@/components/auth-redirect"
export default function AuthLayout({
children,
}: Readonly<{
@@ -6,7 +5,6 @@ export default function AuthLayout({
}>) {
return (
<div className="flex min-h-svh flex-col items-center justify-center bg-muted/30 p-6">
{process.env.OTUNES_STATIC_EXPORT === "1" && <AuthRedirect area="auth" />}
{children}
</div>
)
+15 -2
View File
@@ -1,5 +1,18 @@
import { fetchQuery } from "convex/nextjs"
import { connection } from "next/server"
import { AuthForm } from "@/components/auth-form"
import { convexServerOptions } from "@/lib/convex-server"
import { api } from "@otunes/convex/_generated/api"
export default function SignInPage() {
return <AuthForm flow="signIn" />
export default async function SignInPage() {
await connection()
const { disableAccountCreation } = await fetchQuery(
api.users.getAppSettings,
{},
convexServerOptions()
)
return (
<AuthForm flow="signIn" accountCreationDisabled={disableAccountCreation} />
)
}
+12 -24
View File
@@ -1,30 +1,18 @@
"use client"
import { useQuery } from "convex/react"
import Link from "next/link"
import { fetchQuery } from "convex/nextjs"
import { connection } from "next/server"
import { AuthForm } from "@/components/auth-form"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { convexServerOptions } from "@/lib/convex-server"
import { api } from "@otunes/convex/_generated/api"
export default function SignUpPage() {
const settings = useQuery(api.users.getAppSettings)
// Render nothing until the setting loads so the form never flashes.
if (settings === undefined) return null
if (!settings.disableAccountCreation) return <AuthForm flow="signUp" />
export default async function SignUpPage() {
await connection()
const { disableAccountCreation } = await fetchQuery(
api.users.getAppSettings,
{},
convexServerOptions()
)
return (
<Card className="w-full max-w-sm">
<CardHeader>
<CardTitle className="text-lg">
This server has disabled new signups :(
</CardTitle>
</CardHeader>
<CardContent>
<Button asChild className="w-full">
<Link href="/signin">Back</Link>
</Button>
</CardContent>
</Card>
<AuthForm flow="signUp" accountCreationDisabled={disableAccountCreation} />
)
}
@@ -37,7 +37,7 @@ export async function POST(request: NextRequest) {
let songs: Awaited<ReturnType<typeof getSongSources>>
try {
songs = await getSongSources(songIds, request)
songs = await getSongSources(songIds)
} catch {
return new Response("Not found", { status: 404 })
}
@@ -7,7 +7,7 @@ import { audioInfo } from "@/lib/server-audio-info"
import { streamFile } from "@/lib/server-audio-stream"
import { spawnFfmpeg } from "@/lib/server-ffmpeg"
import { seekableLosslessFile } from "@/lib/server-lossless"
import { getSongLyrics, getSongSource } from "@/lib/server-song"
import { getSongSource } from "@/lib/server-song"
import { NextRequest, NextResponse, userAgent } from "next/server"
import fs from "node:fs/promises"
import os from "node:os"
@@ -40,27 +40,16 @@ async function fileResponse(songId: string, file: string, contentType: string) {
})
}
/** Longest lyrics passed to ffmpeg; Linux caps one argument at 128 KiB. */
const MAX_LYRICS_ARGUMENT_BYTES = 100 * 1024
/**
* Transcodes to an AAC .m4a with its index up front, so the saved file has a
* duration and seeks offline. Tags carry over, and the stored lyrics are
* written too, since ffmpeg drops some formats' lyrics tags (like MP3 USLT)
* when writing MP4. The temporary file is removed once sent.
* duration and seeks offline. The temporary file is removed once sent.
*/
async function transcodeResponse(
songId: string,
source: string,
kbps: number,
request: NextRequest
signal: AbortSignal
) {
const { signal } = request
const lyrics = await getSongLyrics(songId, request)
const lyricsArgs =
lyrics && Buffer.byteLength(lyrics) <= MAX_LYRICS_ARGUMENT_BYTES
? ["-metadata", `lyrics=${lyrics}`]
: []
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "otunes-download-"))
const output = path.join(dir, "audio.m4a")
const cleanup = () => fs.rm(dir, { recursive: true, force: true })
@@ -75,7 +64,6 @@ async function transcodeResponse(
"aac",
"-b:a",
`${kbps}k`,
...lyricsArgs,
"-movflags",
"+faststart",
output,
@@ -116,7 +104,7 @@ export async function GET(
let song: Awaited<ReturnType<typeof getSongSource>>
try {
song = await getSongSource(id, request)
song = await getSongSource(id)
} catch {
return new Response("Not found", { status: 404 })
}
@@ -129,7 +117,12 @@ export async function GET(
try {
if (plan.kbps > 0) {
return await transcodeResponse(song._id, sourceFile, plan.kbps, request)
return await transcodeResponse(
song._id,
sourceFile,
plan.kbps,
request.signal
)
}
if (plan.source === "lossless") {
@@ -15,7 +15,7 @@ export async function GET(
const { id } = await params
try {
const song = await getSongSource(id, request)
const song = await getSongSource(id)
const quality = request.nextUrl.searchParams.get("quality")
const preferAtmos =
@@ -35,7 +35,7 @@ export async function GET(
const preferAtmos =
request.nextUrl.searchParams.get("preferAtmos") === "true"
// Resolve the source even when a job is cached so every segment is authorized.
const song = await getSongSource(id, request)
const song = await getSongSource(id)
const job =
getExistingHlsJob(id, quality, preferAtmos) ??
(await ensureHlsJob(song, quality, preferAtmos))
@@ -120,7 +120,7 @@ export async function GET(
const { browser } = userAgent(request)
try {
const song = await getSongSource(id, request)
const song = await getSongSource(id)
const {
source: originalCodec,
+9 -18
View File
@@ -37,11 +37,8 @@ async function hostedUrl() {
}
}
const staticExport = process.env.OTUNES_STATIC_EXPORT === "1"
export async function generateMetadata(): Promise<Metadata> {
// Static exports have no request to read the host from.
const url = staticExport ? undefined : await hostedUrl()
const url = await hostedUrl()
return {
title: "oTunes",
@@ -73,13 +70,6 @@ export default function RootLayout({
}: Readonly<{
children: React.ReactNode
}>) {
const content = (
<ThemeProvider defaultTheme="system">
{children}
<Toaster />
</ThemeProvider>
)
return (
<html
lang="en"
@@ -92,13 +82,14 @@ export default function RootLayout({
)}
>
<body className={"overflow-x-hidden"}>
{staticExport ? (
<ConvexClientProvider>{content}</ConvexClientProvider>
) : (
<ConvexAuthNextjsServerProvider storageNamespace="otunes">
<ConvexClientProvider>{content}</ConvexClientProvider>
</ConvexAuthNextjsServerProvider>
)}
<ConvexAuthNextjsServerProvider storageNamespace="otunes">
<ConvexClientProvider convexUrl={process.env.PUBLIC_CONVEX_URL}>
<ThemeProvider>
{children}
<Toaster />
</ThemeProvider>
</ConvexClientProvider>
</ConvexAuthNextjsServerProvider>
</body>
</html>
)
-2
View File
@@ -1,7 +1,5 @@
import type { MetadataRoute } from "next"
export const dynamic = "force-static"
export default function manifest(): MetadataRoute.Manifest {
return {
name: "oTunes",
-9
View File
@@ -1,9 +0,0 @@
import { notFound } from "next/navigation"
import { ServerForm } from "@/components/server-form"
export default function ServerPage() {
// The server build is the server; only desktop apps pick one.
if (process.env.OTUNES_STATIC_EXPORT !== "1") notFound()
return <ServerForm />
}
@@ -1,7 +1,5 @@
"use client"
import { playlistPath } from "@/lib/routes"
import * as React from "react"
import { useConvex, useMutation, useQuery } from "convex/react"
import { useRouter } from "next/navigation"
@@ -258,7 +256,7 @@ export function AddToPlaylistProvider({
setNewPlaylistName("")
setPendingSongIds([])
if (count === 0) {
router.push(playlistPath(playlistId))
router.push(`/playlist/${playlistId}`)
}
} catch (error) {
toast.error(
+3 -5
View File
@@ -1,7 +1,5 @@
"use client"
import { albumPath, artistPath } from "@/lib/routes"
import * as React from "react"
import Image from "next/image"
import Link from "next/link"
@@ -125,7 +123,7 @@ export function AlbumCard({ album }: { album: BrowseAlbum }) {
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
>
<Link className="absolute inset-0" href={albumPath(album.id)}>
<Link className="absolute inset-0" href={"/album/" + album.id}>
<Image
src={albumCoverUrl(album.id)}
alt={album.title}
@@ -188,11 +186,11 @@ export function AlbumCard({ album }: { album: BrowseAlbum }) {
</div>
<div className="min-w-0">
<Link href={albumPath(album.id)} className="hover:underline">
<Link href={"/album/" + album.id} className="hover:underline">
<p className="truncate text-sm font-medium">{album.title}</p>
</Link>
<Link
href={artistPath(album.artist.id)}
href={"/artist/" + album.artist.id}
className="text-muted-foreground decoration-muted-foreground hover:underline"
>
<p className="truncate text-xs">{album.artist.name}</p>
+1 -3
View File
@@ -1,7 +1,5 @@
"use client"
import { artistPath } from "@/lib/routes"
import { PageHeader } from "@/components/library-skeletons"
import * as React from "react"
import Image from "next/image"
@@ -289,7 +287,7 @@ export function AlbumView({
{album.title}
</h1>
<Link
href={artistPath(album.artist.id)}
href={"/artist/" + album.artist.id}
className="inline-block text-lg font-semibold text-primary hover:underline"
>
{album.artist.name}
+20 -104
View File
@@ -1,8 +1,5 @@
"use client"
import { playlistPath } from "@/lib/routes"
import { serverUrl, staticExport } from "@/lib/server"
import {
ArrowDownToLine,
Disc3,
@@ -13,12 +10,11 @@ import {
Mic,
Music2,
Search,
Server,
Settings,
Star,
} from "lucide-react"
import { usePathname, useRouter, useSearchParams } from "next/navigation"
import { usePathname, useRouter } from "next/navigation"
import dynamic from "next/dynamic"
import { useAuthActions } from "@convex-dev/auth/react"
@@ -47,14 +43,11 @@ import Image from "next/image"
import Link from "next/link"
import { useTheme } from "next-themes"
import * as React from "react"
import { Suspense } from "react"
import { api } from "@otunes/convex/_generated/api"
import { playlistCoverUrl } from "@/lib/cover-urls"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { useMounted } from "@/hooks/use-mounted"
import { clearPersistentCache } from "@/lib/persistent-cache"
import { clearOfflinePages, DOWNLOADS_PATH } from "@/lib/downloads"
import { OfflineLink } from "@/components/offline-gate"
import { resetPlaybackStores } from "@otunes/convex/client/playback-store"
const OptionsModal = dynamic(() =>
@@ -70,13 +63,7 @@ const library = [
{ title: "Albums", path: "/library/albums", icon: Disc3 },
{ title: "Artists", path: "/library/artists", icon: Mic },
{ title: "Songs", path: "/library/songs", icon: Music2 },
// Opens offline, so it uses OfflineLink.
{
title: "Downloads",
path: DOWNLOADS_PATH,
icon: ArrowDownToLine,
worksOffline: true,
},
{ title: "Downloads", path: "/library/downloads", icon: ArrowDownToLine },
]
export function AppSidebar() {
@@ -96,7 +83,6 @@ export function AppSidebar() {
await signOut()
resetPlaybackStores()
await clearPersistentCache()
await clearOfflinePages()
router.push("/signin")
}
@@ -114,7 +100,7 @@ export function AppSidebar() {
...(sidebarPlaylists?.subscribed ?? []),
].map((playlist) => ({
title: playlist.title,
path: playlistPath(playlist.id),
path: `/playlist/${playlist.id}`,
icon: playlist.cover ? (
// eslint-disable-next-line @next/next/no-img-element -- versioned cover, already sized by the route
<img
@@ -174,23 +160,10 @@ export function AppSidebar() {
}
asChild
>
{item.worksOffline ? (
<OfflineLink
href={item.path}
onClick={() => setOpenMobile(false)}
>
<item.icon />
<span>{item.title}</span>
</OfflineLink>
) : (
<Link
href={item.path}
onClick={() => setOpenMobile(false)}
>
<item.icon />
<span>{item.title}</span>
</Link>
)}
<Link href={item.path} onClick={() => setOpenMobile(false)}>
<item.icon />
<span>{item.title}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
))}
@@ -201,20 +174,18 @@ export function AppSidebar() {
<SidebarGroup>
<SidebarGroupLabel>Playlists</SidebarGroupLabel>
<SidebarGroupContent>
<Suspense
fallback={
<PlaylistMenu
items={playlistNav}
route={pathname}
onNavigate={() => setOpenMobile(false)}
/>
}
>
<CurrentPlaylistMenu
items={playlistNav}
onNavigate={() => setOpenMobile(false)}
/>
</Suspense>
<SidebarMenu>
{playlistNav.map((item) => (
<SidebarMenuItem key={item.path}>
<SidebarMenuButton isActive={pathname === item.path} asChild>
<Link href={item.path} onClick={() => setOpenMobile(false)}>
{item.icon}
<span>{item.title}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
</SidebarContent>
@@ -227,10 +198,7 @@ export function AppSidebar() {
<SidebarMenuButton size="lg" className="min-w-0 flex-1">
<Avatar size="sm" key={user?.image ?? "fallback"}>
{user?.image ? (
<AvatarImage
src={serverUrl(user.image)}
alt={user.name}
/>
<AvatarImage src={user.image} alt={user.name} />
) : null}
<AvatarFallback>{fallbackLetters}</AvatarFallback>
</Avatar>
@@ -253,15 +221,6 @@ export function AppSidebar() {
Options
<Settings />
</DropdownMenuItem>
{staticExport ? (
<DropdownMenuItem
className="justify-between"
onClick={() => router.push("/server")}
>
Change Server
<Server />
</DropdownMenuItem>
) : null}
</DropdownMenuContent>
</DropdownMenu>
{optionsOpen ? (
@@ -274,46 +233,3 @@ export function AppSidebar() {
</Sidebar>
)
}
type NavItem = { title: string; path: string; icon: React.ReactNode }
// Playlist routes differ only by `?id=`. Reading the query needs a Suspense
// boundary in static exports, so the fallback matches on the path alone.
function CurrentPlaylistMenu(props: {
items: NavItem[]
onNavigate: () => void
}) {
const pathname = usePathname()
const query = useSearchParams().toString()
return (
<PlaylistMenu
{...props}
route={query ? `${pathname}?${query}` : pathname}
/>
)
}
function PlaylistMenu({
items,
route,
onNavigate,
}: {
items: NavItem[]
route: string
onNavigate: () => void
}) {
return (
<SidebarMenu>
{items.map((item) => (
<SidebarMenuItem key={item.path}>
<SidebarMenuButton isActive={route === item.path} asChild>
<Link href={item.path} onClick={onNavigate}>
{item.icon}
<span>{item.title}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
)
}
+2 -4
View File
@@ -1,7 +1,5 @@
"use client"
import { artistPath } from "@/lib/routes"
import Image from "next/image"
import Link from "next/link"
@@ -13,7 +11,7 @@ export function ArtistCard({ artist }: { artist: BrowseArtist }) {
<div className="group flex flex-col items-center gap-2">
<Link
className="relative flex aspect-square w-full items-center justify-center overflow-hidden rounded-full ring-1 ring-foreground/10"
href={artistPath(artist.id)}
href={"/artist/" + artist.id}
>
<Image
src={artistCoverUrl(artist.id)}
@@ -24,7 +22,7 @@ export function ArtistCard({ artist }: { artist: BrowseArtist }) {
/>
</Link>
<div className="min-w-0">
<Link href={artistPath(artist.id)} className="hover:underline">
<Link href={"/artist/" + artist.id} className="hover:underline">
<p className="truncate text-center text-sm font-medium">
{artist.name}
</p>
+11 -8
View File
@@ -1,6 +1,6 @@
"use client"
import { useSearchParams } from "next/navigation"
import { usePathname } from "next/navigation"
import { useCallback } from "react"
import { ArtistsView } from "@/components/artists-view"
@@ -8,17 +8,20 @@ import { ArtistsSkeleton, PageHeader } from "@/components/library-skeletons"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api"
const ARTISTS_PATH = "/library/artists"
function artistIdFromPathname(pathname: string) {
const [, id] = pathname.slice(ARTISTS_PATH.length).split("/")
return id ? decodeURIComponent(id) : undefined
}
export function ArtistsPage() {
const artistId = useSearchParams().get("id") ?? undefined
const pathname = usePathname()
const artists = useCachedQuery(api.library.browseArtists)
const albums = useCachedQuery(api.library.browseAlbums)
const selectArtist = useCallback((artistId: string) => {
window.history.pushState(
null,
"",
`/library/artists?${new URLSearchParams({ id: artistId })}`
)
window.history.pushState(null, "", `${ARTISTS_PATH}/${artistId}`)
}, [])
return (
@@ -31,7 +34,7 @@ export function ArtistsPage() {
<ArtistsView
artists={artists.flat()}
albums={albums.flat()}
artistId={artistId}
artistId={artistIdFromPathname(pathname)}
onSelectArtist={selectArtist}
/>
)}
+1 -3
View File
@@ -1,7 +1,5 @@
"use client"
import { artistPath } from "@/lib/routes"
import * as React from "react"
import Image from "next/image"
import Link from "next/link"
@@ -157,7 +155,7 @@ export function ArtistsView({
<div className="pb-28">
<div className="flex min-w-0 items-center justify-between gap-4 border-b px-6 py-4">
<Link
href={artistPath(selectedArtist.id)}
href={`/artist/${selectedArtist.id}`}
className="group inline-flex min-w-0 flex-1 items-center gap-1 text-xl font-bold tracking-tight hover:underline"
>
<span className="min-w-0 truncate">{selectedArtist.name}</span>
+72 -52
View File
@@ -53,16 +53,27 @@ const copy: Record<
},
}
export function AuthForm({ flow }: { flow: AuthFlow }) {
export function AuthForm({
flow,
accountCreationDisabled,
}: {
flow: AuthFlow
accountCreationDisabled: boolean
}) {
const { signIn } = useAuthActions()
const router = useRouter()
const [error, setError] = useState<string | null>(null)
const [submitting, setSubmitting] = useState(false)
const text = copy[flow]
const signupsDisabled = flow === "signUp" && accountCreationDisabled
const hideSignUpLink = flow === "signIn" && accountCreationDisabled
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault()
if (signupsDisabled) {
return
}
setError(null)
setSubmitting(true)
@@ -89,62 +100,71 @@ export function AuthForm({ flow }: { flow: AuthFlow }) {
<CardDescription>{text.description}</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit}>
<FieldGroup>
{flow === "signUp" && (
{signupsDisabled ? (
<p className="text-sm text-muted-foreground">
New account registration is currently disabled. Contact an
administrator if you need access.
</p>
) : (
<form onSubmit={handleSubmit}>
<FieldGroup>
{flow === "signUp" && (
<Field>
<FieldLabel htmlFor="name">Name</FieldLabel>
<Input
id="name"
name="name"
type="text"
autoComplete="name"
placeholder="Ada Lovelace"
required
/>
</Field>
)}
<Field>
<FieldLabel htmlFor="name">Name</FieldLabel>
<FieldLabel htmlFor="email">Email</FieldLabel>
<Input
id="name"
name="name"
type="text"
autoComplete="name"
placeholder="Ada Lovelace"
id="email"
name="email"
type="email"
autoComplete="email"
placeholder="you@example.com"
required
/>
</Field>
)}
<Field>
<FieldLabel htmlFor="email">Email</FieldLabel>
<Input
id="email"
name="email"
type="email"
autoComplete="email"
placeholder="you@example.com"
required
/>
</Field>
<Field>
<FieldLabel htmlFor="password">Password</FieldLabel>
<Input
id="password"
name="password"
type="password"
autoComplete={
flow === "signIn" ? "current-password" : "new-password"
}
required
/>
</Field>
{error && <FieldError>{error}</FieldError>}
<Field>
<Button type="submit" disabled={submitting}>
{submitting && <Spinner />}
{text.submit}
</Button>
</Field>
<p className="text-center text-sm text-muted-foreground">
{text.switchPrompt}{" "}
<Link
href={text.switchHref}
className="text-primary underline-offset-4 hover:underline"
>
{text.switchLabel}
</Link>
</p>
</FieldGroup>
</form>
<Field>
<FieldLabel htmlFor="password">Password</FieldLabel>
<Input
id="password"
name="password"
type="password"
autoComplete={
flow === "signIn" ? "current-password" : "new-password"
}
required
/>
</Field>
{error && <FieldError>{error}</FieldError>}
<Field>
<Button type="submit" disabled={submitting}>
{submitting && <Spinner />}
{text.submit}
</Button>
</Field>
{!hideSignUpLink ? (
<p className="text-center text-sm text-muted-foreground">
{text.switchPrompt}{" "}
<Link
href={text.switchHref}
className="text-primary underline-offset-4 hover:underline"
>
{text.switchLabel}
</Link>
</p>
) : null}
</FieldGroup>
</form>
)}
</CardContent>
</Card>
)
-27
View File
@@ -1,27 +0,0 @@
"use client"
import { useConvexAuth } from "convex/react"
import { usePathname, useRouter } from "next/navigation"
import { useEffect } from "react"
// Media pages that signed-out visitors can open from share links.
const PUBLIC_PATHS = new Set(["/album", "/artist", "/playlist"])
/**
* Static exports have no proxy, so this keeps signed-out users on the auth
* pages and signed-in users off them. Server builds redirect in proxy.server.ts.
*/
export function AuthRedirect({ area }: { area: "app" | "auth" }) {
const { isAuthenticated, isLoading } = useConvexAuth()
const pathname = usePathname()
const router = useRouter()
useEffect(() => {
if (isLoading) return
if (area === "auth" && isAuthenticated) router.replace("/")
if (area === "app" && !isAuthenticated && !PUBLIC_PATHS.has(pathname))
router.replace("/signin")
}, [area, isAuthenticated, isLoading, pathname, router])
return null
}
+20 -49
View File
@@ -1,19 +1,11 @@
"use client"
import { ConvexAuthNextjsProvider } from "@convex-dev/auth/nextjs"
import { ConvexAuthProvider, useAuthToken } from "@convex-dev/auth/react"
import { buildConvexUrl } from "@otunes/convex/server-url"
import { ConvexReactClient } from "convex/react"
import { usePathname, useRouter } from "next/navigation"
import { ReactNode, useEffect } from "react"
import { ReactNode } from "react"
import { PersistentCacheProvider } from "@/components/persistent-cache-provider"
import {
selectedServer,
setMediaToken,
staticExport,
useSelectedServer,
} from "@/lib/server"
// Server rendering never runs Convex queries, so this URL is never contacted.
const SSR_CONVEX_URL = "http://127.0.0.1:3210"
@@ -25,50 +17,29 @@ function browserConvexUrl() {
return buildConvexUrl(host, protocol === "https:" ? "https" : "http")
}
function getConvexClient(convexUrl: string) {
client ??= new ConvexReactClient(convexUrl)
function getConvexClient(convexUrl: string | undefined) {
if (!client) {
client = new ConvexReactClient(
typeof window === "undefined"
? SSR_CONVEX_URL
: (convexUrl ??
process.env.NEXT_PUBLIC_CONVEX_URL ??
browserConvexUrl())
)
}
return client
}
export function ConvexClientProvider({ children }: { children: ReactNode }) {
if (staticExport) return <ExportProviders>{children}</ExportProviders>
const url =
typeof window === "undefined"
? SSR_CONVEX_URL
: (process.env.NEXT_PUBLIC_CONVEX_URL ?? browserConvexUrl())
export function ConvexClientProvider({
convexUrl,
children,
}: {
convexUrl?: string
children: ReactNode
}) {
return (
<ConvexAuthNextjsProvider client={getConvexClient(url)}>
<PersistentCacheProvider>{children}</PersistentCacheProvider>
<ConvexAuthNextjsProvider client={getConvexClient(convexUrl)}>
<PersistentCacheProvider>{children}</PersistentCacheProvider>{" "}
</ConvexAuthNextjsProvider>
)
}
// Static exports pick a server at /server first. With no Next.js server to
// hold the session in cookies, tokens live in localStorage, keyed by the
// Convex URL, as in the mobile app. Changing servers reloads the page.
function ExportProviders({ children }: { children: ReactNode }) {
const server = useSelectedServer()
const pathname = usePathname()
const router = useRouter()
const onServerPage = pathname === "/server"
useEffect(() => {
if (!onServerPage && !selectedServer()) router.replace("/server")
}, [onServerPage, router])
if (onServerPage) return children
if (!server) return null
return (
<ConvexAuthProvider client={getConvexClient(server.convexUrl)}>
<MediaTokenSync />
<PersistentCacheProvider>{children}</PersistentCacheProvider>
</ConvexAuthProvider>
)
}
function MediaTokenSync() {
const token = useAuthToken()
// Set during render so players created in this commit see the new token.
setMediaToken(token)
return null
}
+1 -28
View File
@@ -18,16 +18,11 @@ import { Label } from "@/components/ui/label"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { useDownloadsVersion } from "@/hooks/use-downloads"
import { authedUrl } from "@/lib/server"
import {
downloadQueue,
readRememberedDownloadQuality,
DOWNLOADS_PATH,
downloadedCollectionPath,
OTHER_DOWNLOADS_PATH,
registerDownloadsServiceWorker,
requestPersistentStorage,
saveDownloadPagesForOffline,
writeRememberedDownloadQuality,
} from "@/lib/downloads"
import { api } from "@otunes/convex/_generated/api"
@@ -79,7 +74,7 @@ export function useDownloads() {
}
async function fetchDownloadOptions(songIds: string[]) {
const response = await fetch(authedUrl(DOWNLOAD_OPTIONS_PATH), {
const response = await fetch(DOWNLOAD_OPTIONS_PATH, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ songIds }),
@@ -283,27 +278,6 @@ function useFailureToasts() {
}, [])
}
/** Keeps Downloads and each downloaded collection's page saved for offline. */
function OfflinePagesSync() {
useDownloadsVersion()
const collectionPaths = downloadQueue
.collections()
.map(downloadedCollectionPath)
const hasOtherSongs = downloadQueue.otherSongIds().length > 0
// A string, so the effect reruns only when the saved set changes.
const pathsKey = collectionPaths.join("\n")
React.useEffect(() => {
if (!pathsKey && !hasOtherSongs) return
saveDownloadPagesForOffline([
DOWNLOADS_PATH,
OTHER_DOWNLOADS_PATH,
...(pathsKey ? pathsKey.split("\n") : []),
])
}, [pathsKey, hasOtherSongs])
return null
}
export function DownloadsProvider({ children }: { children: React.ReactNode }) {
const [pending, setPending] = React.useState<{
target: DownloadTarget
@@ -355,7 +329,6 @@ export function DownloadsProvider({ children }: { children: React.ReactNode }) {
<DownloadsContext.Provider value={value}>
{children}
<DownloadSync />
<OfflinePagesSync />
<DownloadQualityDialog
pending={pending}
onClose={() => setPending(null)}
+18 -10
View File
@@ -2,24 +2,32 @@
import * as React from "react"
import Image from "next/image"
import Link from "next/link"
import { Star } from "lucide-react"
import { FAVORITES_DOWNLOAD_ID } from "@/components/downloads-provider"
import { PageHeader } from "@/components/library-skeletons"
import { OfflineLink } from "@/components/offline-gate"
import { useDownloadsVersion } from "@/hooks/use-downloads"
import {
FROM_DOWNLOADS_PARAM,
useDownloadsVersion,
} from "@/hooks/use-downloads"
import { albumGridClassName } from "@/lib/album-grid-classes"
import { albumCoverUrl, playlistCoverUrl } from "@/lib/cover-urls"
import {
downloadedCollectionPath,
downloadQueue,
OTHER_DOWNLOADS_PATH,
} from "@/lib/downloads"
import { downloadQueue } from "@/lib/downloads"
import type { DownloadedCollection } from "@otunes/convex/client/download-queue"
import { formatBytes } from "@otunes/convex/download-quality"
export const OTHER_DOWNLOADS_PATH = "/library/downloads/other"
export const OTHER_DOWNLOADS_TITLE = "Other Downloaded Songs"
function collectionHref({ kind, id }: DownloadedCollection) {
if (kind === "album") return `/album/${id}?${FROM_DOWNLOADS_PARAM}`
if (id === FAVORITES_DOWNLOAD_ID) {
return `/playlist/favorites?${FROM_DOWNLOADS_PARAM}`
}
return `/playlist/${id}?${FROM_DOWNLOADS_PARAM}`
}
function CollectionCover({ collection }: { collection: DownloadedCollection }) {
if (collection.id === FAVORITES_DOWNLOAD_ID) {
return (
@@ -55,7 +63,7 @@ function DownloadCard({
cover: React.ReactNode
}) {
return (
<OfflineLink href={href} className="group flex flex-col gap-2">
<Link href={href} className="group flex flex-col gap-2">
<div className="relative aspect-square overflow-hidden rounded-lg ring-1 ring-foreground/10">
{cover}
</div>
@@ -67,7 +75,7 @@ function DownloadCard({
{subtitle}
</p>
</div>
</OfflineLink>
</Link>
)
}
@@ -130,7 +138,7 @@ export function DownloadsView() {
{rows.map(({ collection, bytes }) => (
<DownloadCard
key={`${collection.kind}:${collection.id}`}
href={downloadedCollectionPath(collection)}
href={collectionHref(collection)}
title={collection.title}
subtitle={`${collection.kind === "album" ? "Album" : "Playlist"} · ${formatBytes(bytes)}`}
cover={<CollectionCover collection={collection} />}
+1 -7
View File
@@ -8,14 +8,8 @@ const QueuePanel = dynamic(() =>
import("@/components/queue-panel").then((module) => module.QueuePanel)
)
const LyricsPanel = dynamic(() =>
import("@/components/lyrics-panel").then((module) => module.LyricsPanel)
)
/** The queue or lyrics panel beside the page, whichever is open. */
export function LazyQueuePanel() {
const { queueOpen, lyricsOpen } = usePlayback()
const { queueOpen } = usePlayback()
if (lyricsOpen) return <LyricsPanel />
return queueOpen ? <QueuePanel /> : null
}
-242
View File
@@ -1,242 +0,0 @@
"use client"
import * as React from "react"
import {
useIsPlaying,
usePlayback,
usePlaybackProgress,
} from "@/components/playback-provider"
import { useLyrics, useLyricsTime } from "@/hooks/use-lyrics"
import { cn } from "@/lib/utils"
import {
activeLineIndex,
type LyricLine,
type LyricWord,
type Lyrics,
} from "@otunes/convex/client/lyrics"
/** How long a manual scroll keeps the panel from following the song. */
const MANUAL_SCROLL_HOLD_MS = 3000
/** Blur by distance from the playing line; farther lines share the last. */
const LINE_BLUR = ["blur-none", "blur-[1px]", "blur-[2px]", "blur-[3px]"]
/** Unsung words wipe from dim to bright, soft edge first, as they are sung. */
const WORD_FILL = {
backgroundImage:
"linear-gradient(90deg, var(--foreground) 40%, color-mix(in oklab, var(--foreground) 45%, transparent) 60%)",
backgroundSize: "250% 100%",
}
const WORD_FILL_FRAMES = [
{ backgroundPosition: "100% 0" },
{ backgroundPosition: "0% 0" },
]
/** How far a word's fill may drift from playback before it is reset. */
const FILL_DRIFT_MS = 80
/** Lyrics beside the page, in the queue's place. Synced lines follow playback. */
export function LyricsPanel() {
const { currentSong } = usePlayback()
const lyrics = useLyrics(currentSong?.id ?? null)
return (
<aside
aria-label="Lyrics"
className={cn(
"flex h-svh w-72 shrink-0 flex-col border-l bg-background",
"max-md:fixed max-md:inset-y-0 max-md:right-0 max-md:z-20 max-md:shadow-xl"
)}
>
{lyrics === null ? (
<p className="m-auto text-sm text-muted-foreground">No lyrics</p>
) : lyrics ? (
<LyricsLines key={currentSong?.id} lyrics={lyrics} />
) : null}
</aside>
)
}
function LyricsLines({ lyrics }: { lyrics: Lyrics }) {
const { seekTo, currentTime } = usePlaybackProgress()
const isPlaying = useIsPlaying()
const { setIsPlaying } = usePlayback()
const time = useLyricsTime(lyrics, currentTime, isPlaying)
const active = activeLineIndex(lyrics, time)
const scrollRef = React.useRef<HTMLDivElement>(null)
const synced = lyrics.synced !== "none"
// While the listener scrolls, lines stay sharp and the panel stays put.
const [browsing, setBrowsing] = React.useState(false)
const browseTimer = React.useRef<ReturnType<typeof setTimeout>>(undefined)
React.useEffect(() => () => clearTimeout(browseTimer.current), [])
React.useEffect(() => {
const container = scrollRef.current
const line = container?.querySelector<HTMLElement>(
`[data-line="${Math.max(active, 0)}"]`
)
if (!container || !line || !synced || browsing) return
container.scrollTo({
top: line.offsetTop - container.clientHeight * 0.25,
behavior: "smooth",
})
}, [active, synced, browsing])
const playFrom = React.useCallback(
(seconds: number) => {
seekTo(seconds)
setIsPlaying(true)
clearTimeout(browseTimer.current)
setBrowsing(false)
},
[seekTo, setIsPlaying]
)
const holdScroll = () => {
setBrowsing(true)
clearTimeout(browseTimer.current)
browseTimer.current = setTimeout(
() => setBrowsing(false),
MANUAL_SCROLL_HOLD_MS
)
}
return (
<div
ref={scrollRef}
onWheel={holdScroll}
onTouchMove={holdScroll}
className="group relative min-h-0 flex-1 overflow-y-auto px-6 pt-[25svh] pb-[60svh]"
>
{lyrics.lines.map((line, index) =>
synced ? (
<SyncedLine
key={index}
index={index}
line={line}
distance={
browsing
? 0
: Math.min(Math.abs(index - active), LINE_BLUR.length - 1)
}
active={index === active}
time={index === active ? time : null}
isPlaying={isPlaying}
onSelect={playFrom}
/>
) : (
<p
key={index}
className={cn(
"text-lg leading-snug font-semibold text-foreground/85",
line.text === "" && "h-4"
)}
>
{line.text}
</p>
)
)}
</div>
)
}
/**
* One timed line, blurred by its `distance` from the playing line. Only the
* active line gets the playback time, so memoized lines elsewhere skip
* re-rendering as the song plays.
*/
const SyncedLine = React.memo(function SyncedLine({
index,
line,
distance,
active,
time,
isPlaying,
onSelect,
}: {
index: number
line: LyricLine
distance: number
active: boolean
time: number | null
isPlaying: boolean
onSelect: (seconds: number) => void
}) {
return (
<button
type="button"
data-line={index}
onClick={() => onSelect(line.start ?? 0)}
className={cn(
"-mx-2 my-1 block w-[calc(100%+1rem)] rounded-md px-2 py-1.5 text-left text-[22px] leading-tight font-bold transition-[color,filter] duration-300 group-hover:blur-none hover:bg-foreground/5",
LINE_BLUR[distance],
active && !line.words ? "text-foreground" : "text-foreground/30"
)}
>
{active && line.words && time !== null ? (
<FilledWords words={line.words} time={time} isPlaying={isPlaying} />
) : (
line.text
)}
</button>
)
})
/**
* The playing line's words, each filled as far as it has been sung. The
* browser runs the fills; playback updates only correct their drift.
*/
function FilledWords({
words,
time,
isPlaying,
}: {
words: LyricWord[]
time: number
isPlaying: boolean
}) {
const spans = React.useRef<(HTMLSpanElement | null)[]>([])
const fills = React.useRef<(Animation | undefined)[]>([])
React.useEffect(() => {
fills.current = words.map((word, index) =>
spans.current[index]?.animate(WORD_FILL_FRAMES, {
duration: Math.max(word.end - word.start, 0.05) * 1000,
easing: "linear",
fill: "both",
})
)
return () => fills.current.forEach((fill) => fill?.cancel())
}, [words])
React.useEffect(() => {
fills.current.forEach((fill, index) => {
if (!fill) return
const at = (time - words[index].start) * 1000
if (Math.abs(Number(fill.currentTime ?? 0) - at) > FILL_DRIFT_MS) {
fill.currentTime = at
}
// `play` on a finished fill would rewind it.
const duration = Number(fill.effect?.getTiming().duration ?? 0)
if (isPlaying && at < duration) fill.play()
else fill.pause()
})
}, [words, time, isPlaying])
return words.map((word, index) => {
const text = word.text.trimEnd()
return (
<React.Fragment key={index}>
<span
ref={(span) => {
spans.current[index] = span
}}
className="bg-clip-text text-transparent"
style={WORD_FILL}
>
{text}
</span>
{word.text.slice(text.length)}
</React.Fragment>
)
})
}
+15 -10
View File
@@ -1,7 +1,5 @@
"use client"
import { albumPath, artistPath } from "@/lib/routes"
import * as React from "react"
import Link from "next/link"
import {
@@ -76,6 +74,10 @@ export function MediaMenuSeparator() {
)
}
function actionLabel(base: string, selectedCount: number) {
return selectedCount > 1 ? `${base} (${selectedCount})` : base
}
export function MediaContextMenuItems({
selectedCount,
onAction,
@@ -119,7 +121,7 @@ export function MediaContextMenuItems({
className="justify-between"
onClick={() => onAction("playlist")}
>
{playlistLabel}
{actionLabel(playlistLabel, selectedCount)}
<ListPlus />
</MediaMenuItem>
{downloaded !== undefined ? (
@@ -127,7 +129,10 @@ export function MediaContextMenuItems({
className="justify-between"
onClick={() => onAction(downloaded ? "remove-download" : "download")}
>
{downloaded ? "Remove Download" : "Download"}
{actionLabel(
downloaded ? "Remove Download" : "Download",
selectedCount
)}
{downloaded ? <CircleX /> : <ArrowDownToLine />}
</MediaMenuItem>
) : null}
@@ -136,21 +141,21 @@ export function MediaContextMenuItems({
className="justify-between"
onClick={() => onAction("play-next")}
>
Play Next
{actionLabel("Play Next", selectedCount)}
<ListStart />
</MediaMenuItem>
<MediaMenuItem
className="justify-between"
onClick={() => onAction("play-last")}
>
Play Last
{actionLabel("Play Last", selectedCount)}
<ListEnd />
</MediaMenuItem>
<MediaMenuItem
className="justify-between"
onClick={() => onAction("shuffle")}
>
Shuffle
{actionLabel("Shuffle", selectedCount)}
<Shuffle />
</MediaMenuItem>
{stationArtistId ? (
@@ -167,7 +172,7 @@ export function MediaContextMenuItems({
<MediaMenuSeparator />
{artist ? (
<MediaMenuItem asChild className="justify-between">
<Link href={artistPath(artist.id)}>
<Link href={`/artist/${artist.id}`}>
Go to Artist
<MicVocal />
</Link>
@@ -175,7 +180,7 @@ export function MediaContextMenuItems({
) : null}
{album ? (
<MediaMenuItem asChild className="justify-between">
<Link href={albumPath(album.id)}>
<Link href={`/album/${album.id}`}>
Go to Album
<GalleryVerticalEnd />
</Link>
@@ -191,7 +196,7 @@ export function MediaContextMenuItems({
className="justify-between"
onClick={() => onAction("favorite")}
>
{favorited ? "Unfavorite" : "Favorite"}
{actionLabel(favorited ? "Unfavorite" : "Favorite", selectedCount)}
<Star />
</MediaMenuItem>
</>
-101
View File
@@ -1,101 +0,0 @@
"use client"
import { connectivityStore } from "@otunes/convex/client/connectivity"
import { useConvex } from "convex/react"
import { WifiOff } from "lucide-react"
import Link from "next/link"
import { usePathname, useSearchParams } from "next/navigation"
import { useOffline } from "next/offline"
import { useEffect, useRef, useSyncExternalStore } from "react"
import { PageHeader } from "@/components/library-skeletons"
import { DOWNLOADS_PATH } from "@/lib/downloads"
/** How long an offline navigation may wait before loading the page in full. */
const STALLED_NAVIGATION_MS = 1_500
/**
* True while the browser is offline or the server can't be reached. Next's
* `useOffline` covers the network and the web server (it needs
* `experimental.useOffline`); the shared store covers the Convex backend.
*/
export function useIsOffline() {
const nextOffline = useOffline()
const store = connectivityStore(useConvex())
const convexOffline = useSyncExternalStore(
store.subscribe,
store.getSnapshot,
() => false
)
return nextOffline || convexOffline
}
/**
* Replaces page content with a no-connection message while offline. Downloads
* pages, and albums and playlists opened from them, keep rendering so offline
* playback stays reachable. Needs a Suspense boundary for `useSearchParams`.
*/
export function OfflineGate({ children }: { children: React.ReactNode }) {
const offline = useIsOffline()
const pathname = usePathname()
const fromDownloads = useSearchParams().get("from") === "downloads"
const isDownloadsPage =
pathname === DOWNLOADS_PATH || pathname.startsWith(`${DOWNLOADS_PATH}/`)
if (!offline || isDownloadsPage || fromDownloads) return children
return (
<div className="flex h-svh flex-col">
<PageHeader />
<div className="flex flex-1 flex-col items-center justify-center gap-2 p-6 pb-28 text-center">
<WifiOff className="mb-1 size-7 text-muted-foreground" />
<p className="text-sm font-medium">No connection</p>
<p className="text-sm text-muted-foreground">
Your downloads still play.
</p>
<OfflineLink
href={DOWNLOADS_PATH}
className="text-sm underline underline-offset-4"
>
Go to Downloads
</OfflineLink>
</div>
</div>
)
}
/**
* A fully prefetched link for pages that work offline. Offline, a page that
* was never prefetched would wait for the connection, so after a moment it
* loads in full instead and the service worker serves its saved copy.
*/
export function OfflineLink({
href,
onClick,
...props
}: React.ComponentProps<typeof Link> & { href: string }) {
const offline = useIsOffline()
const pathname = usePathname()
const fallback = useRef<ReturnType<typeof setTimeout>>(undefined)
// Any completed navigation, or leaving the page, cancels the fallback.
useEffect(() => () => clearTimeout(fallback.current), [pathname])
return (
<Link
href={href}
prefetch
onClick={(event) => {
onClick?.(event)
if (!offline || event.defaultPrevented) return
if (event.metaKey || event.ctrlKey || event.shiftKey) return
clearTimeout(fallback.current)
fallback.current = setTimeout(
() => window.location.assign(href),
STALLED_NAVIGATION_MS
)
}}
{...props}
/>
)
}
+1 -11
View File
@@ -2,20 +2,10 @@
import { ArrowUpRight } from "lucide-react"
import { serverOrigin } from "@/lib/server"
export function OpenAppButton() {
function openApp() {
const link = new URL("otunes://open")
// The app understands share links (/album/<id>), not in-app /album?id=<id>.
const { pathname, search } = window.location
const page = new URL(`${pathname}${search}`, serverOrigin())
const id = page.searchParams.get("id")
if (id && /^\/(album|artist|playlist)$/.test(page.pathname)) {
page.pathname += `/${encodeURIComponent(id)}`
page.searchParams.delete("id")
}
link.searchParams.set("url", page.href)
link.searchParams.set("url", window.location.href)
window.location.assign(link.href)
}
+1 -5
View File
@@ -1,7 +1,5 @@
"use client"
import { serverUrl } from "@/lib/server"
import { useAction, useMutation, useQuery } from "convex/react"
import { MoreHorizontal, Trash2, Upload, UserPlus } from "lucide-react"
import { useCallback, useEffect, useRef, useState } from "react"
@@ -151,9 +149,7 @@ function UserAvatar({
key={user.image ?? "fallback"}
size={size === "sm" ? "sm" : "default"}
>
{user.image ? (
<AvatarImage src={serverUrl(user.image)} alt={user.name} />
) : null}
{user.image ? <AvatarImage src={user.image} alt={user.name} /> : null}
<AvatarFallback>{initials}</AvatarFallback>
</Avatar>
)
+10 -44
View File
@@ -1,7 +1,5 @@
"use client"
import { authedUrl } from "@/lib/server"
import {
useState,
useEffect,
@@ -62,13 +60,10 @@ type PlaybackContextValue = {
shuffleEnabled: boolean
repeatEnabled: RepeatMode
queueOpen: boolean
/** The lyrics panel, which shares the queue's place beside the page. */
lyricsOpen: boolean
isPlaying: boolean
volume: number
setQueueOpen: (open: boolean) => void
toggleQueueOpen: () => void
toggleLyricsOpen: () => void
setIsPlaying: (playing: boolean) => void
setVolume: (volume: number) => void
/** An origin from `downloadsQueueOrigin` plays downloads in any quality. */
@@ -108,11 +103,8 @@ type PlaybackContextValue = {
toggleShuffle: () => Promise<void>
cycleRepeat: () => Promise<void>
clearQueue: () => Promise<void>
clearHistory: () => Promise<void>
reorderQueue: (songIds: Id<"songs">[]) => Promise<void>
skipToQueueIndex: (index: number) => Promise<void>
/** Plays `history[index]`, moving it and every later song back into the queue. */
skipToHistoryIndex: (index: number) => Promise<void>
skipNext: () => Promise<void>
skipPrevious: () => Promise<void>
dolbyAtmosSupported: boolean | null
@@ -127,7 +119,6 @@ type PlaybackActions = Omit<
| "shuffleEnabled"
| "repeatEnabled"
| "queueOpen"
| "lyricsOpen"
| "isPlaying"
| "volume"
| "dolbyAtmosSupported"
@@ -356,11 +347,15 @@ function loadAudioSource(
}
const { settings } = source
const directUrl = authedUrl(
songPlayPath(songId, settings.playbackQuality, settings.preferAtmos)
const directUrl = songPlayPath(
songId,
settings.playbackQuality,
settings.preferAtmos
)
const hlsUrl = authedUrl(
songHlsPlaylistPath(songId, settings.playbackQuality, settings.preferAtmos)
const hlsUrl = songHlsPlaylistPath(
songId,
settings.playbackQuality,
settings.preferAtmos
)
const loadDirectSource = () => {
@@ -508,12 +503,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
const currentTimeRef = useRef(0)
const durationRef = useRef(0)
const [sidePanel, setSidePanel] = useState<"queue" | "lyrics" | null>(null)
const queueOpen = sidePanel === "queue"
const lyricsOpen = sidePanel === "lyrics"
const setQueueOpen = useCallback((open: boolean) => {
setSidePanel((panel) => (open ? "queue" : panel === "queue" ? null : panel))
}, [])
const [queueOpen, setQueueOpen] = useState(false)
const [isPlaying, setIsPlaying] = useState(false)
const [playbackStartVersion, setPlaybackStartVersion] = useState(0)
const [currentTime, setCurrentTime] = useState(0)
@@ -1448,11 +1438,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
)
const toggleQueueOpen = useCallback(() => {
setSidePanel((panel) => (panel === "queue" ? null : "queue"))
}, [])
const toggleLyricsOpen = useCallback(() => {
setSidePanel((panel) => (panel === "lyrics" ? null : "lyrics"))
setQueueOpen((open) => !open)
}, [])
const toggleShuffle = useCallback(async () => {
@@ -1469,10 +1455,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
setIsPlaying(false)
}, [store])
const clearHistory = useCallback(async () => {
store.update(playbackQueue.clearHistory)
}, [store])
const reorderQueue = useCallback(
async (songIds: Id<"songs">[]) => {
store.update((state) => playbackQueue.reorderQueue(state, songIds))
@@ -1487,13 +1469,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
[store]
)
const skipToHistoryIndex = useCallback(
async (index: number) => {
store.update((state) => playbackQueue.skipToHistoryIndex(state, index))
},
[store]
)
const skipNext = useCallback(async () => {
const before = store.getState()
if (before.repeatEnabled === "none" && before.queue.length <= 1) {
@@ -1558,7 +1533,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
() => ({
setQueueOpen,
toggleQueueOpen,
toggleLyricsOpen,
setIsPlaying,
setVolume,
playInOrder,
@@ -1576,17 +1550,13 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
toggleShuffle,
cycleRepeat,
clearQueue,
clearHistory,
reorderQueue,
skipToQueueIndex,
skipToHistoryIndex,
skipNext,
skipPrevious,
}),
[
setQueueOpen,
toggleQueueOpen,
toggleLyricsOpen,
setVolume,
playInOrder,
playShuffled,
@@ -1603,10 +1573,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
toggleShuffle,
cycleRepeat,
clearQueue,
clearHistory,
reorderQueue,
skipToQueueIndex,
skipToHistoryIndex,
skipNext,
skipPrevious,
]
@@ -1622,7 +1590,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
shuffleEnabled: playback.shuffleEnabled,
repeatEnabled: playback.repeatEnabled,
queueOpen,
lyricsOpen,
isPlaying: isPlaybackActive,
volume,
dolbyAtmosSupported,
@@ -1633,7 +1600,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
currentSong,
currentFormat,
queueOpen,
lyricsOpen,
isPlaybackActive,
volume,
dolbyAtmosSupported,
+3 -4
View File
@@ -1,4 +1,3 @@
import { albumPath, artistPath } from "@/lib/routes"
import Link from "next/link"
import type { BrowseSong } from "@otunes/convex/types"
@@ -25,7 +24,7 @@ export function PlaybackSongMeta({
)}
>
<Link
href={albumPath(song.album.id)}
href={`/album/${song.album.id}`}
className={cn(
"block truncate text-sm font-medium hover:underline",
inRange && "text-primary-foreground hover:text-primary-foreground/80",
@@ -41,7 +40,7 @@ export function PlaybackSongMeta({
)}
>
<Link
href={artistPath(song.artist.id)}
href={`/artist/${song.artist.id}`}
className={cn(
"hover:underline",
inRange
@@ -55,7 +54,7 @@ export function PlaybackSongMeta({
<>
<span aria-hidden="true"> — </span>
<Link
href={albumPath(song.album.id)}
href={`/album/${song.album.id}`}
className="hover:text-foreground hover:underline"
>
{song.album.title}
+6 -17
View File
@@ -1,7 +1,5 @@
"use client"
import { albumPath, artistPath } from "@/lib/routes"
import * as React from "react"
import Image from "next/image"
import Link from "next/link"
@@ -31,7 +29,6 @@ import {
import { Button } from "@/components/ui/button"
import { Slider } from "@/components/ui/slider"
import { useSidebar } from "@/components/ui/sidebar"
import { useLyrics } from "@/hooks/use-lyrics"
import { albumCoverUrl } from "@/lib/cover-urls"
import { cn } from "@/lib/utils"
import { formatDuration } from "@/lib/format-duration"
@@ -76,21 +73,18 @@ export function PlayerBar() {
shuffleEnabled,
repeatEnabled,
queueOpen,
lyricsOpen,
isPlaying,
volume,
queueSongIds,
setIsPlaying,
setVolume,
toggleQueueOpen,
toggleLyricsOpen,
toggleShuffle,
cycleRepeat,
skipNext,
skipPrevious,
} = usePlayback()
const { state, isMobile } = useSidebar()
const lyrics = useLyrics(currentSong?.id ?? null)
const hasQueue = queueSongIds.length > 0
const sidebarExpanded = !isMobile && state === "expanded"
@@ -100,7 +94,7 @@ export function PlayerBar() {
className={cn(
"@container pointer-events-none fixed bottom-4 z-50 flex justify-center px-4 transition-[left,right] duration-200 ease-linear",
sidebarExpanded ? "right-0 left-[16rem]" : "inset-x-0",
(queueOpen || lyricsOpen) && !isMobile && "right-72"
queueOpen && !isMobile && "right-72"
)}
>
<div className="pointer-events-auto flex w-full max-w-[40rem] items-center gap-2 rounded-full border border-foreground/20 bg-(--player-background) px-3 py-2 text-card-foreground shadow-lg [--player-background:var(--card)] md:gap-3 md:py-1.5 dark:border-white/20 dark:text-white dark:[--player-background:#303033]">
@@ -186,21 +180,21 @@ export function PlayerBar() {
</div>
<div className="min-w-0 flex-1">
<Link
href={albumPath(currentSong.album.id)}
href={`/album/${currentSong.album.id}`}
className="block truncate text-sm font-semibold hover:underline md:text-[13px] md:leading-4"
>
{currentSong.title}
</Link>
<p className="truncate text-xs">
<Link
href={artistPath(currentSong.artist.id)}
href={`/artist/${currentSong.artist.id}`}
className="hover:underline"
>
{currentSong.artist.name}
</Link>
<span aria-hidden> · </span>
<Link
href={albumPath(currentSong.album.id)}
href={`/album/${currentSong.album.id}`}
className="hover:underline"
>
{currentSong.album.title}
@@ -233,14 +227,9 @@ export function PlayerBar() {
<Button
variant="ghost"
size="icon"
className="hidden @min-[640px]:inline-flex"
aria-label="Lyrics"
aria-pressed={lyricsOpen}
className={cn(
"hidden @min-[640px]:inline-flex",
lyricsOpen && "text-primary"
)}
disabled={!lyrics && !lyricsOpen}
onClick={toggleLyricsOpen}
disabled
>
<MessageSquareQuote className="size-4" />
</Button>
+2 -4
View File
@@ -1,7 +1,5 @@
"use client"
import { playlistPath } from "@/lib/routes"
import Image from "next/image"
import Link from "next/link"
@@ -81,7 +79,7 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
return (
<div className="flex flex-col gap-2">
<div className="group relative aspect-square overflow-hidden rounded-lg ring-1 ring-foreground/10">
<Link className="absolute inset-0" href={playlistPath(playlist.id)}>
<Link className="absolute inset-0" href={"/playlist/" + playlist.id}>
<Image
src={playlistCoverUrl(playlist.id, playlist.cover, 384)}
alt={playlist.title}
@@ -132,7 +130,7 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
</div>
<div className="min-w-0">
<Link href={playlistPath(playlist.id)} className="hover:underline">
<Link href={"/playlist/" + playlist.id} className="hover:underline">
<p className="truncate text-sm font-medium">{playlist.title}</p>
</Link>
<p className="truncate text-xs text-muted-foreground decoration-muted-foreground">
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff. Show more