Compare commits

..
172 changed files with 3902 additions and 13012 deletions

No files matched your search

+1 -4
View File
@@ -11,7 +11,7 @@ ARG NODE_VERSION=24.13.0-slim
# The Convex backend runs inside the oTunes image. Pin to a commit tag from
# https://github.com/get-convex/convex-backend/pkgs/container/convex-backend
ARG CONVEX_BACKEND_IMAGE=ghcr.io/convex/convex-backend:5c7cb5bc7db457290f1769f95f1d1340912f7fd7
ARG CONVEX_BACKEND_IMAGE=ghcr.io/get-convex/convex-backend:5c7cb5bc7db457290f1769f95f1d1340912f7fd7
# Audio-only static ffmpeg. The distro package links video filters that pull
# in LLVM and Mesa (~420MB) for codecs this app never uses.
@@ -27,8 +27,6 @@ WORKDIR /app
# Only manifests needed for @otunes/web and its workspace dependency (@otunes/convex).
# Mobile is intentionally omitted so its deps are never installed.
COPY package.json pnpm-lock.yaml .npmrc ./
# pnpm validates patches even when their packages are outside the install filter.
COPY patches ./patches
COPY apps/web/package.json ./apps/web/
COPY packages/convex/package.json ./packages/convex/
@@ -83,7 +81,6 @@ FROM node:${NODE_VERSION} AS convex-functions
WORKDIR /app
COPY package.json pnpm-lock.yaml .npmrc ./
COPY patches ./patches
COPY packages/convex/package.json ./packages/convex/
RUN printf '%s\n' \
+3 -3
View File
@@ -1,7 +1,7 @@
/ios/
/android/
ios/
android/
# @generated expo-cli sync-2b81b286409207a5da26e14c78851eb30d8ccbdb
# The following patterns were generated by expo-cli
expo-env.d.ts
# @end expo-cli
# @end expo-cli
-44
View File
@@ -1,44 +0,0 @@
# Mobile build variants
EAS profiles set `APP_VARIANT` to select the app identity in `app.config.ts`.
Both iOS bundle identifiers and Android package names use these values:
| Profile | App name | Identifier |
| --- | --- | --- |
| development | oTunes (Development) | com.abunchofknowitalls.otunes.development |
| preview | oTunes (Preview) | com.abunchofknowitalls.otunes.preview |
| production | oTunes | com.abunchofknowitalls.otunes |
Build with `eas build --profile development`, `--profile preview`, or
`--profile production` from this directory.
For local builds and Metro, select the same variant explicitly:
```sh
APP_VARIANT=development pnpm ios
APP_VARIANT=development pnpm android
APP_VARIANT=development pnpm start
```
An unset `APP_VARIANT` keeps the production identity. Unknown variants fail
configuration. URL schemes are `otunes-development`, `otunes-preview`, and
`otunes` respectively, allowing the apps to be installed together.
### Shared links and artwork
Shared URLs stay as ordinary HTTPS links. The web page's "Open App" action
opens `otunes://open?url=<encoded HTTPS URL>`, including the server address and
album, artist, or playlist destination. No domain association files, signing
settings, or per-server mobile builds are needed.
The app checks the link's server against its configured server before opening
media. Links for another server do not switch the current server. On a fresh
installation, the server address is prefilled in setup. The destination is kept
in memory through setup and sign-in, and is opened after authentication.
The browser may ask before opening the app. If the app is absent, the web page
remains available. Native changes still require a new mobile build.
Native sharing supplies media titles and artwork through iOS link metadata and Android's chooser
thumbnail, while sharing the original HTTPS URL. Receiving apps control whether
they display previews. If artwork cannot load, the URL is still shared. Existing
builds without the native sharing module fall back to URL-only sharing.
@@ -1,42 +0,0 @@
import Foundation
import AppIntents
internal import ExpoAppIntents
internal import ExpoModulesCore
/// Registers the app-owned intent types and their system integrations.
enum MusicAppIntents {
static func register() {
Task {
await AppIntentDispatcher.shared.setShortcutsRefreshHandler {
AppShortcuts.updateAppShortcutParameters()
}
AppShortcuts.updateAppShortcutParameters()
}
}
}
/// Registered Expo inline module that wires app-target App Intents code to expo-app-intents.
/// Do not change the name of this class.
final class AppIntentsSetup: Module {
public func definition() -> ExpoModulesCore.ModuleDefinition {
Name("AppIntentsSetup")
AsyncFunction("replaceCatalog") { (kind: String, json: String) in
try await MusicCatalogStorage.shared.replace(kind: kind, json: json)
}
AsyncFunction("catalogJSON") { (kind: String) in
let records = try await MusicCatalogStorage.shared.records(kind: kind)
return String(decoding: try JSONEncoder().encode(records), as: UTF8.self)
}
AsyncFunction("completeInvocation") { (token: String, error: String?) in
await MusicIntentExecution.shared.complete(token: token, error: error)
}
OnCreate {
MusicAppIntents.register()
MusicEntityRegistration.register()
}
}
}
@@ -1,96 +0,0 @@
import AppIntents
/// Phrases compiled into the app. Each one includes the app name, and each
/// phrase fills at most one parameter. Siri asks for anything a phrase leaves out.
struct AppShortcuts: AppShortcutsProvider {
static var appShortcuts: [AppShortcut] {
AppShortcut(
intent: PlayMusicIntent(),
phrases: [
"Play music in \(.applicationName)",
"Play \(\.$song) in \(.applicationName)",
"Play the album \(\.$album) in \(.applicationName)",
"Play \(\.$artist) in \(.applicationName)",
"Play the playlist \(\.$playlist) in \(.applicationName)",
],
shortTitle: "Play Music",
systemImageName: "play.fill"
)
AppShortcut(
intent: AddToPlaylistIntent(),
phrases: [
"Add to a playlist in \(.applicationName)",
"Add \(\.$song) to a playlist in \(.applicationName)",
],
shortTitle: "Add to Playlist",
systemImageName: "text.badge.plus"
)
AppShortcut(
intent: AddToUpNextIntent(),
phrases: [
"Play \(\.$song) next in \(.applicationName)",
"Add to Up Next in \(.applicationName)",
],
shortTitle: "Add to Up Next",
systemImageName: "text.line.first.and.arrowtriangle.forward"
)
AppShortcut(
intent: ClearUpNextIntent(),
phrases: [
"Clear Up Next in \(.applicationName)",
],
shortTitle: "Clear Up Next",
systemImageName: "clear"
)
AppShortcut(
intent: CreatePlaylistIntent(),
phrases: [
"Create a playlist in \(.applicationName)",
],
shortTitle: "Create Playlist",
systemImageName: "music.note.list"
)
AppShortcut(
intent: GetCurrentSongIntent(),
phrases: [
"What's playing in \(.applicationName)",
],
shortTitle: "Get Current Song",
systemImageName: "music.note"
)
AppShortcut(
intent: LoveSongIntent(),
phrases: [
"Love this song in \(.applicationName)",
"Favorite this song in \(.applicationName)",
"Favorite song in \(.applicationName)",
],
shortTitle: "Love Song",
systemImageName: "heart.fill"
)
AppShortcut(
intent: PauseMusicIntent(),
phrases: [
"Pause \(.applicationName)",
],
shortTitle: "Pause",
systemImageName: "pause.fill"
)
AppShortcut(
intent: ResumeMusicIntent(),
phrases: [
"Resume \(.applicationName)",
],
shortTitle: "Resume",
systemImageName: "play.fill"
)
AppShortcut(
intent: SkipMusicIntent(),
phrases: [
"Skip this song in \(.applicationName)",
],
shortTitle: "Skip",
systemImageName: "forward.fill"
)
}
}
@@ -1,625 +0,0 @@
#if compiler(>=6.4)
import AppIntents
internal import ExpoAppIntents
import Foundation
import MediaIntents
/// Apple's audio schemas are what Siri and Shortcuts use for Music.app actions
/// such as play, add to library, add to playlist, love, and create station.
/// They require the iOS 27 SDK. Older compilers keep the custom intents in
/// `MusicIntents.swift`.
@available(iOS 27.0, *)
@AppEnum(schema: .audio.playbackAttributes)
enum PlaybackAttributes: String {
case shuffle
case `repeat`
static let caseDisplayRepresentations: [PlaybackAttributes: DisplayRepresentation] = [
.shuffle: "Shuffle",
.`repeat`: "Repeat",
]
}
@available(iOS 27.0, *)
@AppEnum(schema: .audio.queueInsertionLocation)
enum QueueInsertionLocation: String {
case next
case tail
static let caseDisplayRepresentations: [QueueInsertionLocation: DisplayRepresentation] = [
.next: "Play Next",
.tail: "Play Last",
]
}
@available(iOS 27.0, *)
@AppEnum(schema: .audio.affinityState)
enum AffinityState: String {
case like
case dislike
case unset
static let caseDisplayRepresentations: [AffinityState: DisplayRepresentation] = [
.like: "Like",
.dislike: "Dislike",
.unset: "Unset",
]
}
@available(iOS 27.0, *)
@UnionValue
enum PlaylistOwner {
case name(String)
}
@available(iOS 27.0, *)
@AppEntity(schema: .audio.artist)
struct AudioArtistEntity {
static let defaultQuery = AudioArtistQuery()
var id: String
var name: String
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(title: "\(name)")
}
init(record: AppIntentEntityRecord) {
id = record.id
name = record.title
}
}
@available(iOS 27.0, *)
struct AudioArtistQuery: EntityStringQuery {
func entities(for identifiers: [AudioArtistEntity.ID]) async throws -> [AudioArtistEntity] {
try await MusicCatalog.records(ofKind: MusicCatalog.artistKind, matching: identifiers)
.map(AudioArtistEntity.init(record:))
}
func suggestedEntities() async throws -> [AudioArtistEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.artistKind)
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
.map(AudioArtistEntity.init(record:))
}
func entities(matching string: String) async throws -> [AudioArtistEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.artistKind)
if string.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
.map(AudioArtistEntity.init(record:))
}
return MusicCatalog.rank(records, query: string, limit: 50, score: MusicCatalog.nameScore)
.map(AudioArtistEntity.init(record:))
}
}
@available(iOS 27.0, *)
extension AudioArtistQuery: IntentValueQuery {
func values(for audioSearch: AudioSearch) async throws -> [AudioArtistEntity] {
switch audioSearch.criteria {
case .searchQuery(let query):
return try await entities(matching: query)
case .unspecified:
return try await suggestedEntities()
case .url(let urls):
return try await artists(for: urls)
@unknown default:
return []
}
}
private func artists(for urls: [URL]) async throws -> [AudioArtistEntity] {
let identifiers = urls.compactMap { url -> String? in
guard case .artist(let id) = MusicCatalog.linkTarget(from: url) else {
return nil
}
return id
}
return try await entities(for: identifiers)
}
}
@available(iOS 27.0, *)
@AppEntity(schema: .audio.album)
struct AudioAlbumEntity {
static let defaultQuery = AudioAlbumQuery()
var id: String
var title: String
var artistName: String
var artists: [AudioArtistEntity]
var universalProductCode: String?
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(title: "\(title)", subtitle: "\(artistName)")
}
init(record: AppIntentEntityRecord, artistsById: [String: AudioArtistEntity]) {
id = record.id
title = record.title
artistName = record.metadata["artistName"] ?? ""
universalProductCode = nil
if let artist = artistsById[record.metadata["artistId"] ?? ""] {
artists = [artist]
} else {
artists = []
}
}
}
@available(iOS 27.0, *)
struct AudioAlbumQuery: EntityStringQuery {
func entities(for identifiers: [AudioAlbumEntity.ID]) async throws -> [AudioAlbumEntity] {
let artistsById = try await Self.artistsById()
return try await MusicCatalog.records(ofKind: MusicCatalog.albumKind, matching: identifiers)
.map { AudioAlbumEntity(record: $0, artistsById: artistsById) }
}
func suggestedEntities() async throws -> [AudioAlbumEntity] {
let artistsById = try await Self.artistsById()
let records = try await MusicCatalog.records(ofKind: MusicCatalog.albumKind)
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
.map { AudioAlbumEntity(record: $0, artistsById: artistsById) }
}
func entities(matching string: String) async throws -> [AudioAlbumEntity] {
let artistsById = try await Self.artistsById()
let records = try await MusicCatalog.records(ofKind: MusicCatalog.albumKind)
let matches = string.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
? MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
: MusicCatalog.rank(records, query: string, limit: 50, score: MusicCatalog.albumScore)
return matches.map { AudioAlbumEntity(record: $0, artistsById: artistsById) }
}
fileprivate static func artistsById() async throws -> [String: AudioArtistEntity] {
let artists = try await MusicCatalog.records(ofKind: MusicCatalog.artistKind)
.map(AudioArtistEntity.init(record:))
return Dictionary(uniqueKeysWithValues: artists.map { ($0.id, $0) })
}
}
@available(iOS 27.0, *)
extension AudioAlbumQuery: IntentValueQuery {
func values(for audioSearch: AudioSearch) async throws -> [AudioAlbumEntity] {
switch audioSearch.criteria {
case .searchQuery(let query):
return try await entities(matching: query)
case .unspecified:
return try await suggestedEntities()
case .url(let urls):
let identifiers = urls.compactMap { url -> String? in
guard case .album(let id) = MusicCatalog.linkTarget(from: url) else {
return nil
}
return id
}
return try await entities(for: identifiers)
@unknown default:
return []
}
}
}
@available(iOS 27.0, *)
@AppEntity(schema: .audio.song)
struct AudioSongEntity {
static let defaultQuery = AudioSongQuery()
var id: String
var title: String
var artistName: String
var composerName: String?
var albumTitle: String?
var artists: [AudioArtistEntity]
var album: AudioAlbumEntity?
var composers: [AudioArtistEntity]
var internationalStandardRecordingCode: String?
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(title: "\(title)", subtitle: "\(artistName)")
}
init(
record: AppIntentEntityRecord,
artistsById: [String: AudioArtistEntity],
albumsById: [String: AudioAlbumEntity]
) {
id = record.id
title = record.title
artistName = record.metadata["artistName"] ?? ""
composerName = nil
albumTitle = record.metadata["albumTitle"]
composers = []
internationalStandardRecordingCode = nil
if let artist = artistsById[record.metadata["artistId"] ?? ""] {
artists = [artist]
} else {
artists = []
}
album = albumsById[record.metadata["albumId"] ?? ""]
}
}
@available(iOS 27.0, *)
struct AudioSongQuery: EntityStringQuery {
func entities(for identifiers: [AudioSongEntity.ID]) async throws -> [AudioSongEntity] {
let context = try await AudioLibraryContext.load()
return try await MusicCatalog.records(ofKind: MusicCatalog.songKind, matching: identifiers)
.map { context.song(from: $0) }
}
func suggestedEntities() async throws -> [AudioSongEntity] {
let context = try await AudioLibraryContext.load()
let records = try await MusicCatalog.records(ofKind: MusicCatalog.songKind)
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true).map {
context.song(from: $0)
}
}
func entities(matching string: String) async throws -> [AudioSongEntity] {
let context = try await AudioLibraryContext.load()
let records = try await MusicCatalog.records(ofKind: MusicCatalog.songKind)
let matches = string.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
? MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
: MusicCatalog.rank(records, query: string, limit: 50, score: MusicCatalog.songScore)
return matches.map { context.song(from: $0) }
}
}
@available(iOS 27.0, *)
extension AudioSongQuery: IntentValueQuery {
func values(for audioSearch: AudioSearch) async throws -> [AudioSongEntity] {
switch audioSearch.criteria {
case .searchQuery(let query):
return try await entities(matching: query)
case .unspecified:
return try await suggestedEntities()
case .url(let urls):
let context = try await AudioLibraryContext.load()
var matches: [AppIntentEntityRecord] = []
for url in urls {
guard let target = MusicCatalog.linkTarget(from: url) else {
continue
}
matches.append(contentsOf: try await MusicCatalog.songs(for: target))
}
return matches.map { context.song(from: $0) }
@unknown default:
return []
}
}
}
@available(iOS 27.0, *)
@AppEntity(schema: .audio.playlist)
struct AudioPlaylistEntity {
static let defaultQuery = AudioPlaylistQuery()
var id: String
var title: String
var owner: PlaylistOwner?
var createdByMe: Bool?
var curatedForMe: Bool?
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(title: "\(title)")
}
init(record: AppIntentEntityRecord) {
id = record.id
title = record.title
let ownerName = record.metadata["ownerName"] ?? ""
owner = ownerName.isEmpty ? nil : .name(ownerName)
createdByMe = record.metadata["createdByMe"] == "1"
curatedForMe = nil
}
}
@available(iOS 27.0, *)
struct AudioPlaylistQuery: EntityStringQuery {
func entities(for identifiers: [AudioPlaylistEntity.ID]) async throws -> [AudioPlaylistEntity] {
try await MusicCatalog.records(ofKind: MusicCatalog.playlistKind, matching: identifiers)
.map(AudioPlaylistEntity.init(record:))
}
func suggestedEntities() async throws -> [AudioPlaylistEntity] {
try await MusicCatalog.records(ofKind: MusicCatalog.playlistKind)
.map(AudioPlaylistEntity.init(record:))
}
func entities(matching string: String) async throws -> [AudioPlaylistEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.playlistKind)
if string.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
return records.map(AudioPlaylistEntity.init(record:))
}
return MusicCatalog.rank(records, query: string, limit: 50, score: MusicCatalog.nameScore)
.map(AudioPlaylistEntity.init(record:))
}
}
@available(iOS 27.0, *)
extension AudioPlaylistQuery: IntentValueQuery {
func values(for audioSearch: AudioSearch) async throws -> [AudioPlaylistEntity] {
switch audioSearch.criteria {
case .searchQuery(let query):
return try await entities(matching: query)
case .unspecified:
return try await suggestedEntities()
case .url(let urls):
let identifiers = urls.compactMap { url -> String? in
guard case .playlist(let id) = MusicCatalog.linkTarget(from: url) else {
return nil
}
return id
}
return try await entities(for: identifiers)
@unknown default:
return []
}
}
}
@available(iOS 27.0, *)
@AppEntity(schema: .audio.warmupAudioQueueResult)
struct WarmupAudioQueueResultEntity {
static let defaultQuery = WarmupAudioQueueResultQuery()
var id: String
var title: String
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(title: "\(title)")
}
}
@available(iOS 27.0, *)
struct WarmupAudioQueueResultQuery: EntityStringQuery {
func entities(for identifiers: [WarmupAudioQueueResultEntity.ID]) async throws -> [WarmupAudioQueueResultEntity] {
identifiers.compactMap { id in
guard let entry = WarmupAudioStore.entry(id: id) else {
return nil
}
return WarmupAudioQueueResultEntity(id: entry.id, title: entry.title)
}
}
func suggestedEntities() async throws -> [WarmupAudioQueueResultEntity] {
WarmupAudioStore.all().map { WarmupAudioQueueResultEntity(id: $0.id, title: $0.title) }
}
func entities(matching string: String) async throws -> [WarmupAudioQueueResultEntity] {
let query = MusicCatalog.normalized(string)
return WarmupAudioStore.all().compactMap { entry in
if query.isEmpty || MusicCatalog.normalized(entry.title).contains(query) {
return WarmupAudioQueueResultEntity(id: entry.id, title: entry.title)
}
return nil
}
}
}
@available(iOS 27.0, *)
enum WarmupAudioStore {
private static let defaultsKey = "otunes.warmupAudioQueue"
struct Entry: Codable {
var id: String
var title: String
}
static func remember(id: String, title: String) {
var entries = all()
entries.removeAll { $0.id == id }
entries.append(Entry(id: id, title: title))
if entries.count > 20 {
entries = Array(entries.suffix(20))
}
if let data = try? JSONEncoder().encode(entries) {
UserDefaults.standard.set(data, forKey: defaultsKey)
}
}
static func entry(id: String) -> Entry? {
all().first { $0.id == id }
}
static func all() -> [Entry] {
guard let data = UserDefaults.standard.data(forKey: defaultsKey),
let entries = try? JSONDecoder().decode([Entry].self, from: data)
else {
return []
}
return entries
}
}
@available(iOS 27.0, *)
@UnionValue
enum AudioItem {
case song(AudioSongEntity)
case album(AudioAlbumEntity)
case artist(AudioArtistEntity)
case playlist(AudioPlaylistEntity)
var kind: String {
switch self {
case .song:
return "song"
case .album:
return "album"
case .artist:
return "artist"
case .playlist:
return "playlist"
}
}
var itemId: String {
switch self {
case .song(let song):
return song.id
case .album(let album):
return album.id
case .artist(let artist):
return artist.id
case .playlist(let playlist):
return playlist.id
}
}
var itemTitle: String {
switch self {
case .song(let song):
return song.title
case .album(let album):
return album.title
case .artist(let artist):
return artist.name
case .playlist(let playlist):
return playlist.title
}
}
}
@available(iOS 27.0, *)
private struct AudioLibraryContext {
var artistsById: [String: AudioArtistEntity]
var albumsById: [String: AudioAlbumEntity]
static func load() async throws -> AudioLibraryContext {
let artistsById = try await AudioAlbumQuery.artistsById()
let albums = try await MusicCatalog.records(ofKind: MusicCatalog.albumKind).map {
AudioAlbumEntity(record: $0, artistsById: artistsById)
}
return AudioLibraryContext(
artistsById: artistsById,
albumsById: Dictionary(uniqueKeysWithValues: albums.map { ($0.id, $0) })
)
}
func song(from record: AppIntentEntityRecord) -> AudioSongEntity {
AudioSongEntity(record: record, artistsById: artistsById, albumsById: albumsById)
}
}
@available(iOS 27.0, *)
@AppIntent(schema: .audio.playAudio)
struct PlayAudioIntent: AudioStartingIntent {
static let openAppWhenRun = true
var audioEntity: AudioItem
var playbackAttributes: Set<PlaybackAttributes>
var warmupAudioQueueResult: WarmupAudioQueueResultEntity?
var queueLocation: QueueInsertionLocation?
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
let queue: String
switch queueLocation {
case .next:
queue = "next"
case .tail:
queue = "tail"
case nil:
queue = "now"
}
try await MusicCommands.play(
kind: audioEntity.kind,
id: audioEntity.itemId,
title: audioEntity.itemTitle,
shuffle: playbackAttributes.contains(.shuffle),
repeatMode: playbackAttributes.contains(.`repeat`) ? "all" : "none",
queue: queue,
warmupId: warmupAudioQueueResult?.id
)
return .result(dialog: "Playing \(audioEntity.itemTitle).")
}
}
@available(iOS 27.0, *)
@AppIntent(schema: .audio.warmupAudioQueue)
struct WarmupAudioQueueIntent {
static let openAppWhenRun = true
var audioEntity: AudioItem
var playbackAttributes: Set<PlaybackAttributes>
@MainActor
func perform() async throws -> some IntentResult & ReturnsValue<WarmupAudioQueueResultEntity> {
let id = try await MusicCommands.warmup(
kind: audioEntity.kind,
id: audioEntity.itemId,
title: audioEntity.itemTitle,
shuffle: playbackAttributes.contains(.shuffle)
)
WarmupAudioStore.remember(id: id, title: audioEntity.itemTitle)
let result = WarmupAudioQueueResultEntity(id: id, title: audioEntity.itemTitle)
return .result(value: result)
}
}
@available(iOS 27.0, *)
@AppIntent(schema: .audio.addToPlaylist)
struct AddAudioToPlaylistIntent {
static let openAppWhenRun = true
var audioEntity: AudioItem
var playlist: AudioPlaylistEntity
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
if audioEntity.kind == "playlist" && audioEntity.itemId == playlist.id {
throw MusicIntentFailure("Choose a different playlist.")
}
try await MusicCommands.addToPlaylist(
playlistId: playlist.id,
sources: [(kind: audioEntity.kind, id: audioEntity.itemId)]
)
return .result(dialog: "Adding to \(playlist.title).")
}
}
@available(iOS 27.0, *)
@AppIntent(schema: .audio.updateAudioAffinity)
struct UpdateAudioAffinityIntent {
static let openAppWhenRun = true
var affinityState: AffinityState
var target: AudioItem
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
if affinityState == .dislike {
throw MusicIntentFailure("oTunes doesn't keep dislikes. You can unlike it instead.")
}
if target.kind == "playlist" {
throw MusicIntentFailure("oTunes can love songs, albums, and artists.")
}
let state = affinityState == .like ? "like" : "unset"
try await MusicCommands.updateAffinity(kind: target.kind, id: target.itemId, state: state)
let verb = affinityState == .like ? "Loving" : "Unliking"
return .result(dialog: "\(verb) \(target.itemTitle).")
}
}
@available(iOS 27.0, *)
@AppIntent(schema: .audio.createStation)
struct CreateAudioStationIntent {
static let openAppWhenRun = true
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
guard let song = try await MusicCatalog.currentSong() else {
throw MusicIntentFailure("Nothing is playing in oTunes.")
}
if song.artistId.isEmpty {
throw MusicIntentFailure("oTunes can't find an artist for this song.")
}
try await MusicCommands.createStation(artistId: song.artistId, artistName: song.artistName)
let artist = song.artistName.isEmpty ? "this artist" : song.artistName
return .result(dialog: "Playing more by \(artist).")
}
}
#endif
@@ -1,332 +0,0 @@
import AppIntents
internal import ExpoAppIntents
import Foundation
struct MusicIntentFailure: Error, CustomLocalizedStringResourceConvertible {
let localizedStringResource: LocalizedStringResource
init(_ message: String) {
localizedStringResource = LocalizedStringResource(stringLiteral: message)
}
}
enum MusicLinkTarget {
case song(String)
case album(String)
case artist(String)
case playlist(String)
}
/// Reads the full disk-backed catalogs JavaScript publishes and turns
/// spoken requests into those records. The same kinds back Shortcuts pickers and,
/// on iOS 27, the audio schemas Siri uses for Apple Music-style requests.
enum MusicCatalog {
static let songKind = "song"
static let albumKind = "album"
static let artistKind = "artist"
static let playlistKind = "playlist"
static let nowPlayingKind = "nowPlaying"
/// Kept in sync with the catalog query and the JavaScript bridge.
static let favoritesPlaylistId = "otunes:favorites"
static func records(ofKind kind: String) async throws -> [AppIntentEntityRecord] {
try await MusicCatalogStorage.shared.records(kind: kind)
}
static func records(ofKind kind: String, matching identifiers: [String]) async throws -> [AppIntentEntityRecord] {
try await records(ofKind: kind).filter { identifiers.contains($0.id) }
}
static func currentSong() async throws -> SongEntity? {
guard let current = try await records(ofKind: nowPlayingKind).first else {
return nil
}
if let song = try await SongQuery().entities(for: [current.id]).first {
return song
}
return SongEntity(record: current)
}
static func normalized(_ value: String) -> String {
value
.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: .current)
.trimmingCharacters(in: .whitespacesAndNewlines)
}
static func cleanedQuery(_ query: String) -> String {
var text = normalized(query)
let prefixes = [
"the song ", "the album ", "the artist ", "the playlist ",
"songs by ", "music by ", "song ", "album ", "artist ", "playlist ", "some ",
]
var didStrip = true
while didStrip {
didStrip = false
for prefix in prefixes where text.hasPrefix(prefix) {
text = String(text.dropFirst(prefix.count))
.trimmingCharacters(in: .whitespacesAndNewlines)
didStrip = true
}
}
return text
}
static func rank(
_ records: [AppIntentEntityRecord],
query: String,
limit: Int,
score: (AppIntentEntityRecord, String) -> Int
) -> [AppIntentEntityRecord] {
let cleaned = cleanedQuery(query)
guard !cleaned.isEmpty else {
return []
}
return records
.compactMap { record -> (AppIntentEntityRecord, Int)? in
let value = score(record, cleaned)
return value > 0 ? (record, value) : nil
}
.sorted { lhs, rhs in
if lhs.1 != rhs.1 {
return lhs.1 > rhs.1
}
return lhs.0.title.localizedCaseInsensitiveCompare(rhs.0.title) == .orderedAscending
}
.prefix(limit)
.map(\.0)
}
static func songScore(_ record: AppIntentEntityRecord, _ query: String) -> Int {
let title = normalized(record.title)
let artist = normalized(record.metadata["artistName"] ?? "")
if title == query {
return 100
}
if let range = query.range(of: " by ") {
let titlePart = normalized(String(query[..<range.lowerBound]))
let artistPart = normalized(String(query[range.upperBound...]))
var score = 0
if !titlePart.isEmpty && (title == titlePart || title.contains(titlePart)) {
score += title == titlePart ? 70 : 50
}
if !artistPart.isEmpty && (artist == artistPart || artist.contains(artistPart)) {
score += artist == artistPart ? 30 : 20
}
return score >= 50 ? score : 0
}
if title.contains(query) || (query.contains(title) && title.count > 2) {
return title.contains(query) ? 80 : 60
}
return 0
}
static func albumScore(_ record: AppIntentEntityRecord, _ query: String) -> Int {
let title = normalized(record.title)
let artist = normalized(record.metadata["artistName"] ?? "")
if title == query {
return 100
}
if title.contains(query) || (query.contains(title) && title.count > 2) {
return 80
}
if artist == query {
return 45
}
if artist.contains(query) && query.count > 2 {
return 30
}
return 0
}
static func nameScore(_ record: AppIntentEntityRecord, _ query: String) -> Int {
let name = normalized(record.title)
let synonyms = record.synonyms.map(normalized)
if name == query || synonyms.contains(query) {
return 100
}
if name.contains(query) || synonyms.contains(where: { $0.contains(query) }) {
return 80
}
if query.contains(name) && name.count > 2 {
return 60
}
return 0
}
static func suggested(
_ records: [AppIntentEntityRecord],
limit: Int,
favoritesFirst: Bool
) -> [AppIntentEntityRecord] {
let pool: [AppIntentEntityRecord]
if favoritesFirst {
let favorites = records.filter { $0.metadata["favorite"] == "1" }
pool = favorites.isEmpty ? records : favorites
} else {
pool = records
}
return Array(pool.prefix(limit))
}
static func linkTarget(from url: URL) -> MusicLinkTarget? {
let parts = url.path.split(separator: "/").map(String.init).filter { !$0.isEmpty }
guard let kind = parts.first, parts.count >= 2 else {
return nil
}
let id = parts[1]
switch kind {
case "album":
if let songId = URLComponents(url: url, resolvingAgainstBaseURL: false)?
.queryItems?
.first(where: { $0.name == "s" })?
.value,
!songId.isEmpty
{
return .song(songId)
}
return .album(id)
case "artist":
return .artist(id)
case "playlist":
return .playlist(id == "favorites" ? favoritesPlaylistId : id)
default:
return nil
}
}
static func songs(for target: MusicLinkTarget) async throws -> [AppIntentEntityRecord] {
let songs = try await records(ofKind: songKind)
switch target {
case .song(let id):
return songs.filter { $0.id == id }
case .album(let id):
return Array(songs.filter { $0.metadata["albumId"] == id }.prefix(25))
case .artist(let id):
return Array(songs.filter { $0.metadata["artistId"] == id }.prefix(25))
case .playlist:
return []
}
}
static func formatDuration(_ seconds: Int) -> String {
guard seconds > 0 else {
return ""
}
return String(format: "%d:%02d", seconds / 60, seconds % 60)
}
}
enum MusicCommands {
static func play(
kind: String,
id: String,
title: String,
shuffle: Bool?,
repeatMode: String?,
queue: String,
warmupId: String?
) async throws -> String {
let params: AppIntentParams = [
"kind": .string(kind),
"id": .string(id),
"title": .string(title),
"queue": .string(queue),
"shuffle": shuffle.map { .string($0 ? "songs" : "off") } ?? .null,
"repeat": repeatMode.map(AppIntentValue.string) ?? .null,
"warmupId": warmupId.map(AppIntentValue.string) ?? .null,
]
return try await MusicIntentExecution.shared.run(name: "playMusic", params: params)
}
static func warmup(kind: String, id: String, title: String, shuffle: Bool) async throws -> String {
try await MusicIntentExecution.shared.run(
name: "warmupAudio",
params: [
"kind": .string(kind),
"id": .string(id),
"title": .string(title),
"shuffle": .string(shuffle ? "songs" : "off"),
]
)
}
static func addToPlaylist(playlistId: String, sources: [(kind: String, id: String)]) async throws {
try await MusicIntentExecution.shared.run(
name: "addToPlaylist",
params: [
"playlistId": .string(playlistId),
"sources": .array(sources.map { source in
.object([
"kind": .string(source.kind),
"id": .string(source.id),
])
}),
]
)
}
static func addToUpNext(
position: String,
sources: [(kind: String, id: String)]
) async throws {
try await MusicIntentExecution.shared.run(
name: "addToUpNext",
params: [
"position": .string(position),
"sources": .array(sources.map { source in
.object([
"kind": .string(source.kind),
"id": .string(source.id),
])
}),
]
)
}
static func createPlaylist(name: String, sources: [(kind: String, id: String)]) async throws {
try await MusicIntentExecution.shared.run(
name: "createPlaylist",
params: [
"name": .string(name),
"sources": .array(sources.map { source in
.object([
"kind": .string(source.kind),
"id": .string(source.id),
])
}),
]
)
}
static func clearUpNext() async throws {
try await MusicIntentExecution.shared.run(name: "clearUpNext")
}
static func createStation(artistId: String, artistName: String) async throws {
try await MusicIntentExecution.shared.run(
name: "createStation",
params: [
"artistId": .string(artistId),
"title": .string(artistName),
]
)
}
static func updateAffinity(kind: String, id: String, state: String) async throws {
try await MusicIntentExecution.shared.run(
name: "updateAffinity",
params: [
"kind": .string(kind),
"id": .string(id),
"state": .string(state),
]
)
}
static func transport(_ command: String) async throws {
try await MusicIntentExecution.shared.run(
name: "transport",
params: ["command": .string(command)]
)
}
}
@@ -1,245 +0,0 @@
import AppIntents
@preconcurrency import CoreSpotlight
internal import ExpoAppIntents
internal import ExpoModulesCore
import UniformTypeIdentifiers
enum MusicEntityRegistration {
static func register() {
AppIntentDonationRegistry.shared.register("playMusic", as: PlayMusicIntent.self)
if #available(iOS 18.0, *) {
AppEntityIdentifierRegistry.shared.registerIndexed("song", as: SongEntity.self)
} else {
AppEntityIdentifierRegistry.shared.register("song", as: SongEntity.self)
}
if #available(iOS 18.0, *) {
AppEntityIdentifierRegistry.shared.registerIndexed("album", as: AlbumEntity.self)
} else {
AppEntityIdentifierRegistry.shared.register("album", as: AlbumEntity.self)
}
if #available(iOS 18.0, *) {
AppEntityIdentifierRegistry.shared.registerIndexed("artist", as: ArtistEntity.self)
} else {
AppEntityIdentifierRegistry.shared.register("artist", as: ArtistEntity.self)
}
if #available(iOS 18.0, *) {
AppEntityIdentifierRegistry.shared.registerIndexed("playlist", as: PlaylistEntity.self)
} else {
AppEntityIdentifierRegistry.shared.register("playlist", as: PlaylistEntity.self)
}
}
}
extension SongEntity: AppIntentEntityRecordConvertible {}
@available(iOS 18.0, *)
extension SongEntity: IndexedEntity {
var attributeSet: CSSearchableItemAttributeSet {
let attributes = CSSearchableItemAttributeSet(contentType: .text)
attributes.title = title
attributes.displayName = title
attributes.contentDescription = "\(artistName) · \(albumTitle)"
attributes.keywords = [title, artistName, albumTitle, "music", "song"]
return attributes
}
}
struct OpenSongIntent: OpenIntent {
static let title: LocalizedStringResource = "Open Song"
static let openAppWhenRun = true
@Parameter(title: "Song")
var target: SongEntity
@MainActor
func perform() async throws -> some IntentResult {
_ = try await MusicIntentExecution.shared.run(
name: "openMusic", params: ["kind": .string("song"), "id": .string(target.id)]
)
return .result()
}
}
extension AlbumEntity: AppIntentEntityRecordConvertible {}
@available(iOS 18.0, *)
extension AlbumEntity: IndexedEntity {
var attributeSet: CSSearchableItemAttributeSet {
let attributes = CSSearchableItemAttributeSet(contentType: .text)
attributes.title = title
attributes.displayName = title
attributes.contentDescription = artistName
attributes.keywords = [title, artistName, "music", "album"]
return attributes
}
}
struct OpenAlbumIntent: OpenIntent {
static let title: LocalizedStringResource = "Open Album"
static let openAppWhenRun = true
@Parameter(title: "Album")
var target: AlbumEntity
@MainActor
func perform() async throws -> some IntentResult {
_ = try await MusicIntentExecution.shared.run(
name: "openMusic", params: ["kind": .string("album"), "id": .string(target.id)]
)
return .result()
}
}
extension ArtistEntity: AppIntentEntityRecordConvertible {}
@available(iOS 18.0, *)
extension ArtistEntity: IndexedEntity {
var attributeSet: CSSearchableItemAttributeSet {
let attributes = CSSearchableItemAttributeSet(contentType: .text)
attributes.title = name
attributes.displayName = name
attributes.contentDescription = "oTunes artist"
attributes.keywords = [name, "music", "artist"]
return attributes
}
}
struct OpenArtistIntent: OpenIntent {
static let title: LocalizedStringResource = "Open Artist"
static let openAppWhenRun = true
@Parameter(title: "Artist")
var target: ArtistEntity
@MainActor
func perform() async throws -> some IntentResult {
_ = try await MusicIntentExecution.shared.run(
name: "openMusic", params: ["kind": .string("artist"), "id": .string(target.id)]
)
return .result()
}
}
extension PlaylistEntity: AppIntentEntityRecordConvertible {}
@available(iOS 18.0, *)
extension PlaylistEntity: IndexedEntity {
var attributeSet: CSSearchableItemAttributeSet {
let attributes = CSSearchableItemAttributeSet(contentType: .text)
attributes.title = title
attributes.displayName = title
attributes.contentDescription = "oTunes playlist"
attributes.keywords = [title, "music", "playlist"]
return attributes
}
}
struct OpenPlaylistIntent: OpenIntent {
static let title: LocalizedStringResource = "Open Playlist"
static let openAppWhenRun = true
@Parameter(title: "Playlist")
var target: PlaylistEntity
@MainActor
func perform() async throws -> some IntentResult {
_ = try await MusicIntentExecution.shared.run(
name: "openMusic", params: ["kind": .string("playlist"), "id": .string(target.id)]
)
return .result()
}
}
extension PlayMusicIntent: DonatableAppIntent {
struct DonationParams: Record {
@Field(.required) var kind: String = ""
@Field(.required) var id: String = ""
@Field var shuffle: Bool = false
}
init(donationParams: DonationParams) async throws {
self.init()
shuffle = donationParams.shuffle ? .songs : .off
switch donationParams.kind {
case "song":
guard let value = try await SongQuery().entities(for: [donationParams.id]).first else {
throw MusicIntentFailure("This song is no longer available.")
}
song = value
case "album":
guard let value = try await AlbumQuery().entities(for: [donationParams.id]).first else {
throw MusicIntentFailure("This album is no longer available.")
}
album = value
case "artist":
guard let value = try await ArtistQuery().entities(for: [donationParams.id]).first else {
throw MusicIntentFailure("This artist is no longer available.")
}
artist = value
case "playlist":
guard let value = try await PlaylistQuery().entities(for: [donationParams.id]).first else {
throw MusicIntentFailure("This playlist is no longer available.")
}
playlist = value
default:
throw MusicIntentFailure("Unknown music type.")
}
}
}
// The system can recover an evicted Spotlight index without waiting for the next
// catalog refresh. Rebuild only the compact catalog published to expo-app-intents.
#if compiler(>=6.4)
@available(iOS 27.0, *)
extension SongQuery: IndexedEntityQuery {
func reindexEntities(
for identifiers: [SongEntity.ID], indexDescription: CSSearchableIndexDescription
) async throws {
try await AppEntityIdentifierRegistry.shared.updateIndexFromCatalog(kind: "song", matching: identifiers)
}
func reindexAllEntities(indexDescription: CSSearchableIndexDescription) async throws {
try await AppEntityIdentifierRegistry.shared.replaceIndexFromCatalog(kind: "song")
}
}
@available(iOS 27.0, *)
extension AlbumQuery: IndexedEntityQuery {
func reindexEntities(
for identifiers: [AlbumEntity.ID], indexDescription: CSSearchableIndexDescription
) async throws {
try await AppEntityIdentifierRegistry.shared.updateIndexFromCatalog(kind: "album", matching: identifiers)
}
func reindexAllEntities(indexDescription: CSSearchableIndexDescription) async throws {
try await AppEntityIdentifierRegistry.shared.replaceIndexFromCatalog(kind: "album")
}
}
@available(iOS 27.0, *)
extension ArtistQuery: IndexedEntityQuery {
func reindexEntities(
for identifiers: [ArtistEntity.ID], indexDescription: CSSearchableIndexDescription
) async throws {
try await AppEntityIdentifierRegistry.shared.updateIndexFromCatalog(kind: "artist", matching: identifiers)
}
func reindexAllEntities(indexDescription: CSSearchableIndexDescription) async throws {
try await AppEntityIdentifierRegistry.shared.replaceIndexFromCatalog(kind: "artist")
}
}
@available(iOS 27.0, *)
extension PlaylistQuery: IndexedEntityQuery {
func reindexEntities(
for identifiers: [PlaylistEntity.ID], indexDescription: CSSearchableIndexDescription
) async throws {
try await AppEntityIdentifierRegistry.shared.updateIndexFromCatalog(kind: "playlist", matching: identifiers)
}
func reindexAllEntities(indexDescription: CSSearchableIndexDescription) async throws {
try await AppEntityIdentifierRegistry.shared.replaceIndexFromCatalog(kind: "playlist")
}
}
#endif
@@ -1,301 +0,0 @@
import AppIntents
internal import ExpoAppIntents
import Foundation
struct SongEntity: AppEntity {
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Song")
static let defaultQuery = SongQuery()
var id: String
var title: String
var artistName: String
var artistId: String
var albumTitle: String
var albumId: String
var durationSeconds: Int
var genres: String
var year: String
var trackNumber: String
var discNumber: String
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(title: "\(title)", subtitle: "\(artistName)")
}
init(record: AppIntentEntityRecord) {
id = record.id
title = record.title
artistName = record.metadata["artistName"] ?? record.subtitle ?? ""
artistId = record.metadata["artistId"] ?? ""
albumTitle = record.metadata["albumTitle"] ?? ""
albumId = record.metadata["albumId"] ?? ""
durationSeconds = Int(record.metadata["duration"] ?? "") ?? 0
genres = record.metadata["genres"] ?? ""
year = record.metadata["year"] ?? ""
trackNumber = record.metadata["track"] ?? ""
discNumber = record.metadata["disk"] ?? ""
}
}
struct SongQuery: EntityStringQuery {
func entities(for identifiers: [String]) async throws -> [SongEntity] {
try await MusicCatalog.records(ofKind: MusicCatalog.songKind, matching: identifiers)
.map(SongEntity.init(record:))
}
func suggestedEntities() async throws -> [SongEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.songKind)
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
.map(SongEntity.init(record:))
}
func entities(matching string: String) async throws -> [SongEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.songKind)
let query = string.trimmingCharacters(in: .whitespacesAndNewlines)
if query.isEmpty {
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
.map(SongEntity.init(record:))
}
return MusicCatalog.rank(records, query: query, limit: 50, score: MusicCatalog.songScore)
.map(SongEntity.init(record:))
}
}
struct AlbumEntity: AppEntity {
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Album")
static let defaultQuery = AlbumQuery()
var id: String
var title: String
var artistName: String
var artistId: String
var year: String
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(title: "\(title)", subtitle: "\(artistName)")
}
init(record: AppIntentEntityRecord) {
id = record.id
title = record.title
artistName = record.metadata["artistName"] ?? record.subtitle ?? ""
artistId = record.metadata["artistId"] ?? ""
year = record.metadata["year"] ?? ""
}
}
struct AlbumQuery: EntityStringQuery {
func entities(for identifiers: [String]) async throws -> [AlbumEntity] {
try await MusicCatalog.records(ofKind: MusicCatalog.albumKind, matching: identifiers)
.map(AlbumEntity.init(record:))
}
func suggestedEntities() async throws -> [AlbumEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.albumKind)
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
.map(AlbumEntity.init(record:))
}
func entities(matching string: String) async throws -> [AlbumEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.albumKind)
let query = string.trimmingCharacters(in: .whitespacesAndNewlines)
if query.isEmpty {
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
.map(AlbumEntity.init(record:))
}
return MusicCatalog.rank(records, query: query, limit: 50, score: MusicCatalog.albumScore)
.map(AlbumEntity.init(record:))
}
}
struct ArtistEntity: AppEntity {
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Artist")
static let defaultQuery = ArtistQuery()
var id: String
var name: String
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(title: "\(name)")
}
init(record: AppIntentEntityRecord) {
id = record.id
name = record.title
}
}
struct ArtistQuery: EntityStringQuery {
func entities(for identifiers: [String]) async throws -> [ArtistEntity] {
try await MusicCatalog.records(ofKind: MusicCatalog.artistKind, matching: identifiers)
.map(ArtistEntity.init(record:))
}
func suggestedEntities() async throws -> [ArtistEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.artistKind)
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
.map(ArtistEntity.init(record:))
}
func entities(matching string: String) async throws -> [ArtistEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.artistKind)
let query = string.trimmingCharacters(in: .whitespacesAndNewlines)
if query.isEmpty {
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
.map(ArtistEntity.init(record:))
}
return MusicCatalog.rank(records, query: query, limit: 50, score: MusicCatalog.nameScore)
.map(ArtistEntity.init(record:))
}
}
struct PlaylistEntity: AppEntity {
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Playlist")
static let defaultQuery = PlaylistQuery()
var id: String
var title: String
var ownerName: String
var createdByMe: Bool
var displayRepresentation: DisplayRepresentation {
if ownerName.isEmpty {
return DisplayRepresentation(title: "\(title)")
}
return DisplayRepresentation(title: "\(title)", subtitle: "\(ownerName)")
}
init(record: AppIntentEntityRecord) {
id = record.id
title = record.title
ownerName = record.metadata["ownerName"] ?? record.subtitle ?? ""
createdByMe = record.metadata["createdByMe"] == "1"
}
}
struct PlaylistQuery: EntityStringQuery {
func entities(for identifiers: [String]) async throws -> [PlaylistEntity] {
try await MusicCatalog.records(ofKind: MusicCatalog.playlistKind, matching: identifiers)
.map(PlaylistEntity.init(record:))
}
func suggestedEntities() async throws -> [PlaylistEntity] {
try await MusicCatalog.records(ofKind: MusicCatalog.playlistKind)
.map(PlaylistEntity.init(record:))
}
func entities(matching string: String) async throws -> [PlaylistEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.playlistKind)
let query = string.trimmingCharacters(in: .whitespacesAndNewlines)
if query.isEmpty {
return records.map(PlaylistEntity.init(record:))
}
return MusicCatalog.rank(records, query: query, limit: 50, score: MusicCatalog.nameScore)
.map(PlaylistEntity.init(record:))
}
}
enum MusicShuffle: String, AppEnum {
case off
case songs
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Shuffle")
static let caseDisplayRepresentations: [MusicShuffle: DisplayRepresentation] = [
.off: "Off",
.songs: "Songs",
]
}
enum MusicRepeat: String, AppEnum {
case none
case one
case all
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Repeat")
static let caseDisplayRepresentations: [MusicRepeat: DisplayRepresentation] = [
.none: "None",
.one: "One",
.all: "All",
]
}
enum UpNextPosition: String, AppEnum {
case next
case last
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Position")
static let caseDisplayRepresentations: [UpNextPosition: DisplayRepresentation] = [
.next: "Play Next",
.last: "Play Last",
]
}
enum MusicDetail: String, AppEnum {
case title
case artist
case album
case albumArtist
case genre
case duration
case year
case trackNumber
case discNumber
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Detail")
static let caseDisplayRepresentations: [MusicDetail: DisplayRepresentation] = [
.title: "Title",
.artist: "Artist",
.album: "Album",
.albumArtist: "Album Artist",
.genre: "Genre",
.duration: "Duration",
.year: "Year",
.trackNumber: "Track Number",
.discNumber: "Disc Number",
]
}
enum MusicSelection {
static func sources(
song: SongEntity?,
album: AlbumEntity?,
artist: ArtistEntity?,
playlist: PlaylistEntity?
) throws -> [(kind: String, id: String, title: String)] {
var sources: [(kind: String, id: String, title: String)] = []
if let song {
sources.append(("song", song.id, song.title))
}
if let album {
sources.append(("album", album.id, album.title))
}
if let artist {
sources.append(("artist", artist.id, artist.name))
}
if let playlist {
sources.append(("playlist", playlist.id, playlist.title))
}
if sources.isEmpty {
throw MusicIntentFailure("Choose a song, album, artist, or playlist.")
}
return sources
}
static func singleTarget(
song: SongEntity?,
album: AlbumEntity?,
artist: ArtistEntity?,
playlist: PlaylistEntity?
) throws -> (kind: String, id: String, title: String)? {
let sources = [
song.map { (kind: "song", id: $0.id, title: $0.title) },
album.map { (kind: "album", id: $0.id, title: $0.title) },
artist.map { (kind: "artist", id: $0.id, title: $0.name) },
playlist.map { (kind: "playlist", id: $0.id, title: $0.title) },
].compactMap { $0 }
if sources.count > 1 {
throw MusicIntentFailure("Choose one song, album, artist, or playlist.")
}
return sources.first
}
}
@@ -1,425 +0,0 @@
import AppIntents
import Foundation
// Actions that use the React player or authenticated mutations open the app and
// wait for its acknowledgment. Native catalog reads can run without opening it.
struct PlayMusicIntent: AppIntent {
static let title: LocalizedStringResource = "Play Music"
static let description = IntentDescription("Plays music using oTunes.")
static let openAppWhenRun = true
@Parameter(title: "Song")
var song: SongEntity?
@Parameter(title: "Album")
var album: AlbumEntity?
@Parameter(title: "Artist")
var artist: ArtistEntity?
@Parameter(title: "Playlist")
var playlist: PlaylistEntity?
@Parameter(title: "Shuffle")
var shuffle: MusicShuffle?
@Parameter(title: "Repeat")
var repeatMode: MusicRepeat?
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
let target = try MusicSelection.singleTarget(
song: song,
album: album,
artist: artist,
playlist: playlist
)
let kind = target?.0 ?? "resume"
let id = target?.1 ?? ""
let name = target?.2 ?? "your music"
try await MusicCommands.play(
kind: kind,
id: id,
title: name,
shuffle: shuffle.map { $0 == .songs },
repeatMode: repeatMode?.rawValue,
queue: "now",
warmupId: nil
)
return .result(dialog: "Playing \(name).")
}
}
struct AddToPlaylistIntent: AppIntent {
static let title: LocalizedStringResource = "Add to Playlist"
static let description = IntentDescription(
"Adds the items passed as input to the specified playlist."
)
static let openAppWhenRun = true
@Parameter(title: "Song")
var song: SongEntity?
@Parameter(title: "Album")
var album: AlbumEntity?
@Parameter(title: "Artist")
var artist: ArtistEntity?
@Parameter(title: "Music")
var sourcePlaylist: PlaylistEntity?
@Parameter(title: "Playlist")
var playlist: PlaylistEntity
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
let sources = try MusicSelection.sources(
song: song,
album: album,
artist: artist,
playlist: sourcePlaylist
)
if sources.contains(where: { $0.id == playlist.id && $0.kind == "playlist" }) {
throw MusicIntentFailure("Choose a different playlist.")
}
try await MusicCommands.addToPlaylist(
playlistId: playlist.id,
sources: sources.map { (kind: $0.kind, id: $0.id) }
)
return .result(dialog: "Adding to \(playlist.title).")
}
}
struct AddToUpNextIntent: AppIntent {
static let title: LocalizedStringResource = "Add to Up Next"
static let description = IntentDescription(
"Adds the music passed as input to your Up Next queue."
)
static let openAppWhenRun = true
@Parameter(title: "Song")
var song: SongEntity?
@Parameter(title: "Album")
var album: AlbumEntity?
@Parameter(title: "Artist")
var artist: ArtistEntity?
@Parameter(title: "Playlist")
var playlist: PlaylistEntity?
@Parameter(title: "Position", default: .next)
var position: UpNextPosition
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
let sources = try MusicSelection.sources(
song: song,
album: album,
artist: artist,
playlist: playlist
)
try await MusicCommands.addToUpNext(
position: position.rawValue,
sources: sources.map { (kind: $0.kind, id: $0.id) }
)
let placement = position == .next ? "Playing this next." : "Adding this to the end of Up Next."
return .result(dialog: "\(placement)")
}
}
struct ClearUpNextIntent: AppIntent {
static let title: LocalizedStringResource = "Clear Up Next"
static let description = IntentDescription("Clears the Up Next queue.")
static let openAppWhenRun = true
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
try await MusicCommands.clearUpNext()
return .result(dialog: "Clearing Up Next.")
}
}
struct CreatePlaylistIntent: AppIntent {
static let title: LocalizedStringResource = "Create Playlist"
static let description = IntentDescription(
"Creates a new playlist, adding any items passed as input."
)
static let openAppWhenRun = true
@Parameter(title: "Name")
var name: String
@Parameter(title: "Song")
var song: SongEntity?
@Parameter(title: "Album")
var album: AlbumEntity?
@Parameter(title: "Artist")
var artist: ArtistEntity?
@Parameter(title: "Playlist")
var playlist: PlaylistEntity?
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmed.isEmpty {
throw MusicIntentFailure("A playlist needs a name.")
}
let sources = [
song.map { (kind: "song", id: $0.id) },
album.map { (kind: "album", id: $0.id) },
artist.map { (kind: "artist", id: $0.id) },
playlist.map { (kind: "playlist", id: $0.id) },
].compactMap { $0 }
try await MusicCommands.createPlaylist(name: trimmed, sources: sources)
return .result(dialog: "Creating \(trimmed).")
}
}
struct GetCurrentSongIntent: AppIntent {
static let title: LocalizedStringResource = "Get Current Song"
static let description = IntentDescription(
"Returns the song that is currently playing in oTunes, if any."
)
static let openAppWhenRun = false
@MainActor
func perform() async throws -> some IntentResult & ReturnsValue<SongEntity> & ProvidesDialog {
guard let song = try await MusicCatalog.currentSong() else {
throw MusicIntentFailure("Nothing is playing in oTunes.")
}
return .result(value: song, dialog: "\(song.title)")
}
}
struct GetDetailsOfMusicIntent: AppIntent {
static let title: LocalizedStringResource = "Get Details of Music"
static let description = IntentDescription(
"Gets a specific piece of information from the music passed into the action."
)
static let openAppWhenRun = false
@Parameter(title: "Song")
var song: SongEntity?
@Parameter(title: "Album")
var album: AlbumEntity?
@Parameter(title: "Artist")
var artist: ArtistEntity?
@Parameter(title: "Playlist")
var playlist: PlaylistEntity?
@Parameter(title: "Detail")
var detail: MusicDetail
@MainActor
func perform() async throws -> some IntentResult & ReturnsValue<String> & ProvidesDialog {
let value = try await detailValue()
return .result(value: value, dialog: value.isEmpty ? "Not available." : "\(value)")
}
private func detailValue() async throws -> String {
if let target = try MusicSelection.singleTarget(
song: song,
album: album,
artist: artist,
playlist: playlist
) {
return try value(for: target)
}
guard let current = try await MusicCatalog.currentSong() else {
throw MusicIntentFailure("Choose music, or play a song in oTunes first.")
}
return Self.value(detail, song: current)
}
private func value(for target: (kind: String, id: String, title: String)) throws -> String {
switch target.kind {
case "song":
guard let song else {
throw MusicIntentFailure("That song is no longer in your library.")
}
return Self.value(detail, song: song)
case "album":
guard let album else {
throw MusicIntentFailure("That album is no longer in your library.")
}
return Self.value(detail, album: album)
case "artist":
guard let artist else {
throw MusicIntentFailure("That artist is no longer in your library.")
}
return Self.value(detail, artist: artist)
case "playlist":
guard let playlist else {
throw MusicIntentFailure("That playlist is no longer in your library.")
}
return Self.value(detail, playlist: playlist)
default:
throw MusicIntentFailure("oTunes can't read that.")
}
}
private static func value(_ detail: MusicDetail, song: SongEntity) -> String {
switch detail {
case .title:
return song.title
case .artist, .albumArtist:
return song.artistName
case .album:
return song.albumTitle
case .genre:
return song.genres
case .duration:
return MusicCatalog.formatDuration(song.durationSeconds)
case .year:
return song.year == "0" ? "" : song.year
case .trackNumber:
return song.trackNumber
case .discNumber:
return song.discNumber
}
}
private static func value(_ detail: MusicDetail, album: AlbumEntity) -> String {
switch detail {
case .title, .album:
return album.title
case .artist, .albumArtist:
return album.artistName
case .year:
return album.year == "0" ? "" : album.year
case .genre, .duration, .trackNumber, .discNumber:
return ""
}
}
private static func value(_ detail: MusicDetail, artist: ArtistEntity) -> String {
switch detail {
case .title, .artist, .albumArtist:
return artist.name
case .album, .genre, .duration, .year, .trackNumber, .discNumber:
return ""
}
}
private static func value(_ detail: MusicDetail, playlist: PlaylistEntity) -> String {
switch detail {
case .title:
return playlist.title
case .artist, .albumArtist:
return playlist.ownerName
case .album, .genre, .duration, .year, .trackNumber, .discNumber:
return ""
}
}
}
struct LoveSongIntent: AppIntent {
static let title: LocalizedStringResource = "Love Song"
static let description = IntentDescription(
"Loves the song that is playing in oTunes. Also used for Favorite Song."
)
static let openAppWhenRun = true
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
guard let song = try await MusicCatalog.currentSong() else {
throw MusicIntentFailure("Nothing is playing in oTunes.")
}
try await MusicCommands.updateAffinity(kind: "song", id: song.id, state: "like")
return .result(dialog: "Loving \(song.title).")
}
}
struct UnlikeSongIntent: AppIntent {
static let title: LocalizedStringResource = "Unlike Song"
static let description = IntentDescription("Removes the love from the song that is playing.")
static let openAppWhenRun = true
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
guard let song = try await MusicCatalog.currentSong() else {
throw MusicIntentFailure("Nothing is playing in oTunes.")
}
try await MusicCommands.updateAffinity(kind: "song", id: song.id, state: "unset")
return .result(dialog: "Unliking \(song.title).")
}
}
struct CreateStationIntent: AppIntent {
static let title: LocalizedStringResource = "Create Station"
static let description = IntentDescription(
"Plays more music by the artist of the song that is playing."
)
static let openAppWhenRun = true
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
guard let song = try await MusicCatalog.currentSong() else {
throw MusicIntentFailure("Nothing is playing in oTunes.")
}
if song.artistId.isEmpty {
throw MusicIntentFailure("oTunes can't find an artist for this song.")
}
try await MusicCommands.createStation(artistId: song.artistId, artistName: song.artistName)
let artist = song.artistName.isEmpty ? "this artist" : song.artistName
return .result(dialog: "Playing more by \(artist).")
}
}
struct PauseMusicIntent: AppIntent {
static let title: LocalizedStringResource = "Pause Music"
static let description = IntentDescription("Pauses playback in oTunes.")
static let openAppWhenRun = true
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
try await MusicCommands.transport("pause")
return .result(dialog: "Pausing.")
}
}
struct ResumeMusicIntent: AppIntent {
static let title: LocalizedStringResource = "Resume Music"
static let description = IntentDescription("Resumes playback in oTunes.")
static let openAppWhenRun = true
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
try await MusicCommands.transport("resume")
return .result(dialog: "Resuming.")
}
}
struct SkipMusicIntent: AppIntent {
static let title: LocalizedStringResource = "Skip Song"
static let description = IntentDescription("Skips to the next song in oTunes.")
static let openAppWhenRun = true
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
try await MusicCommands.transport("next")
return .result(dialog: "Skipping.")
}
}
struct PreviousTrackIntent: AppIntent {
static let title: LocalizedStringResource = "Previous Song"
static let description = IntentDescription("Goes back to the previous song in oTunes.")
static let openAppWhenRun = true
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
try await MusicCommands.transport("previous")
return .result(dialog: "Going back.")
}
}
@@ -1,70 +0,0 @@
import Foundation
internal import ExpoAppIntents
/// Full catalogs live in Application Support, never in UserDefaults. The package
/// catalog contains only a bounded selection for shortcut suggestions and Spotlight.
actor MusicCatalogStorage {
static let shared = MusicCatalogStorage()
private func location(_ kind: String) throws -> URL {
guard ["song", "album", "artist", "playlist", "nowPlaying"].contains(kind) else {
throw MusicIntentFailure("Unknown music catalog.")
}
let directory = try FileManager.default.url(
for: .applicationSupportDirectory, in: .userDomainMask,
appropriateFor: nil, create: true
).appendingPathComponent("MusicIntents", isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
return directory.appendingPathComponent("\(kind).json")
}
func replace(kind: String, json: String) throws {
let data = Data(json.utf8)
let records = try JSONDecoder().decode([AppIntentEntityRecord].self, from: data)
guard Set(records.map(\.id)).count == records.count,
records.allSatisfy({ !$0.id.isEmpty && !$0.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty })
else { throw MusicIntentFailure("Invalid music catalog.") }
try data.write(to: location(kind), options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])
}
func records(kind: String) throws -> [AppIntentEntityRecord] {
let url = try location(kind)
guard FileManager.default.fileExists(atPath: url.path) else { return [] }
return try JSONDecoder().decode([AppIntentEntityRecord].self, from: Data(contentsOf: url))
}
}
/// App-owned completion channel. Expo's dispatcher itself remains one-way.
actor MusicIntentExecution {
static let shared = MusicIntentExecution()
private var waiting = Set<String>()
private var results: [String: String] = [:]
func complete(token: String, error: String?) {
guard waiting.contains(token) else { return }
results[token] = error ?? ""
}
func run(name: String, params: AppIntentParams = [:]) async throws -> String {
let token = UUID().uuidString
let deadline = Date().addingTimeInterval(25)
waiting.insert(token)
defer {
waiting.remove(token)
results.removeValue(forKey: token)
}
var payload = params
payload["completionToken"] = .string(token)
payload["deadline"] = .double(deadline.timeIntervalSince1970 * 1000)
let id = await AppIntentDispatcher.shared.dispatch(name: name, params: payload)
while Date() < deadline {
try Task.checkCancellation()
if let error = results.removeValue(forKey: token) {
if !error.isEmpty { throw MusicIntentFailure(error) }
return id
}
try await Task.sleep(for: .milliseconds(100))
}
throw MusicIntentFailure("oTunes did not finish in time. Open the app, check your connection, and try again.")
}
}
-33
View File
@@ -1,33 +0,0 @@
# Siri and Shortcuts
This integration uses Expo 58 inline modules and `expo-app-intents`. Rebuild the native app after changing Swift declarations or registrations. An OTA JavaScript update cannot add these capabilities.
Playback and library changes open oTunes because they need its authenticated React runtime. Swift dispatches a request and waits for an app-owned completion acknowledgment. Playback waits for the native audio player to load the requested track; warmup waits for it to load while paused. Errors reach Siri, and requests that have expired are discarded before starting a side effect. Native catalog reads do not open the app.
The full entity catalog lives in Application Support. The backend supplies pages of 200 records. Expo's UserDefaults catalog holds at most 100 suggestions per kind, with favorites first, and mirrors those suggestions into Spotlight. Siri's native queries search the full disk catalog. Catalogs refresh on launch, foreground entry, favorite changes, and every five minutes while foregrounded.
Songs, albums, artists, and playlists have Spotlight open intents and on-screen entity associations. Associations require iOS 18.4 and Xcode 27; Spotlight indexing requires iOS 18. Playback donations are made after the player starts, preserve shuffle, and resolve real catalog entities. Removed records trigger donation cleanup. Sign-out clears catalogs, Spotlight entries, donations, and pending invocations. On iOS 27, the query types also handle system requests to rebuild Spotlight indexes.
Audio schema intents require Xcode 27 and iOS 27. Custom intents remain available on earlier supported versions and remain visible on iOS 27 because intent discovery metadata must be a compile-time constant.
## Backend rollout
Deploy the companion Convex changes before installing the new mobile build:
- `library.intentCatalogPage` supplies authenticated, paginated entity records.
- `appIntentPlaylists` records playlist-creation request IDs in the same transaction as creation. Replaying a request returns the original playlist ID.
- `playlists.createPlaylist` accepts an optional `invocationId`; existing callers can omit it.
## Verification
Run from the repository root:
```sh
pnpm --filter @otunes/mobile typecheck
pnpm --filter @otunes/convex typecheck
node --test apps/mobile/lib/app-intents.test.cjs packages/convex/convex/app-intent-playlists.test.cjs
```
Build iOS with Xcode and verify the app target's `ExtractAppIntentsMetadata` phase. TypeScript checks alone do not validate Swift declarations or Apple's schema contracts.
On a suitable device, verify cold and warm playback, paused warmup followed by playback, offline errors, request expiry, playlist replay, and a saved shortcut after upgrading. Check entity resolution after rename/delete and sign-out. Verify Spotlight opening, on-screen requests, and donations separately; metadata extraction does not establish system discovery or successful runtime execution.
-51
View File
@@ -1,51 +0,0 @@
import type { ConfigContext, ExpoConfig } from "expo/config"
export default ({ config }: ConfigContext): ExpoConfig => {
const variant: string =
process.env.APP_VARIANT ?? process.env.EAS_BUILD_PROFILE ?? "production"
if (
variant !== "development" &&
variant !== "preview" &&
variant !== "production"
) {
throw new Error(`Unsupported APP_VARIANT: ${variant}`)
}
const suffix = variant === "production" ? "" : `.${variant}`
const iconSuffix = variant === "production" ? "" : `-${variant}`
const nameSuffix =
variant === "development"
? " (Development)"
: variant === "preview"
? " (Preview)"
: ""
// Expo writes this filename into Xcode build settings without quoting it.
const composer = {
development: "oTunesDev",
preview: "oTunesPreview",
production: "oTunes",
}[variant]
return {
...config,
name: `${config.name}${nameSuffix}`,
slug: config.slug!,
scheme: variant === "production" ? "otunes" : `otunes-${variant}`,
icon: `./assets/icon${iconSuffix}.png`,
ios: {
...config.ios,
bundleIdentifier: `${config.ios!.bundleIdentifier}${suffix}`,
icon: `./assets/${composer}.icon`,
},
android: {
...config.android,
package: `${config.android!.package}${suffix}`,
icon: `./assets/android-icon${iconSuffix}.png`,
adaptiveIcon: {
monochromeImage: "./assets/android-icon-monochrome.png",
foregroundImage: `./assets/android-icon-foreground${iconSuffix}.png`,
backgroundImage: `./assets/android-icon-background${iconSuffix}.png`,
},
},
}
}
+23 -22
View File
@@ -26,11 +26,8 @@
"adaptiveIcon": {
"monochromeImage": "./assets/android-icon-monochrome.png",
"foregroundImage": "./assets/android-icon-foreground.png",
"backgroundImage": "./assets/android-icon-background.png"
},
"userInterfaceStyle": "dark",
"softwareKeyboardLayoutMode": "resize",
"icon": "./assets/android-icon.png"
"backgroundColor": "#C60322"
}
},
"plugins": [
"expo-router",
@@ -47,29 +44,33 @@
[
"expo-splash-screen",
{
"backgroundColor": "#000000"
"ios": {
"backgroundColor": "#ffffff",
"image": "./assets/ios-icon.png",
"dark": {
"image": "./assets/ios-icon-dark.png",
"backgroundColor": "#000000"
},
"imageWidth": 200
},
"android": {
"backgroundColor": "#ffffff",
"image": "./assets/icon.png",
"dark": {
"image": "./assets/icon-dark.png",
"backgroundColor": "#000000"
},
"imageWidth": 200
}
}
],
"expo-image",
"expo-status-bar",
"expo-app-intents",
"./plugins/with-android-colors",
[
"expo-navigation-bar",
{
"enforceContrast": false,
"style": "light"
}
]
"./plugins/with-ios-pod-deployment-target.js",
"./plugins/with-ios-scene-lifecycle.js"
],
"experiments": {
"typedRoutes": true,
"inlineModules": {
"watchedDirectories": [
"app-intents",
"native"
]
}
"typedRoutes": true
},
"extra": {
"router": {},
+55 -105
View File
@@ -1,50 +1,35 @@
import { NavigationBar } from "expo-navigation-bar"
import {
AndroidTabThemeProvider,
useAndroidTabPalette,
useAndroidTabSelectedColor,
} from "@/contexts/android-tab-theme"
import { DarkTheme, DefaultTheme, ThemeProvider } from "expo-router"
import { NativeTabs } from "expo-router/native-tabs"
import { DynamicColorIOS, Platform, View } from "react-native"
import { NativeTabs } from "expo-router/unstable-native-tabs"
import { DynamicColorIOS, Platform, useColorScheme } from "react-native"
import { useMemo } from "react"
import { AndroidMiniPlayer, TabBottomAccessory } from "@/components/mini-player"
import { useAndroidKeyboardVisible } from "@/hooks/use-android-keyboard-visible"
import { TabBottomAccessory } from "@/components/mini-player"
import { usePlaybackQueue } from "@/contexts/playback"
import { appleMusic, colors, miniPlayerHeight, useIsDark } from "@/lib/theme"
export const unstable_settings = { anchor: "library" }
import { appleMusic, colors } from "@/lib/theme"
function useRouterTheme() {
const themeIsDark = useIsDark()
const androidPalette = useAndroidTabPalette()
const isDark = Platform.OS === "android" ? androidPalette.isDark : themeIsDark
const isDark = useColorScheme() === "dark"
return useMemo(() => {
const palette = isDark ? colors.dark : colors.light
const android = Platform.OS === "android" ? androidPalette : null
const base = isDark ? DarkTheme : DefaultTheme
return {
...base,
colors: {
...base.colors,
background: android?.background ?? palette.background,
card: android?.surface ?? palette.card,
text: android?.foreground ?? palette.foreground,
border: android?.divider ?? palette.border,
primary: android?.accentText ?? palette.primary,
background: palette.background,
card: palette.card,
text: palette.foreground,
border: palette.border,
primary: palette.primary,
},
}
}, [isDark, androidPalette])
}, [isDark])
}
function useNativeTabColors() {
const selectedColor = useAndroidTabSelectedColor()
const themeIsDark = useIsDark()
const androidPalette = useAndroidTabPalette()
const isDark = Platform.OS === "android" ? androidPalette.isDark : themeIsDark
const isDark = useColorScheme() === "dark"
const inactive = appleMusic.tabInactive
const iconColor =
@@ -54,23 +39,24 @@ function useNativeTabColors() {
selected: appleMusic.pink,
}
: {
default: androidPalette.secondaryForeground,
selected: selectedColor,
default: isDark ? inactive : "#636366",
selected: appleMusic.pink,
}
const labelColor =
Platform.OS === "ios"
? DynamicColorIOS({ dark: inactive, light: "#636366" })
: androidPalette.secondaryForeground
: isDark
? inactive
: "#636366"
return {
isDark,
tintColor: Platform.OS === "android" ? selectedColor : appleMusic.pink,
iconColor,
labelStyle: {
default: { color: labelColor, fontSize: 10 },
selected: {
color: Platform.OS === "android" ? selectedColor : appleMusic.pink,
color: appleMusic.pink,
fontSize: 10,
fontWeight: "600" as const,
},
@@ -79,93 +65,57 @@ function useNativeTabColors() {
? "systemChromeMaterialDark"
: "systemChromeMaterialLight",
backgroundColor:
Platform.OS === "ios" ? undefined : androidPalette.background,
Platform.OS === "ios"
? undefined
: isDark
? appleMusic.background
: colors.light.background,
}
}
function TabsContent() {
const keyboardVisible = useAndroidKeyboardVisible()
export default function TabsLayout() {
const routerTheme = useRouterTheme()
const tabColors = useNativeTabColors()
const { currentSong, queueSongIds } = usePlaybackQueue()
const showBottomAccessory = Boolean(currentSong && queueSongIds.length > 0)
// NativeTabs already owns the tab bar and system navigation insets.
const androidContentStyle =
Platform.OS === "android"
? {
paddingBottom:
showBottomAccessory && !keyboardVisible ? miniPlayerHeight : 0,
}
: undefined
return (
<ThemeProvider value={routerTheme}>
<View style={{ flex: 1 }}>
{Platform.OS === "android" ? (
<NavigationBar style={tabColors.isDark ? "light" : "dark"} />
<NativeTabs
blurEffect={
tabColors.blurEffect as
"systemChromeMaterialDark" | "systemChromeMaterialLight"
}
backgroundColor={tabColors.backgroundColor}
iconColor={tabColors.iconColor}
labelStyle={tabColors.labelStyle}
tintColor={appleMusic.pink}
minimizeBehavior="onScrollDown"
>
{showBottomAccessory ? (
<NativeTabs.BottomAccessory>
<TabBottomAccessory />
</NativeTabs.BottomAccessory>
) : null}
<NativeTabs
blurEffect={
tabColors.blurEffect as
"systemChromeMaterialDark" | "systemChromeMaterialLight"
}
backgroundColor={tabColors.backgroundColor}
iconColor={tabColors.iconColor}
labelStyle={tabColors.labelStyle}
tintColor={tabColors.tintColor}
minimizeBehavior="onScrollDown"
{...(Platform.OS === "android"
? { disableIndicator: true, rippleColor: tabColors.tintColor }
: {})}
>
{Platform.OS === "ios" && showBottomAccessory ? (
<NativeTabs.BottomAccessory>
<TabBottomAccessory />
</NativeTabs.BottomAccessory>
) : null}
<NativeTabs.Trigger
name="home"
disableTransparentOnScrollEdge
contentStyle={androidContentStyle}
>
<NativeTabs.Trigger.Icon sf="house.fill" md="home" />
<NativeTabs.Trigger.Label>Home</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger name="home" disableTransparentOnScrollEdge>
<NativeTabs.Trigger.Icon sf="house.fill" md="home" />
<NativeTabs.Trigger.Label>Home</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger
name="library"
disableTransparentOnScrollEdge
contentStyle={androidContentStyle}
>
<NativeTabs.Trigger.Icon
sf="music.note.square.stack.fill"
md="library_music"
/>
<NativeTabs.Trigger.Label>Library</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger name="library" disableTransparentOnScrollEdge>
<NativeTabs.Trigger.Icon
sf="music.note.square.stack.fill"
md="library_music"
/>
<NativeTabs.Trigger.Label>Library</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger
name="search"
disableTransparentOnScrollEdge
contentStyle={androidContentStyle}
>
<NativeTabs.Trigger.Icon sf="magnifyingglass" md="search" />
<NativeTabs.Trigger.Label>Search</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
</NativeTabs>
{!keyboardVisible ? <AndroidMiniPlayer /> : null}
</View>
<NativeTabs.Trigger name="search" disableTransparentOnScrollEdge>
<NativeTabs.Trigger.Icon sf="magnifyingglass" md="search" />
<NativeTabs.Trigger.Label>Search</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
</NativeTabs>
</ThemeProvider>
)
}
export default function TabsLayout() {
if (Platform.OS !== "android") return <TabsContent />
return (
<AndroidTabThemeProvider>
<TabsContent />
</AndroidTabThemeProvider>
)
}
+7 -12
View File
@@ -1,11 +1,10 @@
import { Stack } from "expo-router"
import { Platform } from "react-native"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
export const unstable_settings = {
anchor: "index",
initialRouteName: "index",
}
export default function HomeLayout() {
@@ -13,25 +12,21 @@ export default function HomeLayout() {
return (
<Stack
initialRouteName="index"
screenOptions={({ route }) => ({
...baseOptions,
...(Platform.OS === "android" &&
(route.name === "album/[id]" || route.name === "playlist/[id]")
? { animation: "none" as const }
: {}),
title: tabStackScreenTitles[route.name] ?? "Home",
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
headerRight: route.name === "settings" ? undefined : () => <ProfileHeaderButton />,
unstable_headerRightItems:
route.name === "index"
? () => [
route.name === "settings"
? undefined
: () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
],
})}
/>
)
+98 -266
View File
@@ -1,24 +1,9 @@
import { useAndroidScreenPalette } from "@/contexts/android-tab-theme"
import { MusicEntityView } from "@/components/music-entity-view"
import { Stack, useIsFocused, useLocalSearchParams } from "expo-router"
import { StatusBar } from "expo-status-bar"
import { memo, useCallback, useEffect, useMemo } from "react"
import {
FlatList,
Platform,
Pressable,
StyleSheet,
Text,
View,
} from "react-native"
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
import { Ionicons } from "@expo/vector-icons"
import {
CollectionDivider,
collectionInset,
DiscHeader,
} from "@/components/collection-list"
import { AudioFormatBadge } from "@/components/audio-format-badge"
import { CoverImage } from "@/components/cover-image"
import {
@@ -66,66 +51,36 @@ export default function AlbumScreen() {
const isFocused = useIsFocused()
const coverUri =
config && typeof id === "string" ? albumCoverUrl(config.serverUrl, id) : ""
const { palette: artworkPalette, settled } = useCoverPalette(
const { palette, settled } = useCoverPalette(
coverUri,
album ? album.cover != null : album === null ? false : undefined
)
const { palette, onLayout } = useAndroidScreenPalette(artworkPalette)
const songIds = useMemo(
() => album?.tracks.map((track) => track.id as Id<"songs">) ?? [],
[album]
)
// Older servers do not include album format availability yet.
const formatTracks = useCachedQuery(
api.library.getSongsForPlayback,
album && (album.hasLossless === undefined || album.hasAtmos === undefined)
? { ids: songIds }
: "skip"
)
const hasLossless =
album?.hasLossless ??
formatTracks?.some((track) => track && "lossless" in track.files)
const hasAtmos =
album?.hasAtmos ??
formatTracks?.some((track) => track && "atmos" in track.files)
useEffect(() => {
if (album) {
rememberSongs(albumDetailSongs(album))
}
}, [album])
const listItems = useMemo(() => albumListItems(album?.tracks ?? []), [album])
const renderItem = useCallback(
({ item }: { item: AlbumListItem }) => {
if (item.type === "disc") {
return <DiscHeader label={item.label} color={palette.foreground} />
}
return album ? (
const renderTrack = useCallback(
({ item, index }: { item: BrowseAlbumTrack; index: number }) =>
album ? (
<AlbumTrackRow
track={item.track}
number={item.number}
track={item}
index={index}
album={album}
songIds={songIds}
palette={palette}
favorited={isSongFavorite(item.track.id)}
onPlay={(songId, ids) =>
playFromSong(songId, ids, `album:${album.id}`)
}
favorited={isSongFavorite(item.id)}
onPlay={playFromSong}
onAction={handleAlbumTrackAction}
/>
) : null
},
[
album,
handleAlbumTrackAction,
isSongFavorite,
palette,
playFromSong,
songIds,
]
) : null,
[album, handleAlbumTrackAction, isSongFavorite, palette, playFromSong, songIds]
)
if (album === undefined || !config || !settled) {
@@ -173,26 +128,16 @@ export default function AlbumScreen() {
title: "",
headerLargeTitle: false,
headerTintColor: palette.foreground,
...(Platform.OS === "android"
? {
headerStyle: { backgroundColor: palette.background },
statusBarStyle: palette.isDark
? ("light" as const)
: ("dark" as const),
}
: {}),
headerRight: () => (
<MediaActionMenu
stationArtistId={album.artist.id}
selectedCount={album.tracks.length}
favorited={isAlbumFav(album.id)}
share={{ type: "album", albumId: album.id, title: album.title }}
share={{ type: "album", albumId: album.id }}
onAction={(action) =>
void handleAlbumDetailAction(
album.id as Id<"albums">,
songIds,
action,
album.artist.id as Id<"artists">
action
)
}
>
@@ -200,7 +145,7 @@ export default function AlbumScreen() {
<Ionicons
name="ellipsis-horizontal"
size={22}
color={palette.isDark ? "#fff" : "#000"}
color={palette.foreground}
/>
</Pressable>
</MediaActionMenu>
@@ -208,172 +153,80 @@ export default function AlbumScreen() {
}}
/>
<FlatList
onLayout={onLayout}
{...longListProps}
data={listItems}
keyExtractor={albumListItemKey}
data={album.tracks}
keyExtractor={(track) => track.id}
style={{ flex: 1, backgroundColor: palette.background }}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
indicatorStyle={palette.isDark ? "white" : "black"}
ListHeaderComponent={
<View>
<MusicEntityView kind="album" id={album.id} style={styles.hero}>
<CoverImage
uri={coverUri}
hasCover={album.cover != null}
style={styles.cover}
/>
<Text style={[styles.title, { color: palette.foreground }]}>
{album.title}
<View style={styles.hero}>
<CoverImage
uri={coverUri}
hasCover={album.cover != null}
style={styles.cover}
/>
<Text style={[styles.title, { color: palette.foreground }]}>
{album.title}
</Text>
<Pressable onPress={() => push(`/artist/${album.artist.id}`)}>
<Text style={[styles.artist, { color: palette.accentText }]}>
{album.artist.name}
</Text>
</Pressable>
{metadata ? (
<Text style={{ color: palette.secondaryForeground }}>
{metadata}
</Text>
) : null}
<View style={styles.actions}>
<Pressable
onPress={() => push(`/artist/${album.artist.id}`)}
style={styles.artistPressable}
onPress={() => void toggleAlbumFavorite(album.id)}
hitSlop={8}
style={[styles.iconAction, { backgroundColor: palette.surface }]}
>
<Text style={[styles.artist, { color: palette.accentText }]}>
{album.artist.name}
</Text>
</Pressable>
<View
style={{
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
flexWrap: "wrap",
gap: 8,
}}
>
{metadata ? (
<Text style={{ color: palette.secondaryForeground }}>
{metadata}
</Text>
) : null}
{hasLossless ? (
<>
{metadata ? (
<Text style={{ color: palette.secondaryForeground }}>
·
</Text>
) : null}
<AudioFormatBadge
format="lossless"
color={palette.secondaryForeground}
backgroundColor={palette.background}
/>
</>
) : null}
{hasAtmos ? (
<>
{metadata || hasLossless ? (
<Text style={{ color: palette.secondaryForeground }}>
·
</Text>
) : null}
<AudioFormatBadge
format="atmos"
color={palette.secondaryForeground}
backgroundColor={palette.background}
/>
</>
) : null}
</View>
<View style={styles.actions}>
<Pressable
onPress={() => void toggleAlbumFavorite(album.id)}
hitSlop={8}
style={[
styles.iconAction,
{ backgroundColor: palette.surface },
]}
>
<Ionicons
name={favorited ? "star" : "star-outline"}
size={24}
color={favorited ? palette.accent : palette.foreground}
/>
</Pressable>
<Button
title="Play"
icon="play"
onPress={() => void playAlbum(album.id, songIds)}
style={styles.playButton}
tint={{
background: palette.accent,
foreground: palette.accentForeground,
}}
<Ionicons
name={favorited ? "star" : "star-outline"}
size={24}
color={favorited ? palette.accent : palette.foreground}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() => void playAlbumShuffled(album.id, songIds)}
style={[
styles.iconAction,
{ backgroundColor: palette.surface },
]}
>
<Ionicons
name="shuffle"
size={24}
color={palette.foreground}
/>
</Pressable>
</View>
</MusicEntityView>
<CollectionDivider color={palette.divider} />
</Pressable>
<Button
title="Play"
icon="play"
onPress={() => void playAlbum(album.id, songIds)}
style={styles.playButton}
tint={{
background: palette.accent,
foreground: palette.accentForeground,
}}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() => void playAlbumShuffled(album.id, songIds)}
style={[styles.iconAction, { backgroundColor: palette.surface }]}
>
<Ionicons
name="shuffle"
size={24}
color={palette.foreground}
/>
</Pressable>
</View>
</View>
}
renderItem={renderItem}
renderItem={renderTrack}
/>
</>
)
}
type AlbumListItem =
| { type: "disc"; key: string; label: string }
| { type: "track"; track: BrowseAlbumTrack; number: number }
/**
* Tracks arrive sorted by disc then track number. Disc headers are only
* inserted when the album spans more than one disc.
*/
function albumListItems(tracks: BrowseAlbumTrack[]): AlbumListItem[] {
const multiDisc = new Set(tracks.map((track) => track.diskNumber)).size > 1
const items: AlbumListItem[] = []
let currentDisc: number | null | undefined
let positionInDisc = 0
for (const track of tracks) {
if (track.diskNumber !== currentDisc) {
currentDisc = track.diskNumber
positionInDisc = 0
if (multiDisc) {
items.push({
type: "disc",
key: `disc-${currentDisc ?? "unknown"}`,
label: currentDisc == null ? "Other" : `Disc ${currentDisc}`,
})
}
}
positionInDisc += 1
items.push({
type: "track",
track,
number: track.track || positionInDisc,
})
}
return items
}
function albumListItemKey(item: AlbumListItem) {
return item.type === "disc" ? item.key : item.track.id
}
const AlbumTrackRow = memo(function AlbumTrackRow({
track,
number,
index,
album,
songIds,
palette,
@@ -382,7 +235,7 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
onAction,
}: {
track: BrowseAlbumTrack
number: number
index: number
album: BrowseAlbumDetail
songIds: Id<"songs">[]
palette: CoverPalette
@@ -396,7 +249,6 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
}) {
return (
<MediaContextMenu
stationArtistId={album.artist.id}
favorited={favorited}
navigation={{
artist: { id: album.artist.id },
@@ -406,48 +258,38 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
type: "song",
albumId: album.id,
songId: track.id,
title: `${track.title} - ${album.title}`,
}}
onAction={(action) => void onAction(track, album, action)}
>
<MusicEntityView kind="song" id={track.id}>
<Pressable
style={styles.trackRow}
onPress={() => void onPlay(track.id as Id<"songs">, songIds)}
<Pressable
style={[styles.trackRow, { borderBottomColor: palette.divider }]}
onPress={() => void onPlay(track.id as Id<"songs">, songIds)}
>
<Text
style={[styles.trackNumber, { color: palette.secondaryForeground }]}
>
{track.track || index + 1}
</Text>
<View style={styles.trackMeta}>
<Text
style={[styles.trackNumber, { color: palette.secondaryForeground }]}
style={[styles.trackTitle, { color: palette.foreground }]}
numberOfLines={1}
>
{number}
{track.title}
</Text>
<View
style={[
styles.trackContent,
{ borderBottomColor: palette.divider },
]}
>
<View style={styles.trackMeta}>
<Text
style={[styles.trackTitle, { color: palette.foreground }]}
numberOfLines={1}
>
{track.title}
</Text>
{track.artists ? (
<Text
style={{ color: palette.secondaryForeground }}
numberOfLines={1}
>
{track.artists.join(", ")}
</Text>
) : null}
</View>
<Text style={{ color: palette.secondaryForeground }}>
{formatDuration(track.durationSeconds)}
{track.artists ? (
<Text
style={{ color: palette.secondaryForeground }}
numberOfLines={1}
>
{track.artists.join(", ")}
</Text>
</View>
</Pressable>
</MusicEntityView>
) : null}
</View>
<Text style={{ color: palette.secondaryForeground }}>
{formatDuration(track.durationSeconds)}
</Text>
</Pressable>
</MediaContextMenu>
)
})
@@ -465,8 +307,7 @@ const styles = StyleSheet.create({
borderRadius: radius.lg,
},
title: { fontSize: 24, fontWeight: "800", textAlign: "center" },
artistPressable: { alignSelf: "stretch" },
artist: { fontSize: 16, fontWeight: "600", textAlign: "center" },
artist: { fontSize: 16, fontWeight: "600" },
actions: {
flexDirection: "row",
alignItems: "center",
@@ -485,22 +326,13 @@ const styles = StyleSheet.create({
trackRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.sm,
paddingLeft: collectionInset,
},
trackNumber: { width: 24, fontSize: 16, textAlign: "center" },
trackContent: {
flex: 1,
minWidth: 0,
flexDirection: "row",
alignItems: "center",
alignSelf: "stretch",
gap: spacing.md,
minHeight: 52,
minHeight: 60,
paddingHorizontal: spacing.lg,
paddingVertical: 12,
marginRight: collectionInset,
borderBottomWidth: StyleSheet.hairlineWidth,
},
trackNumber: { width: 24, textAlign: "center" },
trackMeta: { flex: 1, minWidth: 0 },
trackTitle: { fontSize: 16, fontWeight: "500" },
})
@@ -1,4 +1,3 @@
import { MusicEntityView } from "@/components/music-entity-view"
import { Stack, useLocalSearchParams } from "expo-router"
import { Pressable, StyleSheet, Text, View } from "react-native"
import { Ionicons } from "@expo/vector-icons"
@@ -75,11 +74,7 @@ export default function ArtistScreen() {
<MediaActionMenu
selectedCount={data.albums.length}
favorited={isArtistFav(data.artist.id)}
share={{
type: "artist",
artistId: data.artist.id,
title: data.artist.name,
}}
share={{ type: "artist", artistId: data.artist.id }}
onAction={(action) =>
void handleArtistAction(data.artist, action)
}
@@ -100,11 +95,7 @@ export default function ArtistScreen() {
paddingBottom={contentBottomInset}
contentInset={false}
ListHeaderComponent={
<MusicEntityView
kind="artist"
id={data.artist.id}
style={styles.hero}
>
<View style={styles.hero}>
<CoverImage
uri={artistCoverUrl(config.serverUrl, data.artist.id)}
hasCover={data.artist.photo != null}
@@ -147,7 +138,7 @@ export default function ArtistScreen() {
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
</View>
</MusicEntityView>
</View>
}
/>
</>
@@ -142,7 +142,7 @@ const ArtistRow = memo(function ArtistRow({
return (
<MediaContextMenu
favorited={favorited}
share={{ type: "artist", artistId: artist.id, title: artist.name }}
share={{ type: "artist", artistId: artist.id }}
onAction={(action) => void onAction(artist, action)}
>
<Pressable
@@ -1,21 +1,9 @@
import {
PlaylistSearchBar,
usePlaylistSearch,
} from "@/components/playlist-search-bar"
import { useAndroidScreenPalette } from "@/contexts/android-tab-theme"
import { MusicEntityView } from "@/components/music-entity-view"
import { useMutation } from "convex/react"
import { memo, useCallback, useEffect, useMemo } from "react"
import {
Stack,
useIsFocused,
useLocalSearchParams,
useRouter,
} from "expo-router"
import { Stack, useIsFocused, useLocalSearchParams, useRouter } from "expo-router"
import { StatusBar } from "expo-status-bar"
import {
FlatList,
Platform,
Pressable,
StyleSheet,
Text,
@@ -25,13 +13,7 @@ import {
import ReanimatedSwipeable from "react-native-gesture-handler/ReanimatedSwipeable"
import { Ionicons } from "@expo/vector-icons"
import { CollectionDivider } from "@/components/collection-list"
import { CoverImage } from "@/components/cover-image"
import {
SwipeToRemoveRow,
useSwipeRowGroup,
type SwipeRowGroup,
} from "@/components/ios-swipe-to-remove-row"
import {
MediaActionMenu,
@@ -43,7 +25,10 @@ import { contentBottomInset, SongListRow } from "@/components/player"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { useCachedQuery } from "@/hooks/use-cached-query"
import {
useCachedPaginatedQuery,
useCachedQuery,
} from "@/hooks/use-cached-query"
import { useCoverPalette } from "@/hooks/use-cover-palette"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api"
@@ -52,10 +37,11 @@ import type { BrowsePlaylistDetail, BrowseSong } from "@otunes/convex/types"
import type { CoverPalette } from "@/lib/cover-palette"
import { longListProps } from "@/lib/list"
import { rememberSongs } from "@/lib/song-cache"
import { showError } from "@/lib/toast"
import { showError, showSuccess } from "@/lib/toast"
import { playlistCoverUrl } from "@/lib/urls"
import { radius, spacing, useThemeColors } from "@/lib/theme"
const PAGE_SIZE = 50
const PLAYLIST_LABEL = "Add to Another Playlist"
const OWNER_MENU_ACTIONS: MediaAction[] = [
"share",
@@ -74,24 +60,46 @@ export default function PlaylistScreen() {
const playlistId = typeof id === "string" ? (id as Id<"playlists">) : null
const playlist = useCachedQuery(
api.playlists.browsePlaylistDetail,
playlistId ? { id: playlistId } : "skip"
playlistId
? {
id: playlistId,
includeSongs: false,
}
: "skip"
)
const {
results: songs,
status,
loadMore,
isCached,
} = useCachedPaginatedQuery(
api.playlists.browsePlaylistSongsPaginated,
playlistId ? { id: playlistId } : "skip",
{ initialNumItems: PAGE_SIZE }
)
const allSongIds = useCachedQuery(
api.playlists.getPlaylistSongIds,
playlistId ? { playlistId } : "skip"
)
const songs = playlist?.songs
const coverUri =
config && playlistId
? playlistCoverUrl(config.serverUrl, playlist?.id ?? playlistId)
: ""
const { palette: artworkPalette, settled } = useCoverPalette(
const { palette, settled } = useCoverPalette(
coverUri,
playlist ? playlist.cover != null : playlist === null ? false : undefined
)
const { palette, onLayout } = useAndroidScreenPalette(artworkPalette)
useEffect(() => {
if (songs) rememberSongs(songs)
rememberSongs(songs)
}, [songs])
if (playlist === undefined || !config || !settled) {
if (
playlist === undefined ||
(status === "LoadingFirstPage" && !isCached) ||
!config ||
!settled
) {
return (
<>
<Stack.Screen
@@ -125,27 +133,32 @@ export default function PlaylistScreen() {
return (
<PlaylistContent
onLayout={onLayout}
playlist={playlist}
songs={playlist.songs}
songs={songs}
allSongIds={allSongIds}
coverUri={coverUri}
palette={palette}
onEndReached={() => {
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
/>
)
}
function PlaylistContent({
onLayout,
playlist,
songs,
allSongIds,
coverUri,
palette,
onEndReached,
}: {
onLayout?: () => void
playlist: BrowsePlaylistDetail
songs: BrowseSong[]
allSongIds: Id<"songs">[] | undefined
coverUri: string
palette: CoverPalette
onEndReached: () => void
}) {
const router = useRouter()
const isFocused = useIsFocused()
@@ -161,15 +174,12 @@ function PlaylistContent({
const playlistId = playlist.id
const isSubscribed = playlist.isSubscribed
const canEdit = playlist.isOwner && playlistId !== null
const songIds = useMemo(() => songs.map((song) => song.id), [songs])
const { filteredSongs, onQueryChange, onSearchSubmit } =
usePlaylistSearch(songs)
const swipeGroup = useSwipeRowGroup()
const loadedSongIds = useMemo(() => songs.map((song) => song.id), [songs])
const songIds = allSongIds ?? loadedSongIds
const handlePlaySong = useCallback(
(song: BrowseSong) =>
void playFromSong(song.id, songIds, `playlist:${playlistId}`),
[playFromSong, songIds, playlistId]
(song: BrowseSong) => void playFromSong(song.id, songIds),
[playFromSong, songIds]
)
const handleSongMenuAction = useCallback(
@@ -180,37 +190,38 @@ function PlaylistContent({
const handleRemoveSong = useCallback(
async (songId: Id<"songs">) => {
if (!playlistId) return false
if (!playlistId) return
try {
await removeSongs({ playlistId, songIds: [songId] })
return true
showSuccess("Removed from playlist")
} catch (error) {
showError(
error instanceof Error
? error.message
: "Failed to remove from playlist"
)
return false
}
},
[playlistId, removeSongs]
)
const handlePlay = useCallback(() => {
if (playlistId) void playPlaylist(playlistId, songIds)
}, [playPlaylist, playlistId, songIds])
if (playlistId) void playPlaylist(playlistId, allSongIds)
}, [allSongIds, playPlaylist, playlistId])
const handleShuffle = useCallback(() => {
if (playlistId) void playPlaylistShuffled(playlistId, songIds)
}, [playPlaylistShuffled, playlistId, songIds])
if (playlistId) void playPlaylistShuffled(playlistId, allSongIds)
}, [allSongIds, playPlaylistShuffled, playlistId])
const handleSubscribeToggle = useCallback(async () => {
if (!playlistId) return
try {
if (isSubscribed) {
await unsubscribe({ playlistId })
showSuccess("Unsubscribed")
} else {
await subscribe({ playlistId })
showSuccess("Subscribed")
}
} catch (error) {
showError(
@@ -224,6 +235,7 @@ function PlaylistContent({
if (!playlistId) return
try {
await deletePlaylist({ playlistId })
showSuccess("Playlist deleted")
router.back()
} catch (error) {
showError(
@@ -245,14 +257,6 @@ function PlaylistContent({
title: "",
headerLargeTitle: false,
headerTintColor: palette.foreground,
...(Platform.OS === "android"
? {
headerStyle: { backgroundColor: palette.background },
statusBarStyle: palette.isDark
? ("light" as const)
: ("dark" as const),
}
: {}),
headerRight: () => (
<MediaActionMenu
selectedCount={songIds.length}
@@ -260,7 +264,6 @@ function PlaylistContent({
share={{
type: "playlist",
playlistId: playlistId ?? "favorites",
title: playlist?.title ?? "oTunes",
}}
includeActions={canEdit ? OWNER_MENU_ACTIONS : undefined}
onAction={handlePlaylistMenuAction}
@@ -269,7 +272,7 @@ function PlaylistContent({
<Ionicons
name="ellipsis-horizontal"
size={22}
color={palette.isDark ? "#fff" : "#000"}
color={palette.foreground}
/>
</Pressable>
</MediaActionMenu>
@@ -280,10 +283,7 @@ function PlaylistContent({
deletePlaylist,
handlePlaylistDetailAction,
palette.foreground,
palette.background,
palette.isDark,
playlistId,
playlist?.title,
router,
songIds,
])
@@ -295,7 +295,6 @@ function PlaylistContent({
favorited={isSongFavorite(song.id)}
removable={canEdit}
palette={palette}
swipeGroup={swipeGroup}
onPlay={handlePlaySong}
onAction={handleSongMenuAction}
onRemove={handleRemoveSong}
@@ -308,7 +307,6 @@ function PlaylistContent({
handleSongMenuAction,
isSongFavorite,
palette,
swipeGroup,
]
)
@@ -318,34 +316,19 @@ function PlaylistContent({
<StatusBar style={palette.isDark ? "light" : "dark"} />
) : null}
<Stack.Screen options={screenOptions} />
<PlaylistSearchBar
onQueryChange={onQueryChange}
onSearchSubmit={onSearchSubmit}
/>
<FlatList
onLayout={onLayout}
{...longListProps}
data={filteredSongs}
data={songs}
keyExtractor={songKey}
renderItem={renderItem}
style={{ flex: 1, backgroundColor: palette.background }}
indicatorStyle={palette.isDark ? "white" : "black"}
contentContainerStyle={styles.listContent}
contentInsetAdjustmentBehavior="automatic"
onScrollBeginDrag={swipeGroup.closeOpenRow}
ListEmptyComponent={
<Text
style={[
styles.emptyResults,
{ color: palette.secondaryForeground },
]}
>
{songs.length ? "No songs found." : "No songs in this playlist."}
</Text>
}
onEndReached={onEndReached}
onEndReachedThreshold={0.5}
ListHeaderComponent={
<PlaylistHero
entityId={playlistId ?? "otunes:favorites"}
coverUri={coverUri}
hasCover={playlist.cover != null}
title={playlist.title}
@@ -372,7 +355,6 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
favorited,
removable,
palette,
swipeGroup,
onPlay,
onAction,
onRemove,
@@ -381,20 +363,17 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
favorited: boolean
removable: boolean
palette: CoverPalette
swipeGroup: SwipeRowGroup
onPlay: (song: BrowseSong) => void
onAction: (song: BrowseSong, action: MediaAction) => void
onRemove: (songId: Id<"songs">) => Promise<boolean>
onRemove: (songId: Id<"songs">) => void
}) {
const colors = useThemeColors()
const handleRemove = useCallback(() => onRemove(song.id), [onRemove, song.id])
const row = (
<SongListRow
song={song}
favorited={favorited}
playlistLabel={PLAYLIST_LABEL}
palette={palette}
inset
onPlay={onPlay}
onAction={onAction}
/>
@@ -404,19 +383,6 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
return row
}
if (Platform.OS === "ios") {
return (
<SwipeToRemoveRow
group={swipeGroup}
backgroundColor={palette.background}
actionAccessibilityLabel={`Remove ${song.title} from playlist`}
onRemove={handleRemove}
>
{row}
</SwipeToRemoveRow>
)
}
return (
<ReanimatedSwipeable
friction={2}
@@ -431,7 +397,7 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
accessibilityLabel={`Remove ${song.title} from playlist`}
onPress={() => {
swipeable.close()
void handleRemove()
onRemove(song.id)
}}
style={[styles.removeAction, { backgroundColor: colors.destructive }]}
>
@@ -453,7 +419,6 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
})
const PlaylistHero = memo(function PlaylistHero({
entityId,
coverUri,
hasCover,
title,
@@ -465,7 +430,6 @@ const PlaylistHero = memo(function PlaylistHero({
onPlay,
onShuffle,
}: {
entityId: string
coverUri: string
hasCover: boolean
title: string
@@ -478,67 +442,59 @@ const PlaylistHero = memo(function PlaylistHero({
onShuffle: () => void
}) {
return (
<MusicEntityView kind="playlist" id={entityId}>
<View style={styles.hero}>
<CoverImage uri={coverUri} hasCover={hasCover} style={styles.cover} />
<Text style={[styles.title, { color: palette.foreground }]}>
{title}
</Text>
<Text style={{ color: palette.secondaryForeground }}>{ownerName}</Text>
<View style={styles.actions}>
{showSubscribe ? (
<Pressable
accessibilityRole="button"
accessibilityLabel={isSubscribed ? "Subscribed" : "Subscribe"}
accessibilityState={{ selected: isSubscribed }}
hitSlop={8}
onPress={onSubscribeToggle}
style={[
styles.iconAction,
{
backgroundColor: isSubscribed
? palette.surface
: palette.accent,
},
]}
>
<Ionicons
name={isSubscribed ? "checkmark" : "add"}
size={24}
color={
isSubscribed ? palette.foreground : palette.accentForeground
}
/>
</Pressable>
) : null}
<Button
title="Play"
icon="play"
onPress={onPlay}
style={styles.playButton}
tint={{
background: palette.accent,
foreground: palette.accentForeground,
}}
/>
<View style={styles.hero}>
<CoverImage uri={coverUri} hasCover={hasCover} style={styles.cover} />
<Text style={[styles.title, { color: palette.foreground }]}>{title}</Text>
<Text style={{ color: palette.secondaryForeground }}>{ownerName}</Text>
<View style={styles.actions}>
{showSubscribe ? (
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
accessibilityLabel={isSubscribed ? "Subscribed" : "Subscribe"}
accessibilityState={{ selected: isSubscribed }}
hitSlop={8}
onPress={onShuffle}
style={[styles.iconAction, { backgroundColor: palette.surface }]}
onPress={onSubscribeToggle}
style={[
styles.iconAction,
{
backgroundColor: isSubscribed ? palette.surface : palette.accent,
},
]}
>
<Ionicons name="shuffle" size={24} color={palette.foreground} />
<Ionicons
name={isSubscribed ? "checkmark" : "add"}
size={24}
color={
isSubscribed ? palette.foreground : palette.accentForeground
}
/>
</Pressable>
</View>
) : null}
<Button
title="Play"
icon="play"
onPress={onPlay}
style={styles.playButton}
tint={{
background: palette.accent,
foreground: palette.accentForeground,
}}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={onShuffle}
style={[styles.iconAction, { backgroundColor: palette.surface }]}
>
<Ionicons name="shuffle" size={24} color={palette.foreground} />
</Pressable>
</View>
<CollectionDivider color={palette.divider} />
</MusicEntityView>
</View>
)
})
const styles = StyleSheet.create({
emptyResults: { padding: spacing.lg, textAlign: "center" },
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
listContent: { paddingBottom: contentBottomInset },
hero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm },
@@ -1,7 +1,3 @@
import {
PlaylistSearchBar,
usePlaylistSearch,
} from "@/components/playlist-search-bar"
import { memo, useCallback, useEffect, useMemo } from "react"
import {
FlatList,
@@ -12,14 +8,16 @@ import {
type ListRenderItemInfo,
} from "react-native"
import { CollectionDivider } from "@/components/collection-list"
import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset, SongListRow } from "@/components/player"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { useCachedQuery } from "@/hooks/use-cached-query"
import {
useCachedPaginatedQuery,
useCachedQuery,
} from "@/hooks/use-cached-query"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api"
import type { MediaAction } from "@/components/media-context-menu"
@@ -30,23 +28,32 @@ import { radius, spacing, useThemeColors } from "@/lib/theme"
import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router"
const PAGE_SIZE = 50
const SCREEN_OPTIONS = { title: "", headerLargeTitle: false }
export default function FavoritesScreen() {
const colors = useThemeColors()
const { config } = useServerConfig()
const favorites = useCachedQuery(api.favorites.browseFavoritesPlaylistDetail)
const songs = favorites?.songs ?? []
const favorites = useCachedQuery(api.favorites.browseFavoritesSummary)
const {
results: songs,
status,
loadMore,
isCached,
} = useCachedPaginatedQuery(
api.favorites.browseFavoritesSongsPaginated,
{},
{ initialNumItems: PAGE_SIZE }
)
const { playInOrder, playShuffled, playFromSong } = usePlaybackActions()
const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions()
const songIds = useMemo(() => songs.map((song) => song.id), [songs])
const { filteredSongs, onQueryChange, onSearchSubmit } =
usePlaylistSearch(songs)
const loadedSongIds = useMemo(() => songs.map((song) => song.id), [songs])
const songIds = favorites?.songIds ?? loadedSongIds
useEffect(() => {
if (favorites) rememberSongs(favorites.songs)
}, [favorites])
rememberSongs(songs)
}, [songs])
const handlePlaySong = useCallback(
(song: BrowseSong) => void playFromSong(song.id, songIds),
@@ -72,7 +79,6 @@ export default function FavoritesScreen() {
song={song}
favorited={isSongFavorite(song.id)}
playlistLabel="Add to Another Playlist"
inset
onPlay={handlePlaySong}
onAction={handleSongMenuAction}
/>
@@ -80,7 +86,11 @@ export default function FavoritesScreen() {
[handlePlaySong, handleSongMenuAction, isSongFavorite]
)
if (favorites === undefined || !config) {
if (
favorites === undefined ||
(status === "LoadingFirstPage" && !isCached) ||
!config
) {
return (
<>
<Stack.Screen options={SCREEN_OPTIONS} />
@@ -105,25 +115,18 @@ export default function FavoritesScreen() {
return (
<>
<Stack.Screen options={SCREEN_OPTIONS} />
<PlaylistSearchBar
onQueryChange={onQueryChange}
onSearchSubmit={onSearchSubmit}
/>
<FlatList
{...longListProps}
data={filteredSongs}
data={songs}
keyExtractor={songKey}
renderItem={renderItem}
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={styles.listContent}
contentInsetAdjustmentBehavior="automatic"
ListEmptyComponent={
<Text
style={[styles.emptyResults, { color: colors.mutedForeground }]}
>
{songs.length ? "No songs found." : "No songs in this playlist."}
</Text>
}
onEndReached={() => {
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
onEndReachedThreshold={0.5}
ListHeaderComponent={
<FavoritesHero
title={favorites.title}
@@ -152,45 +155,39 @@ const FavoritesHero = memo(function FavoritesHero({
const colors = useThemeColors()
return (
<View>
<View style={styles.hero}>
<View
style={[
styles.cover,
styles.coverPlaceholder,
{ backgroundColor: colors.coverPlaceholder },
]}
<View style={styles.hero}>
<View
style={[
styles.cover,
styles.coverPlaceholder,
{ backgroundColor: colors.coverPlaceholder },
]}
>
<Ionicons name="star" size={120} color={colors.primary} />
</View>
<Text style={[styles.title, { color: colors.foreground }]}>{title}</Text>
<View style={styles.actions}>
<Button
title="Play"
icon="play"
onPress={onPlay}
style={styles.playButton}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={onShuffle}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
>
<Ionicons name="star" size={120} color={colors.primary} />
</View>
<Text style={[styles.title, { color: colors.foreground }]}>
{title}
</Text>
<View style={styles.actions}>
<Button
title="Play"
icon="play"
onPress={onPlay}
style={styles.playButton}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={onShuffle}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
</View>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
</View>
<CollectionDivider />
</View>
)
})
const styles = StyleSheet.create({
emptyResults: { padding: spacing.lg, textAlign: "center" },
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
listContent: { paddingBottom: contentBottomInset },
hero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm },
+1 -1
View File
@@ -160,7 +160,7 @@ export default function QueueScreen() {
)
)}
</View>
) : undefined
) : null
}
/>
</>
+90 -123
View File
@@ -1,12 +1,10 @@
import { dolbyAtmosSupported } from "@/lib/playback-capabilities"
import { Ionicons } from "@expo/vector-icons"
import { useAction, useMutation, useQuery } from "convex/react"
import { Image } from "expo-image"
import * as ImagePicker from "expo-image-picker"
import { useRouter } from "expo-router"
import { useState } from "react"
import { router } from "expo-router"
import {
Platform,
Pressable,
ScrollView,
StyleSheet,
@@ -22,9 +20,9 @@ import { useInvalidateAuthSession } from "@/contexts/convex-auth-session"
import { useServerConfig } from "@/contexts/server-config"
import { initialsFromName } from "@/lib/format"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { changeServer, signOut } from "@/lib/session"
import { clearLocalData, signOutToSignIn } from "@/lib/session"
import { radius, spacing, useThemeColors } from "@/lib/theme"
import { showError } from "@/lib/toast"
import { showError, showSuccess } from "@/lib/toast"
import type { PlaybackQuality } from "@/lib/urls"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
@@ -75,6 +73,7 @@ const SECTIONS: SectionConfig[] = [
export default function SettingsScreen() {
const colors = useThemeColors()
const router = useRouter()
const user = useCachedQuery(api.auth.currentUser)
const { invalidateSession } = useInvalidateAuthSession()
const { clearServer } = useServerConfig()
@@ -92,19 +91,14 @@ export default function SettingsScreen() {
const visibleSections = SECTIONS.filter((item) => !item.admin || isAdmin)
async function handleSignOut() {
try {
await signOut(invalidateSession)
} catch {
showError("Could not clear all local data.")
}
await signOutToSignIn(router, invalidateSession)
}
async function handleChangeServer() {
try {
await changeServer(invalidateSession, clearServer)
} catch {
showError("Could not clear all local data.")
}
await invalidateSession()
await clearLocalData()
await clearServer()
router.replace("/server")
}
return (
@@ -185,6 +179,7 @@ function ProfileSection({ user }: { user: CurrentUser }) {
await updateImage({
image: `data:${mime};base64,${result.assets[0].base64}`,
})
showSuccess("Profile photo updated")
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to update photo"
@@ -195,6 +190,7 @@ function ProfileSection({ user }: { user: CurrentUser }) {
async function removeImage() {
try {
await updateImage({ image: null })
showSuccess("Profile photo removed")
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to remove photo"
@@ -213,6 +209,7 @@ function ProfileSection({ user }: { user: CurrentUser }) {
await updatePassword({ newPassword })
setNewPassword("")
setConfirmPassword("")
showSuccess("Password updated")
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to update password"
@@ -261,8 +258,9 @@ function ProfileSection({ user }: { user: CurrentUser }) {
variant="secondary"
disabled={name.trim() === user.name}
onPress={() =>
void updateName({ name: name.trim() }).catch((error: Error) =>
showError(error.message)
void updateName({ name: name.trim() }).then(
() => showSuccess("Name updated"),
(error: Error) => showError(error.message)
)
}
/>
@@ -281,8 +279,9 @@ function ProfileSection({ user }: { user: CurrentUser }) {
variant="secondary"
disabled={email.trim() === user.email}
onPress={() =>
void updateEmail({ email: email.trim() }).catch((error: Error) =>
showError(error.message)
void updateEmail({ email: email.trim() }).then(
() => showSuccess("Email updated"),
(error: Error) => showError(error.message)
)
}
/>
@@ -376,13 +375,8 @@ function QualitySection({ user }: { user: CurrentUser }) {
<SettingsCard title="Spatial Audio">
<SwitchRow
title="Prefer Dolby Atmos"
subtitle={
dolbyAtmosSupported
? "Use Atmos versions when they are available."
: "This device does not support Dolby Atmos playback."
}
disabled={!dolbyAtmosSupported}
value={dolbyAtmosSupported && (user.preferAtmos ?? false)}
subtitle="Use Atmos versions when they are available."
value={user.preferAtmos ?? false}
onValueChange={(checked) =>
void updateAtmos({ preferAtmos: checked }).catch((error: Error) =>
showError(error.message)
@@ -413,6 +407,7 @@ function LibrarySection() {
setUpdating(true)
try {
await updateLibrary({})
showSuccess("Library updated")
} catch (error) {
showError(
error instanceof Error
@@ -432,7 +427,8 @@ function LibrarySection() {
onPress={async () => {
setCleaningHls(true)
try {
await cleanupHlsStreams({})
const result = await cleanupHlsStreams({})
showSuccess(`Removed ${result.removed} idle HLS streams`)
} catch (error) {
showError(
error instanceof Error
@@ -466,7 +462,7 @@ function UsersSection({
<SettingsCard title="Sign Up">
<SwitchRow
title="Disable account creation"
subtitle="Stop people from registering themselves. Admins can still create accounts."
subtitle="Stop people from registering themselves. Admins can still create accounts from the web app."
value={appSettings?.disableAccountCreation ?? false}
onValueChange={(checked) =>
void setDisableCreation({ disabled: checked }).catch(
@@ -480,85 +476,77 @@ function UsersSection({
title="People"
subtitle="Manage who can access this server."
>
<Button
title="Create account"
onPress={() => router.push("/(app)/create-account")}
/>
<View style={styles.userList}>
{users.map((user, index) => (
<View
key={user._id}
style={[
styles.userBlock,
index > 0
? [styles.userBlockSpaced, { borderTopColor: colors.border }]
: null,
]}
>
<View style={styles.userRow}>
<ProfileAvatar user={user} size={44} />
<View style={styles.userCopy}>
<View style={styles.userNameRow}>
<Text
style={[styles.userName, { color: colors.foreground }]}
numberOfLines={1}
>
{user.name}
</Text>
{user.isAdmin ? (
<View
style={[
styles.badge,
{ backgroundColor: colors.muted },
]}
>
<Text
style={[
styles.badgeText,
{ color: colors.mutedForeground },
]}
>
Admin
</Text>
</View>
) : null}
</View>
{users.map((user, index) => (
<View key={user._id}>
{index > 0 ? (
<View
style={[styles.divider, { backgroundColor: colors.border }]}
/>
) : null}
<View style={styles.userRow}>
<ProfileAvatar user={user} size={44} />
<View style={styles.userCopy}>
<View style={styles.userNameRow}>
<Text
style={{ color: colors.mutedForeground }}
style={[styles.userName, { color: colors.foreground }]}
numberOfLines={1}
>
{user.email}
{user.name}
</Text>
{user.isAdmin ? (
<View
style={[styles.badge, { backgroundColor: colors.muted }]}
>
<Text
style={[
styles.badgeText,
{ color: colors.mutedForeground },
]}
>
Admin
</Text>
</View>
) : null}
</View>
<Text
style={{ color: colors.mutedForeground }}
numberOfLines={1}
>
{user.email}
</Text>
</View>
{user._id !== currentUserId ? (
<View style={styles.userActions}>
<Button
title={user.isAdmin ? "Remove Admin" : "Make Admin"}
variant="secondary"
onPress={() =>
void setAdmin({
userId: user._id,
isAdmin: !user.isAdmin,
}).catch((error: Error) => showError(error.message))
}
style={styles.userActionButton}
/>
<Button
title="Delete"
variant="destructive"
onPress={() =>
void deleteUserMutation({ userId: user._id }).catch(
(error: Error) => showError(error.message)
)
}
style={styles.userActionButton}
/>
</View>
) : null}
</View>
))}
</View>
{user._id !== currentUserId ? (
<View style={styles.userActions}>
<Button
title={user.isAdmin ? "Remove Admin" : "Make Admin"}
variant="secondary"
onPress={() =>
void setAdmin({
userId: user._id,
isAdmin: !user.isAdmin,
}).then(
() => showSuccess("Updated permissions"),
(error: Error) => showError(error.message)
)
}
style={styles.userActionButton}
/>
<Button
title="Delete"
variant="destructive"
onPress={() =>
void deleteUserMutation({ userId: user._id }).then(
() => showSuccess("User deleted"),
(error: Error) => showError(error.message)
)
}
style={styles.userActionButton}
/>
</View>
) : null}
</View>
))}
</SettingsCard>
</>
)
@@ -647,12 +635,10 @@ function SwitchRow({
subtitle,
value,
onValueChange,
disabled,
}: {
title: string
subtitle?: string
value: boolean
disabled?: boolean
onValueChange: (checked: boolean) => void
}) {
const colors = useThemeColors()
@@ -667,17 +653,7 @@ function SwitchRow({
<Text style={{ color: colors.mutedForeground }}>{subtitle}</Text>
) : null}
</View>
<Switch
value={value}
disabled={disabled}
onValueChange={onValueChange}
{...(Platform.OS === "android"
? {
trackColor: { false: colors.muted, true: colors.primary },
thumbColor: colors.foreground,
}
: {})}
/>
<Switch value={value} onValueChange={onValueChange} />
</View>
)
}
@@ -857,16 +833,6 @@ const styles = StyleSheet.create({
alignItems: "center",
gap: spacing.md,
},
userList: {
gap: spacing.lg,
},
userBlock: {
gap: spacing.md,
},
userBlockSpaced: {
paddingTop: spacing.lg,
borderTopWidth: StyleSheet.hairlineWidth,
},
userRow: {
flexDirection: "row",
alignItems: "center",
@@ -889,6 +855,7 @@ const styles = StyleSheet.create({
userActions: {
flexDirection: "row",
gap: spacing.sm,
marginTop: spacing.md,
},
userActionButton: {
flex: 1,
@@ -1,11 +1,10 @@
import { Stack } from "expo-router"
import { Platform } from "react-native"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
export const unstable_settings = {
anchor: "index",
initialRouteName: "index",
}
export default function LibraryLayout() {
@@ -13,25 +12,21 @@ export default function LibraryLayout() {
return (
<Stack
initialRouteName="index"
screenOptions={({ route }) => ({
...baseOptions,
...(Platform.OS === "android" &&
(route.name === "album/[id]" || route.name === "playlist/[id]")
? { animation: "none" as const }
: {}),
title: tabStackScreenTitles[route.name] ?? "Library",
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
headerRight: route.name === "settings" ? undefined : () => <ProfileHeaderButton />,
unstable_headerRightItems:
route.name === "index"
? () => [
route.name === "settings"
? undefined
: () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
],
})}
/>
)
+3 -11
View File
@@ -61,14 +61,12 @@ export default function LibraryScreen() {
{links.map((link) => (
<Pressable
key={link.href}
style={styles.row}
style={[styles.row, { borderBottomColor: colors.border }]}
onPress={() => push(link.href)}
>
<LibraryIcon name={link.icon} />
<View style={[styles.rowContent, { borderBottomColor: colors.border }]}>
<Text style={[styles.rowTitle, { color: colors.foreground }]}>{link.title}</Text>
<Ionicons name="chevron-forward" size={16} color={colors.mutedForeground} />
</View>
<Text style={[styles.rowTitle, { color: colors.foreground }]}>{link.title}</Text>
<Ionicons name="chevron-forward" size={16} color={colors.mutedForeground} />
</Pressable>
))}
@@ -113,12 +111,6 @@ const styles = StyleSheet.create({
alignItems: "center",
gap: spacing.md,
paddingHorizontal: spacing.lg,
},
rowContent: {
flex: 1,
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
paddingVertical: 14,
borderBottomWidth: StyleSheet.hairlineWidth,
},
@@ -1,11 +1,10 @@
import { Stack } from "expo-router"
import { Platform } from "react-native"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
export const unstable_settings = {
anchor: "index",
initialRouteName: "index",
}
export default function SearchLayout() {
@@ -13,25 +12,21 @@ export default function SearchLayout() {
return (
<Stack
initialRouteName="index"
screenOptions={({ route }) => ({
...baseOptions,
...(Platform.OS === "android" &&
(route.name === "album/[id]" || route.name === "playlist/[id]")
? { animation: "none" as const }
: {}),
title: tabStackScreenTitles[route.name] ?? "Search",
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
headerRight: route.name === "settings" ? undefined : () => <ProfileHeaderButton />,
unstable_headerRightItems:
route.name === "index"
? () => [
route.name === "settings"
? undefined
: () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
],
})}
/>
)
@@ -1,5 +1,3 @@
import { Platform } from "react-native"
import { useThemeColors } from "@/lib/theme"
import { Stack } from "expo-router"
import { useCallback } from "react"
@@ -7,7 +5,6 @@ import { SearchResults } from "@/components/search-results"
import { useDebouncedSearch } from "@/hooks/use-debounced-search"
export default function SearchScreen() {
const colors = useThemeColors()
const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch()
const handleChangeText = useCallback(
@@ -24,15 +21,6 @@ export default function SearchScreen() {
onChangeText={handleChangeText}
onSearchButtonPress={onSearchSubmit}
autoCapitalize="none"
{...(Platform.OS === "android"
? {
barTintColor: colors.background,
textColor: colors.foreground,
tintColor: colors.primary,
hintTextColor: colors.mutedForeground,
headerIconColor: colors.foreground,
}
: {})}
/>
<SearchResults searchQuery={searchQuery} />
+21 -46
View File
@@ -1,48 +1,31 @@
import { router, type Href } from "expo-router"
import { useServerConfig } from "@/contexts/server-config"
import {
incomingMediaLink,
subscribeIncomingMediaLink,
takeIncomingMediaLink,
} from "@/lib/incoming-media-link"
import { useConvexAuth as useLocalConvexAuth } from "@convex-dev/auth/react"
import {
useConvexAuth as useServerConvexAuth,
useConvexConnectionState,
} from "convex/react"
import { Stack } from "expo-router"
import { Redirect, Stack } from "expo-router"
import { Platform } from "react-native"
import { useEffect, useSyncExternalStore } from "react"
import { useEffect } from "react"
import { AppIntentBridge } from "@/components/app-intent-bridge"
import { ConvexAuthRecovery } from "@/components/convex-auth-recovery"
import { LoadingView } from "@/components/ui/primitives"
import { AddToPlaylistProvider } from "@/contexts/add-to-playlist"
import { useInvalidateAuthSession } from "@/contexts/convex-auth-session"
import { FavoritesProvider } from "@/contexts/favorites"
import { PlaybackProvider } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { useStackScreenOptions } from "@/lib/navigation"
import { AppNavigationSync } from "@/lib/app-navigation"
const AUTH_HANDSHAKE_TIMEOUT_MS = 15_000
export default function AppLayout() {
const { config } = useServerConfig()
const localAuth = useLocalConvexAuth()
const serverAuth = useServerConvexAuth()
const { isWebSocketConnected } = useConvexConnectionState()
const { invalidateSession } = useInvalidateAuthSession()
const stackOptions = useStackScreenOptions()
const { config } = useServerConfig()
const pendingDestination = useSyncExternalStore(
subscribeIncomingMediaLink,
() => (config ? incomingMediaLink(config.serverUrl) : null),
() => null
)
useEffect(() => {
if (!config || !pendingDestination) return
const destination = takeIncomingMediaLink(config.serverUrl)
if (destination) router.replace(destination as Href)
}, [config, pendingDestination])
useEffect(() => {
if (
@@ -67,52 +50,44 @@ export default function AppLayout() {
serverAuth?.isAuthenticated,
])
if (!config) {
return <Redirect href="/server" />
}
if (!localAuth || localAuth.isLoading) {
return <LoadingView />
}
if (!localAuth.isAuthenticated) {
return <Redirect href="/signin" />
}
// Convex holds queries until the stored token is confirmed, so the app can
// render cached data while the server handshake is still in progress.
return (
<ConvexAuthRecovery onInvalidate={invalidateSession}>
<PlaybackProvider>
<AppIntentBridge />
<AppNavigationSync />
<AddToPlaylistProvider>
<FavoritesProvider>
<Stack screenOptions={stackOptions}>
<Stack.Screen
name="(tabs)"
options={{ headerShown: false, animation: "none" }}
/>
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
<Stack.Screen
name="settings"
options={{
headerShown: Platform.OS === "android",
title: "Settings",
presentation:
Platform.OS === "ios" ? "modal" : "fullScreenModal",
headerShown: false,
presentation: Platform.OS === "ios" ? "modal" : "fullScreenModal",
animation: "slide_from_bottom",
gestureEnabled: true,
gestureDirection: "vertical",
}}
/>
<Stack.Screen
name="create-account"
options={{
title: "Create account",
presentation: "modal",
headerLargeTitle: false,
headerTransparent: false,
headerStyle: { backgroundColor: "#000" },
headerTintColor: "#fff",
contentStyle: { backgroundColor: "#000" },
}}
/>
<Stack.Screen
name="player"
options={{
headerShown: false,
// Keep the library visible behind the custom swipe animation.
presentation: "transparentModal",
contentStyle: { backgroundColor: "transparent" },
presentation: Platform.OS === "ios" ? "modal" : "fullScreenModal",
animation: "slide_from_bottom",
gestureEnabled: true,
gestureDirection: "vertical",
-199
View File
@@ -1,199 +0,0 @@
import { useAction, useQuery } from "convex/react"
import { ConvexError } from "convex/values"
import { router, Stack } from "expo-router"
import { useEffect, useRef, useState } from "react"
import {
KeyboardAvoidingView,
Platform,
ScrollView,
StyleSheet,
Switch,
Text,
View,
} from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { toast } from "sonner-native"
import { Button, Input, LoadingView } from "@/components/ui/primitives"
import { colors, spacing } from "@/lib/theme"
import { api } from "@otunes/convex/_generated/api"
export default function CreateAccountScreen() {
const user = useQuery(api.auth.currentUser)
const createUser = useAction(api.users.adminCreateUser)
const [name, setName] = useState("")
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const [isAdmin, setIsAdmin] = useState(false)
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState<string | null>(null)
const pending = useRef(false)
const mounted = useRef(true)
useEffect(() => {
mounted.current = true
return () => {
mounted.current = false
}
}, [])
async function handleCreate() {
if (pending.current || !user?.isAdmin) return
setError(null)
if (!name.trim() || !email.trim().includes("@") || password.length < 8) {
setError(
"Enter a name, valid email, and password of at least 8 characters."
)
return
}
pending.current = true
setSubmitting(true)
try {
await createUser({
name: name.trim(),
email: email.trim().toLowerCase(),
password,
isAdmin,
})
toast.success("Account created")
if (mounted.current) router.back()
} catch (error) {
if (!mounted.current) return
setError(
error instanceof ConvexError && typeof error.data === "string"
? error.data
: "Could not create account. Try again."
)
} finally {
pending.current = false
if (mounted.current) setSubmitting(false)
}
}
return (
<SafeAreaView edges={["bottom", "left", "right"]} style={styles.screen}>
<Stack.Screen
options={{
gestureEnabled: !submitting,
}}
/>
{user === undefined ? (
<LoadingView />
) : !user?.isAdmin ? (
<Text style={[styles.text, styles.message]}>
Admin access required.
</Text>
) : (
<KeyboardAvoidingView
style={styles.screen}
behavior={Platform.OS === "ios" ? "padding" : undefined}
keyboardVerticalOffset={Platform.OS === "ios" ? 100 : 0}
>
<ScrollView
contentContainerStyle={styles.form}
keyboardShouldPersistTaps="handled"
keyboardDismissMode="on-drag"
>
<View style={styles.field}>
<Text style={styles.label}>Name</Text>
<Input
accessibilityLabel="Name"
value={name}
onChangeText={setName}
autoCapitalize="words"
autoComplete="off"
editable={!submitting}
style={styles.input}
/>
</View>
<View style={styles.field}>
<Text style={styles.label}>Email</Text>
<Input
accessibilityLabel="Email"
value={email}
onChangeText={setEmail}
keyboardType="email-address"
autoCapitalize="none"
autoCorrect={false}
autoComplete="off"
editable={!submitting}
style={styles.input}
/>
</View>
<View style={styles.field}>
<Text style={styles.label}>Password</Text>
<Input
accessibilityLabel="Password"
value={password}
onChangeText={setPassword}
secureTextEntry
autoCapitalize="none"
autoCorrect={false}
autoComplete="new-password"
placeholder="At least 8 characters"
editable={!submitting}
style={styles.input}
/>
</View>
<View style={styles.row}>
<Text style={styles.text}>Grant admin access</Text>
<Switch
accessibilityLabel="Grant admin access"
trackColor={{
false: colors.dark.muted,
true: colors.dark.primary,
}}
thumbColor={colors.dark.foreground}
value={isAdmin}
onValueChange={setIsAdmin}
disabled={submitting}
/>
</View>
{error ? (
<Text accessibilityRole="alert" style={styles.error}>
{error}
</Text>
) : null}
<Button
title={submitting ? "Creating account…" : "Create account"}
disabled={submitting}
onPress={() => void handleCreate()}
tint={{
background: colors.dark.primary,
foreground: colors.dark.primaryForeground,
}}
/>
</ScrollView>
</KeyboardAvoidingView>
)}
</SafeAreaView>
)
}
const styles = StyleSheet.create({
screen: { flex: 1, backgroundColor: "#000" },
form: { padding: spacing.lg, gap: spacing.lg },
field: { gap: spacing.sm },
label: {
color: colors.dark.mutedForeground,
fontSize: 12,
fontWeight: "600",
textTransform: "uppercase",
letterSpacing: 0.6,
},
text: { color: colors.dark.foreground, fontSize: 16, flexShrink: 1 },
input: {
backgroundColor: colors.dark.muted,
color: colors.dark.foreground,
borderColor: colors.dark.border,
},
row: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
gap: spacing.md,
minHeight: 48,
},
message: { padding: spacing.lg },
error: { color: colors.dark.destructive, fontSize: 14, lineHeight: 20 },
})
+5
View File
@@ -0,0 +1,5 @@
import { Redirect } from "expo-router"
export default function AppIndex() {
return <Redirect href="/(app)/(tabs)/home" />
}
+241 -630
View File
@@ -1,82 +1,39 @@
import { dolbyAtmosSupported } from "@/lib/playback-capabilities"
import { NavigationBar } from "expo-navigation-bar"
import { MusicEntityView } from "@/components/music-entity-view"
import { Stack, useRouter } from "expo-router"
import { Ionicons } from "@expo/vector-icons"
import Slider from "@react-native-community/slider"
import { BlurView } from "expo-blur"
import { useRouter } from "expo-router"
import * as Haptics from "expo-haptics"
import { StatusBar } from "expo-status-bar"
import { useEffect, useRef, useState } from "react"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import { useEffect, useRef } from "react"
import {
Platform,
Pressable,
StyleSheet,
Text,
useWindowDimensions,
View,
} from "react-native"
import Animated, {
FadeIn,
FadeOut,
interpolate,
LayoutAnimationConfig,
useAnimatedStyle,
useSharedValue,
withSpring,
withTiming,
} from "react-native-reanimated"
import { useSafeAreaInsets } from "react-native-safe-area-context"
import { scheduleOnRN } from "react-native-worklets"
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context"
import { StatusBar } from "expo-status-bar"
import { api } from "@otunes/convex/_generated/api"
import { playbackFormat } from "@otunes/convex/playback-stream"
import { AudioFormatBadge } from "@/components/audio-format-badge"
import { AudioOutputButton } from "@/components/audio-output-button"
import { MediaActionMenu, type MediaAction } from "@/components/media-actions-sheet"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { CoverImage } from "@/components/cover-image"
import { MarqueeText } from "@/components/marquee-text"
import {
MediaActionMenu,
type MediaAction,
} from "@/components/media-actions-sheet"
import {
NowPlayingQueue,
QUEUE_HORIZONTAL_INSET,
} from "@/components/now-playing-queue"
import { PlayerSlider } from "@/components/player-slider"
import { PlayerSymbol } from "@/components/player-symbol"
import { useFavorites } from "@/contexts/favorites"
import { usePlayback } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { useCoverPalette } from "@/hooks/use-cover-palette"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { useSystemVolume } from "@/hooks/use-system-volume"
import { formatDuration, formatRemainingDuration } from "@/lib/format"
import {
nowPlayingColors,
type NowPlayingColors,
} from "@/lib/now-playing-colors"
import { useAppNavigation } from "@/lib/app-navigation"
import { albumCoverUrl } from "@/lib/urls"
import { radius, spacing } from "@/lib/theme"
import type { BrowseSong } from "@otunes/convex/types"
const HORIZONTAL_INSET = QUEUE_HORIZONTAL_INSET
const META_HEIGHT = 64
const PAUSED_ARTWORK_SCALE = 0.77
const ARTWORK_SPRING = { duration: 550, dampingRatio: 0.72 }
const BACKGROUND_FADE = { duration: 450 }
const MODE_FADE_IN = FadeIn.duration(220)
const MODE_FADE_OUT = FadeOut.duration(140)
const DISMISS_DISTANCE = 140
const DISMISS_VELOCITY = 900
const DISMISS_CORNER_RADIUS = 48
import { appleMusic, radius, spacing, usePlayerTheme } from "@/lib/theme"
export default function PlayerScreen() {
const router = useRouter()
const hadSongRef = useRef(false)
const { push } = useAppNavigation()
const insets = useSafeAreaInsets()
const { width: windowWidth, height: windowHeight } = useWindowDimensions()
const player = usePlayerTheme()
const { config } = useServerConfig()
const { isSongFavorite, toggleSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions()
const {
currentSong,
isPlaying,
@@ -84,99 +41,16 @@ export default function PlayerScreen() {
repeatEnabled,
currentTime,
duration,
volume,
queueSongIds,
setIsPlaying,
setVolume,
seekTo,
toggleShuffle,
cycleRepeat,
skipNext,
skipPrevious,
} = usePlayback()
const { volume, setVolume, available: volumeAvailable } = useSystemVolume()
const [showQueue, setShowQueue] = useState(false)
const [isDismissing, setIsDismissing] = useState(false)
const [stageHeight, setStageHeight] = useState(0)
const [scrubTime, setScrubTime] = useState<number | null>(null)
const user = useCachedQuery(api.auth.currentUser)
const playbackInfo = useCachedQuery(
api.library.getSongPlaybackInfo,
currentSong ? { id: currentSong.id } : "skip"
)
const format =
user && playbackInfo
? playbackFormat(
playbackInfo.files,
user.playbackQuality,
dolbyAtmosSupported && (user.preferAtmos ?? false)
)
: null
const coverUri =
currentSong && config
? albumCoverUrl(config.serverUrl, currentSong.album.id)
: ""
const { palette } = useCoverPalette(
coverUri,
currentSong ? currentSong.album.cover != null : undefined
)
const colors = nowPlayingColors(palette)
const background = useSharedValue(colors.background)
useEffect(() => {
background.value = withTiming(colors.background, BACKGROUND_FADE)
}, [background, colors.background])
const backgroundStyle = useAnimatedStyle(() => ({
backgroundColor: background.value,
}))
const artworkScale = useSharedValue(isPlaying ? 1 : PAUSED_ARTWORK_SCALE)
useEffect(() => {
artworkScale.value = withSpring(
isPlaying ? 1 : PAUSED_ARTWORK_SCALE,
ARTWORK_SPRING
)
}, [artworkScale, isPlaying])
const artworkStyle = useAnimatedStyle(() => ({
transform: [{ scale: artworkScale.value }],
shadowOpacity: interpolate(
artworkScale.value,
[PAUSED_ARTWORK_SCALE, 1],
[0.18, 0.4]
),
}))
const dismissY = useSharedValue(0)
const dismissStyle = useAnimatedStyle(() => ({
transform: [{ translateY: dismissY.value }],
borderRadius: dismissY.value > 0 ? DISMISS_CORNER_RADIUS : 0,
}))
// The player covers the status bar, so it can't use the native sheet's
// swipe to dismiss.
function dismissGesture() {
return Gesture.Pan()
.activeOffsetY(12)
.failOffsetY(-12)
.failOffsetX([-20, 20])
.onUpdate((event) => {
dismissY.value = Math.max(0, event.translationY)
})
.onEnd((event) => {
if (
event.translationY > DISMISS_DISTANCE ||
event.velocityY > DISMISS_VELOCITY
) {
scheduleOnRN(setIsDismissing, true)
dismissY.value = withTiming(
windowHeight,
{ duration: 220 },
(finished) => {
if (finished) scheduleOnRN(router.back)
}
)
} else {
dismissY.value = withSpring(0, { duration: 350, dampingRatio: 0.85 })
}
})
}
const hasQueue = queueSongIds.length > 0
@@ -196,576 +70,313 @@ export default function PlayerScreen() {
}
const hasCover = currentSong.album.cover != null
const bottomInset = Math.max(insets.bottom, spacing.md)
const artworkSize = Math.max(
0,
Math.min(
windowWidth - HORIZONTAL_INSET * 2,
stageHeight > 0 ? stageHeight - META_HEIGHT - spacing.xl : Infinity
)
)
const displayedTime = scrubTime ?? currentTime
const timeColor =
scrubTime === null ? colors.secondaryForeground : colors.foreground
const coverUri = albumCoverUrl(config.serverUrl, currentSong.album.id)
const favorited = isSongFavorite(currentSong.id)
const bottomInset = Math.max(insets.bottom, spacing.md) + spacing.lg
const { colors } = player
async function handleAction(action: MediaAction) {
if (!currentSong) return
await handleSongAction(currentSong, action)
}
function togglePlayback() {
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light)
setIsPlaying(!isPlaying)
}
function toggleQueue() {
void Haptics.selectionAsync()
setShowQueue((value) => !value)
}
return (
<Animated.View style={[styles.root, backgroundStyle, dismissStyle]}>
<StatusBar style={colors.isDark ? "light" : "dark"} />
{Platform.OS === "android" ? (
<View style={[styles.root, { backgroundColor: colors.background }]}>
<StatusBar style={player.statusBar} />
<CoverImage
uri={coverUri}
hasCover={hasCover}
style={[styles.backgroundImage, { opacity: player.backgroundImageOpacity }]}
contentFit="cover"
blurRadius={60}
placeholderVariant="solid"
/>
{Platform.OS === "ios" ? (
<>
<Stack.Screen
options={{
statusBarStyle: colors.isDark ? "light" : "dark",
// The swipe already animates the player offscreen.
animation: isDismissing ? "none" : "slide_from_bottom",
}}
/>
<NavigationBar style={colors.isDark ? "light" : "dark"} />
<BlurView intensity={90} tint={player.blurTint} style={StyleSheet.absoluteFill} />
<View style={[styles.scrim, { backgroundColor: player.scrim }]} />
</>
) : null}
) : (
<View style={[StyleSheet.absoluteFill, { backgroundColor: player.androidScrim }]} />
)}
<MusicEntityView
kind="song"
id={currentSong.id}
style={[styles.safe, { paddingTop: insets.top }]}
>
<GestureDetector gesture={dismissGesture()}>
<Pressable
onPress={() => router.back()}
hitSlop={12}
style={styles.handleRow}
accessibilityRole="button"
accessibilityLabel="Close player"
>
<View
style={[styles.handle, { backgroundColor: colors.sliderTrack }]}
/>
</Pressable>
</GestureDetector>
<SafeAreaView style={styles.safe} edges={["top"]}>
<Pressable
onPress={() => router.back()}
hitSlop={12}
style={styles.handleRow}
accessibilityRole="button"
accessibilityLabel="Close player"
>
<View style={[styles.handle, { backgroundColor: player.handle }]} />
</Pressable>
<GestureDetector gesture={dismissGesture().enabled(!showQueue)}>
<View
style={styles.stage}
onLayout={(event) =>
setStageHeight(event.nativeEvent.layout.height)
}
>
<LayoutAnimationConfig skipEntering>
{showQueue ? (
stageHeight > 0 ? (
<Animated.View
key="queue"
entering={MODE_FADE_IN}
exiting={MODE_FADE_OUT}
style={styles.fill}
>
<NowPlayingQueue
colors={colors}
viewportHeight={stageHeight}
currentHeader={
<View style={styles.queueHeader}>
<CoverImage
uri={coverUri}
hasCover={hasCover}
style={styles.queueArtwork}
/>
<SongMeta
song={currentSong}
colors={colors}
compact
/>
</View>
}
/>
</Animated.View>
) : null
) : (
<Animated.View
key="artwork"
entering={MODE_FADE_IN}
exiting={MODE_FADE_OUT}
style={[styles.fill, styles.artworkMode]}
>
<View style={styles.artworkArea}>
<Animated.View style={[styles.artworkShadow, artworkStyle]}>
<CoverImage
uri={coverUri}
hasCover={hasCover}
style={{
width: artworkSize,
height: artworkSize,
borderRadius: radius.md,
}}
/>
</Animated.View>
</View>
<View style={styles.meta}>
<SongMeta song={currentSong} colors={colors} />
</View>
</Animated.View>
)}
</LayoutAnimationConfig>
<View style={styles.upper}>
<View style={styles.artworkWrap}>
<CoverImage uri={coverUri} hasCover={hasCover} style={styles.artwork} />
</View>
</GestureDetector>
</View>
<GestureDetector gesture={dismissGesture()}>
<View style={[styles.controls, { paddingBottom: bottomInset }]}>
<PlayerSlider
accessibilityLabel="Playback position"
value={displayedTime}
maximumValue={duration}
fillColor={colors.sliderFill}
activeFillColor={colors.foreground}
trackColor={colors.sliderTrack}
onValueChange={setScrubTime}
onSlidingComplete={(value) => {
void seekTo(value)
setScrubTime(null)
}}
<View style={[styles.controls, { paddingBottom: bottomInset }]}>
<View style={styles.metaRow}>
<View style={styles.metaText}>
<Text style={[styles.songTitle, { color: colors.foreground }]} numberOfLines={2}>
{currentSong.title}
</Text>
<Text style={[styles.artistName, { color: colors.mutedForeground }]} numberOfLines={1}>
{currentSong.artist.name}
</Text>
</View>
<View style={styles.metaActions}>
<Pressable
onPress={() => void toggleSongFavorite(currentSong.id)}
hitSlop={10}
style={[styles.circleButton, { backgroundColor: player.buttonSurface }]}
>
<Ionicons
name={favorited ? "star" : "star-outline"}
size={20}
color={favorited ? appleMusic.pink : colors.foreground}
/>
</Pressable>
<MediaActionMenu
favorited={favorited}
navigation={{
artist: { id: currentSong.artist.id },
album: { id: currentSong.album.id },
}}
includeActions={[
"play-next",
"play-last",
"shuffle",
"favorite",
"go-artist",
"go-album",
]}
onAction={handleAction}
>
<Pressable
hitSlop={10}
style={[styles.circleButton, { backgroundColor: player.buttonSurface }]}
>
<Ionicons name="ellipsis-horizontal" size={20} color={colors.foreground} />
</Pressable>
</MediaActionMenu>
</View>
</View>
<View style={styles.progressSection}>
<Slider
style={styles.slider}
minimumValue={0}
maximumValue={duration > 0 ? duration : 1}
value={Math.min(currentTime, duration || 0)}
onSlidingComplete={(value) => void seekTo(value)}
minimumTrackTintColor={colors.foreground}
maximumTrackTintColor={player.trackInactive}
thumbTintColor={colors.foreground}
/>
<View style={styles.timeRow}>
<Text style={[styles.time, { color: timeColor }]}>
{formatDuration(displayedTime)}
<Text style={[styles.time, { color: colors.mutedForeground }]}>
{formatDuration(currentTime)}
</Text>
{format ? (
<View style={styles.format} pointerEvents="none">
<AudioFormatBadge
format={format}
color={colors.secondaryForeground}
backgroundColor={colors.background}
/>
</View>
) : null}
<Text style={[styles.time, { color: timeColor }]}>
{formatRemainingDuration(displayedTime, duration).replace(
"-",
"\u2212"
)}
<Text style={[styles.time, { color: colors.mutedForeground }]}>
{formatRemainingDuration(currentTime, duration)}
</Text>
</View>
<View style={styles.transport}>
<TransportButton
colors={colors}
accessibilityLabel="Previous"
onPress={() => void skipPrevious()}
>
<PlayerSymbol
name="backward.fill"
fallback="play-back"
size={34}
color={colors.foreground}
/>
</TransportButton>
<TransportButton
colors={colors}
accessibilityLabel={isPlaying ? "Pause" : "Play"}
onPress={togglePlayback}
large
>
<PlayerSymbol
name={isPlaying ? "pause.fill" : "play.fill"}
fallback={isPlaying ? "pause" : "play"}
size={44}
color={colors.foreground}
/>
</TransportButton>
<TransportButton
colors={colors}
accessibilityLabel="Next"
onPress={() => void skipNext()}
>
<PlayerSymbol
name="forward.fill"
fallback="play-forward"
size={34}
color={colors.foreground}
/>
</TransportButton>
</View>
{volumeAvailable ? (
<PlayerSlider
accessibilityLabel="Volume"
commitHoldMs={0}
animateValueChanges
value={volume}
maximumValue={1}
fillColor={colors.sliderFill}
activeFillColor={colors.foreground}
trackColor={colors.sliderTrack}
onValueChange={setVolume}
leading={
<PlayerSymbol
name="speaker.fill"
fallback="volume-low"
size={14}
color={colors.secondaryForeground}
/>
}
trailing={
<PlayerSymbol
name="speaker.wave.3.fill"
fallback="volume-high"
size={14}
color={colors.secondaryForeground}
/>
}
/>
) : null}
<View style={styles.footer}>
<Pressable
disabled
accessibilityRole="button"
accessibilityLabel="Lyrics"
accessibilityState={{ disabled: true }}
style={[styles.queueButton, styles.unavailable]}
>
<PlayerSymbol
name="quote.bubble"
fallback={{ material: "lyrics" }}
size={27}
weight="semibold"
color={colors.foreground}
/>
</Pressable>
<AudioOutputButton
color={colors.foreground}
style={styles.queueButton}
/>
<Pressable
onPress={toggleQueue}
hitSlop={8}
accessibilityRole="button"
accessibilityLabel={showQueue ? "Hide queue" : "Show queue"}
accessibilityState={{ selected: showQueue }}
style={[
styles.queueButton,
showQueue && { backgroundColor: colors.selected },
]}
>
<PlayerSymbol
name="list.bullet"
fallback="list"
size={25}
weight="semibold"
color={
showQueue ? colors.selectedForeground : colors.foreground
}
/>
{!showQueue && (shuffleEnabled || repeatEnabled !== "none") ? (
<View
style={[styles.badge, { backgroundColor: colors.control }]}
>
<PlayerSymbol
name={
shuffleEnabled
? "shuffle"
: repeatEnabled === "once"
? "repeat.1"
: "repeat"
}
fallback={shuffleEnabled ? "shuffle" : "repeat"}
size={14}
weight="bold"
color={colors.foreground}
/>
</View>
) : null}
</Pressable>
</View>
</View>
</GestureDetector>
</MusicEntityView>
</Animated.View>
)
}
/** Title and artist with the favorite and more buttons. */
function SongMeta({
song,
colors,
compact = false,
}: {
song: BrowseSong
colors: NowPlayingColors
compact?: boolean
}) {
const { isSongFavorite, toggleSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions()
const favorited = isSongFavorite(song.id)
<View style={styles.transport}>
<Pressable onPress={() => void skipPrevious()} hitSlop={12}>
<Ionicons name="play-back" size={36} color={colors.foreground} />
</Pressable>
<Pressable onPress={togglePlayback} style={styles.playButton} hitSlop={12}>
<Ionicons
name={isPlaying ? "pause" : "play"}
size={52}
color={colors.foreground}
/>
</Pressable>
<Pressable onPress={() => void skipNext()} hitSlop={12}>
<Ionicons name="play-forward" size={36} color={colors.foreground} />
</Pressable>
</View>
async function handleAction(action: MediaAction) {
await handleSongAction(song, action)
}
<View style={styles.volumeSection}>
<Ionicons name="volume-low" size={18} color={colors.mutedForeground} />
<Slider
style={styles.volumeSlider}
minimumValue={0}
maximumValue={1}
value={volume}
onValueChange={setVolume}
minimumTrackTintColor={colors.foreground}
maximumTrackTintColor={player.trackInactive}
thumbTintColor={colors.foreground}
/>
<Ionicons name="volume-high" size={18} color={colors.mutedForeground} />
</View>
return (
<View style={styles.metaRow}>
<View style={styles.metaText}>
<MarqueeText
text={song.title}
style={[
compact ? styles.compactTitle : styles.title,
{ color: colors.foreground },
]}
/>
<MarqueeText
text={song.artist.name}
style={[
compact ? styles.compactArtist : styles.artist,
{ color: colors.secondaryForeground },
]}
/>
</View>
<Pressable
onPress={() => void toggleSongFavorite(song.id)}
hitSlop={10}
style={styles.metaButton}
accessibilityRole="button"
accessibilityLabel={favorited ? "Unfavorite" : "Favorite"}
>
<PlayerSymbol
name={favorited ? "star.fill" : "star"}
fallback={favorited ? "star" : "star-outline"}
size={22}
color={colors.foreground}
/>
</Pressable>
<MediaActionMenu
stationArtistId={song.artist.id}
favorited={favorited}
navigation={{
artist: { id: song.artist.id },
album: { id: song.album.id },
}}
includeActions={[
"play-next",
"play-last",
"shuffle",
"create-station",
"favorite",
"go-artist",
"go-album",
]}
onAction={handleAction}
style={styles.menu}
>
<Pressable
hitSlop={10}
style={styles.metaButton}
accessibilityRole="button"
accessibilityLabel="More"
>
<PlayerSymbol
name="ellipsis"
fallback="ellipsis-horizontal"
size={20}
weight="semibold"
color={colors.foreground}
/>
</Pressable>
</MediaActionMenu>
<View style={styles.footer}>
<Pressable onPress={() => void toggleShuffle()} hitSlop={12} style={styles.footerButton}>
<Ionicons
name="shuffle"
size={22}
color={shuffleEnabled ? appleMusic.pink : colors.mutedForeground}
/>
</Pressable>
<Pressable onPress={() => void cycleRepeat()} hitSlop={12} style={styles.footerButton}>
<Ionicons
name={repeatEnabled === "once" ? "repeat-outline" : "repeat"}
size={22}
color={repeatEnabled !== "none" ? appleMusic.pink : colors.mutedForeground}
/>
</Pressable>
<Pressable
onPress={() => push("/queue")}
hitSlop={12}
style={styles.footerButton}
disabled={queueSongIds.length === 0}
>
<Ionicons name="list" size={22} color={colors.mutedForeground} />
</Pressable>
</View>
</View>
</SafeAreaView>
</View>
)
}
function TransportButton({
colors,
large = false,
accessibilityLabel,
onPress,
children,
}: {
colors: NowPlayingColors
large?: boolean
accessibilityLabel: string
onPress: () => void
children: React.ReactNode
}) {
return (
<Pressable
onPress={onPress}
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
style={({ pressed }) => [
large ? styles.playButton : styles.skipButton,
pressed && {
backgroundColor: colors.controlPressed,
transform: [{ scale: 0.9 }],
},
]}
>
{children}
</Pressable>
)
}
const styles = StyleSheet.create({
root: {
flex: 1,
overflow: "hidden",
},
backgroundImage: {
...StyleSheet.absoluteFill,
},
scrim: {
...StyleSheet.absoluteFill,
},
safe: {
flex: 1,
},
fill: {
flex: 1,
paddingHorizontal: spacing.xl,
},
handleRow: {
alignItems: "center",
paddingTop: spacing.sm,
paddingBottom: spacing.sm,
paddingBottom: spacing.md,
},
handle: {
width: 36,
height: 5,
borderRadius: radius.full,
},
stage: {
upper: {
flex: 1,
minHeight: 0,
},
artworkMode: {
paddingHorizontal: HORIZONTAL_INSET,
},
artworkArea: {
flex: 1,
alignItems: "center",
justifyContent: "center",
},
artworkShadow: {
borderRadius: radius.md,
artworkWrap: {
alignItems: "center",
justifyContent: "center",
paddingVertical: spacing.sm,
},
artwork: {
width: "100%",
maxWidth: 320,
aspectRatio: 1,
borderRadius: 12,
shadowColor: "#000",
shadowOpacity: 0.45,
shadowRadius: 24,
shadowOffset: { width: 0, height: 14 },
shadowOffset: { width: 0, height: 12 },
},
meta: {
height: META_HEIGHT,
justifyContent: "center",
},
queueHeader: {
flexDirection: "row",
alignItems: "center",
gap: 14,
},
queueArtwork: {
width: 64,
height: 64,
borderRadius: 8,
controls: {
flexShrink: 0,
},
metaRow: {
flex: 1,
flexDirection: "row",
alignItems: "center",
alignItems: "flex-start",
gap: spacing.md,
marginBottom: spacing.md,
},
metaText: {
flex: 1,
minWidth: 0,
},
title: {
fontSize: 20,
fontWeight: "600",
songTitle: {
fontSize: 22,
fontWeight: "700",
lineHeight: 28,
},
artist: {
fontSize: 20,
marginTop: 1,
artistName: {
fontSize: 18,
marginTop: spacing.xs,
},
compactTitle: {
fontSize: 17,
fontWeight: "600",
metaActions: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
paddingTop: 4,
},
compactArtist: {
fontSize: 15,
marginTop: 1,
},
menu: {
alignSelf: "center",
},
metaButton: {
width: 30,
height: 30,
borderRadius: 15,
circleButton: {
width: 34,
height: 34,
borderRadius: 17,
alignItems: "center",
justifyContent: "center",
},
controls: {
flexShrink: 0,
paddingHorizontal: HORIZONTAL_INSET,
paddingTop: spacing.md,
progressSection: {
marginBottom: spacing.lg,
},
slider: {
width: "100%",
height: 28,
},
timeRow: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
marginTop: -4,
},
format: {
position: "absolute",
left: 0,
right: 0,
alignItems: "center",
},
time: {
fontSize: 12,
fontWeight: "600",
fontSize: 13,
fontVariant: ["tabular-nums"],
},
transport: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: 28,
marginVertical: spacing.xl,
},
skipButton: {
width: 72,
height: 72,
borderRadius: 36,
alignItems: "center",
justifyContent: "center",
gap: 48,
marginBottom: spacing.lg,
},
playButton: {
width: 84,
height: 84,
borderRadius: 42,
width: 72,
alignItems: "center",
justifyContent: "center",
},
volumeSection: {
flexDirection: "row",
alignItems: "center",
gap: spacing.sm,
marginBottom: spacing.md,
},
volumeSlider: {
flex: 1,
height: 28,
},
footer: {
flexDirection: "row",
justifyContent: "space-between",
paddingTop: spacing.md,
paddingHorizontal: 40,
paddingHorizontal: spacing.xxl,
paddingTop: spacing.sm,
},
unavailable: {
opacity: 0.35,
},
queueButton: {
width: 38,
height: 38,
borderRadius: 19,
alignItems: "center",
justifyContent: "center",
},
badge: {
position: "absolute",
top: -10,
right: -11,
width: 21,
height: 21,
borderRadius: 10.5,
footerButton: {
minWidth: 44,
minHeight: 44,
alignItems: "center",
justifyContent: "center",
},
+1 -16
View File
@@ -1,16 +1 @@
import { Platform } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import SettingsScreen from "./(tabs)/home/settings"
export default function Settings() {
if (Platform.OS !== "android") return <SettingsScreen />
return (
<SafeAreaView
edges={["bottom", "left", "right"]}
style={{ flex: 1, backgroundColor: "#000" }}
>
<SettingsScreen />
</SafeAreaView>
)
}
export { default } from "./(tabs)/home/settings"
+23 -2
View File
@@ -1,7 +1,28 @@
import { Stack } from "expo-router"
import { useConvexAuth } from "@convex-dev/auth/react"
import { Redirect, Stack } from "expo-router"
export const unstable_settings = { anchor: "signin" }
import { LoadingView } from "@/components/ui/primitives"
import { useServerConfig } from "@/contexts/server-config"
export default function AuthLayout() {
const { config, isLoading: serverLoading } = useServerConfig()
const auth = useConvexAuth()
if (serverLoading) {
return <LoadingView />
}
if (!config) {
return <Redirect href="/server" />
}
if (!auth || auth.isLoading) {
return <LoadingView />
}
if (auth.isAuthenticated) {
return <Redirect href="/(app)/(tabs)/home" />
}
return <Stack screenOptions={{ headerShown: false }} />
}
-54
View File
@@ -1,54 +0,0 @@
import { loadServerConfig, parseServerHostname } from "@/lib/server-config"
import { secureGetItem } from "@/lib/auth-storage"
import { rememberIncomingMediaLink } from "@/lib/incoming-media-link"
import { showError } from "@/lib/toast"
export async function redirectSystemPath({
path,
}: {
path: string
initial: boolean
}) {
try {
const link = new URL(path, "otunes:///")
if (
!["otunes:", "otunes-development:", "otunes-preview:"].includes(
link.protocol
) ||
link.hostname !== "open"
) {
return path
}
const target = new URL(link.searchParams.get("url") ?? "")
const server = parseServerHostname(target.host)
if (
!server ||
!["https:", "http:"].includes(target.protocol) ||
target.username ||
target.password ||
new URL(server.serverUrl).origin !== target.origin ||
!/^\/(album|artist|playlist)\/[a-zA-Z0-9_-]+$/.test(target.pathname)
) {
return "/"
}
const config = await loadServerConfig(secureGetItem)
if (config && new URL(config.serverUrl).origin !== target.origin) {
showError("This link belongs to a different oTunes server")
return "/"
}
const query = new URLSearchParams()
const songId = target.searchParams.get("s")
if (target.pathname.startsWith("/album/") && songId) query.set("s", songId)
const suffix = query.size ? `?${query}` : ""
const destination = `/(app)/(tabs)/home${target.pathname}${suffix}`
rememberIncomingMediaLink(destination, target.origin)
return config
? destination
: `/server?hostname=${encodeURIComponent(server.hostname)}`
} catch {
return "/"
}
}
+12 -47
View File
@@ -1,63 +1,28 @@
import { useConvexAuth } from "@convex-dev/auth/react"
import { DarkTheme, Stack, ThemeProvider } from "expo-router"
import { Stack } from "expo-router"
import { StatusBar } from "expo-status-bar"
import { useIsDark } from "@/lib/theme"
import { useColorScheme } from "react-native"
import { GestureHandlerRootView } from "react-native-gesture-handler"
import { SafeAreaProvider } from "react-native-safe-area-context"
import { Toaster } from "@/components/ui/toaster"
import { ConvexAppProvider } from "@/contexts/convex-app"
import { ServerConfigProvider, useServerConfig } from "@/contexts/server-config"
const navigationTheme = {
...DarkTheme,
colors: { ...DarkTheme.colors, background: "#000", card: "#000" },
}
function RootNavigator() {
const { config, isLoading } = useServerConfig()
const auth = useConvexAuth()
if (isLoading || (config && (!auth || auth.isLoading))) {
return null
}
const isAuthenticated = Boolean(config && auth?.isAuthenticated)
return (
<Stack
screenOptions={{
headerShown: false,
animation: "none",
contentStyle: { backgroundColor: "#000" },
}}
>
<Stack.Screen name="index" />
<Stack.Protected guard={isAuthenticated}>
<Stack.Screen name="(app)" />
</Stack.Protected>
<Stack.Protected guard={Boolean(config) && !isAuthenticated}>
<Stack.Screen name="(auth)" />
</Stack.Protected>
<Stack.Protected guard={!config}>
<Stack.Screen name="server" />
</Stack.Protected>
</Stack>
)
}
import { ServerConfigProvider } from "@/contexts/server-config"
export default function RootLayout() {
const isDark = useIsDark()
const colorScheme = useColorScheme()
return (
<GestureHandlerRootView style={{ flex: 1, backgroundColor: "#000" }}>
<GestureHandlerRootView style={{ flex: 1 }}>
<SafeAreaProvider>
<ServerConfigProvider>
<ConvexAppProvider>
<StatusBar style={isDark ? "light" : "dark"} />
<ThemeProvider value={navigationTheme}>
<RootNavigator />
</ThemeProvider>
<StatusBar style={colorScheme === "dark" ? "light" : "dark"} />
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen name="index" />
<Stack.Screen name="server" />
<Stack.Screen name="(auth)" />
<Stack.Screen name="(app)" />
</Stack>
<Toaster />
</ConvexAppProvider>
</ServerConfigProvider>
+9 -17
View File
@@ -1,27 +1,19 @@
import { useConvexAuth } from "@convex-dev/auth/react"
import { incomingMediaLink } from "@/lib/incoming-media-link"
import { Redirect, type Href } from "expo-router"
import { Redirect } from "expo-router"
import { LoadingView } from "@/components/ui/primitives"
import { useServerConfig } from "@/contexts/server-config"
import { AuthenticatedRedirect } from "@/components/authenticated-redirect"
export default function Index() {
const { config } = useServerConfig()
const auth = useConvexAuth()
const { config, isLoading } = useServerConfig()
if (isLoading) {
return <LoadingView />
}
if (!config) {
return <Redirect href="/server" />
}
const destination = auth?.isAuthenticated
? incomingMediaLink(config.serverUrl)
: null
return (
<Redirect
href={
(destination as Href) ??
(auth?.isAuthenticated ? "/(app)/(tabs)/library" : "/signin")
}
/>
)
return <AuthenticatedRedirect />
}
+27 -15
View File
@@ -1,28 +1,32 @@
import { useLocalSearchParams } from "expo-router"
import { useRouter } from "expo-router"
import { useEffect, useState } from "react"
import { StyleSheet, Text, View } from "react-native"
import {
KeyboardAvoidingView,
Platform,
StyleSheet,
Text,
View,
} from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { KeyboardForm } from "@/components/keyboard-form"
import { Button, Card, Input } from "@/components/ui/primitives"
import { useServerConfig } from "@/contexts/server-config"
import { spacing, useThemeColors } from "@/lib/theme"
export default function ServerScreen() {
const router = useRouter()
const colors = useThemeColors()
const { setServerHostname } = useServerConfig()
const { hostname: linkedHostname } = useLocalSearchParams<{
hostname?: string
}>()
const [hostname, setHostname] = useState(linkedHostname ?? "")
useEffect(() => {
if (linkedHostname) setHostname(linkedHostname)
}, [linkedHostname])
const { config, isLoading, setServerHostname } = useServerConfig()
const [hostname, setHostname] = useState("")
const [error, setError] = useState<string | null>(null)
const [submitting, setSubmitting] = useState(false)
useEffect(() => {
if (config?.hostname) {
setHostname(config.hostname)
}
}, [config?.hostname])
async function handleContinue() {
setError(null)
setSubmitting(true)
@@ -34,6 +38,7 @@ export default function ServerScreen() {
)
return
}
router.replace("/signin")
} catch {
setError(
"Could not save the server address. Check device storage and try again."
@@ -43,9 +48,16 @@ export default function ServerScreen() {
}
}
if (isLoading) {
return null
}
return (
<SafeAreaView style={[styles.safe, { backgroundColor: colors.background }]}>
<KeyboardForm style={styles.container}>
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : undefined}
style={styles.container}
>
<View style={styles.hero}>
<Text style={[styles.brand, { color: colors.foreground }]}>
oTunes
@@ -83,7 +95,7 @@ export default function ServerScreen() {
onPress={() => void handleContinue()}
/>
</Card>
</KeyboardForm>
</KeyboardAvoidingView>
</SafeAreaView>
)
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 KiB

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 324 KiB

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 310 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 286 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 284 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 324 KiB

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 284 KiB

After

Width:  |  Height:  |  Size: 963 KiB

+1 -1
View File
@@ -26,7 +26,7 @@
"image-name" : "music.note.png",
"name" : "music.note",
"position" : {
"scale" : 1.5,
"scale" : 1,
"translation-in-points" : [
0,
0
Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.8 KiB

@@ -1,53 +0,0 @@
{
"fill" : {
"linear-gradient" : [
"display-p3:0.00000,0.55106,0.91748,1.00000",
"display-p3:0.00320,0.24546,0.91602,1.00000"
]
},
"groups" : [
{
"layers" : [
{
"fill-specializations" : [
{
"value" : "automatic"
},
{
"appearance" : "dark",
"value" : {
"linear-gradient" : [
"display-p3:0.00000,0.55106,0.91748,1.00000",
"display-p3:0.00320,0.24546,0.91602,1.00000"
]
}
}
],
"image-name" : "music.note.png",
"name" : "music.note",
"position" : {
"scale" : 1.5,
"translation-in-points" : [
0,
0
]
}
}
],
"shadow" : {
"kind" : "neutral",
"opacity" : 0.6
},
"translucency" : {
"enabled" : false,
"value" : 0.2
}
}
],
"supported-platforms" : {
"circles" : [
"watchOS"
],
"squares" : "shared"
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.8 KiB

@@ -1,53 +0,0 @@
{
"fill" : {
"linear-gradient" : [
"display-p3:0.03297,0.65562,0.91748,1.00000",
"display-p3:0.01787,0.85470,0.91602,1.00000"
]
},
"groups" : [
{
"layers" : [
{
"fill-specializations" : [
{
"value" : "automatic"
},
{
"appearance" : "dark",
"value" : {
"linear-gradient" : [
"display-p3:0.03297,0.65562,0.91748,1.00000",
"display-p3:0.01787,0.85470,0.91602,1.00000"
]
}
}
],
"image-name" : "music.note.png",
"name" : "music.note",
"position" : {
"scale" : 1.5,
"translation-in-points" : [
0,
0
]
}
}
],
"shadow" : {
"kind" : "neutral",
"opacity" : 0.6
},
"translucency" : {
"enabled" : false,
"value" : 0.2
}
}
],
"supported-platforms" : {
"circles" : [
"watchOS"
],
"squares" : "shared"
}
}
+1
View File
@@ -2,5 +2,6 @@ module.exports = function (api) {
api.cache(true)
return {
presets: ["babel-preset-expo"],
plugins: ["react-native-reanimated/plugin"],
}
}
-15
View File
@@ -1,15 +0,0 @@
import type { PropsWithChildren } from "react"
import { KeyboardAvoidingView, Platform } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
/** RN modals have their own window; protect their actions from navigation and IME. */
export function AndroidSheet({ children }: PropsWithChildren) {
if (Platform.OS !== "android") return children
return (
<KeyboardAvoidingView behavior="height" style={{ flex: 1 }}>
<SafeAreaView edges={["bottom", "left", "right"]} style={{ flex: 1 }}>
{children}
</SafeAreaView>
</KeyboardAvoidingView>
)
}
@@ -1,822 +0,0 @@
import { useConvex, useQuery } from "convex/react"
import * as AppIntents from "expo-app-intents"
import type { AppIntentEntity, AppIntentInvocation } from "expo-app-intents"
import { useEffect, useMemo, useRef, useSyncExternalStore } from "react"
import { AppState } from "react-native"
import {
completeMusicInvocation,
publishMusicCatalog,
trackMusicCatalogSync,
} from "@/lib/app-intents"
import { useAppNavigation } from "@/lib/app-navigation"
import {
ANONYMOUS_CACHE_SCOPE,
useCacheScope,
} from "@/contexts/persistent-cache"
import { usePlayback } from "@/contexts/playback"
import {
FAVORITES_PLAYLIST_ID,
loadHandledIntentIds,
rememberHandledIntentId,
} from "@/lib/app-intent-handled"
import { showError } from "@/lib/toast"
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
import { getPlaybackStore } from "@otunes/convex/client/playback-store"
import type { RepeatMode } from "@otunes/convex/client/playback-queue"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
const warmedAudioIds = new Set<string>()
class IntentRejected extends Error {}
const KNOWN_INTENTS = new Set([
"playMusic",
"warmupAudio",
"addToPlaylist",
"addToUpNext",
"clearUpNext",
"createPlaylist",
"createStation",
"updateAffinity",
"transport",
"openMusic",
])
type MusicSource = {
kind: string
id: string
}
function readString(value: unknown) {
return typeof value === "string" && value.trim() ? value : null
}
function readSources(value: unknown): MusicSource[] {
if (!Array.isArray(value)) {
return []
}
return value.flatMap((entry) => {
if (!entry || typeof entry !== "object") {
return []
}
const source = entry as { kind?: unknown; id?: unknown }
if (typeof source.kind !== "string" || typeof source.id !== "string") {
return []
}
if (!source.kind || !source.id) {
return []
}
return [{ kind: source.kind, id: source.id }]
})
}
function shuffleChoice(value: unknown, fallback: boolean) {
if (value === "songs") return true
if (value === "off") return false
if (value == null) return fallback
throw new IntentRejected("Shuffle must be Off or Songs.")
}
function repeatChoice(value: unknown): RepeatMode | null {
if (value == null) return null
if (value === "none") return "none"
if (value === "one") return "once"
if (value === "all") return "always"
throw new IntentRejected("Repeat must be None, One, or All.")
}
function ensureActive(invocation: AppIntentInvocation) {
const deadline = invocation.params.deadline
if (typeof deadline === "number" && Date.now() >= deadline) {
throw new IntentRejected("This request expired. Please try again.")
}
}
function isTransient(error: unknown) {
const message = (
error instanceof Error ? error.message : String(error)
).toLowerCase()
return (
message.includes("not authenticated") ||
message.includes("network") ||
message.includes("fetch") ||
message.includes("connection") ||
message.includes("timed out") ||
message.includes("timeout")
)
}
function songEntity(song: {
id: string
title: string
artistName: string
artistId: string
albumTitle: string
albumId: string
durationSeconds: number
genres?: string
year?: number
track?: number
diskNumber?: number | null
favorite?: boolean
}): AppIntentEntity {
return {
id: song.id,
title: song.title,
subtitle: song.artistName,
synonyms: song.artistName ? [song.artistName] : undefined,
metadata: {
artistName: song.artistName,
artistId: song.artistId,
albumTitle: song.albumTitle,
albumId: song.albumId,
duration: String(song.durationSeconds),
genres: song.genres ?? "",
year: song.year == null ? "" : String(song.year),
track: song.track == null ? "" : String(song.track),
disk: song.diskNumber == null ? "" : String(song.diskNumber),
favorite: song.favorite ? "1" : "0",
},
}
}
export function AppIntentBridge() {
const scope = useCacheScope()
const store = useMemo(
() => getPlaybackStore(scope === ANONYMOUS_CACHE_SCOPE ? null : scope),
[scope]
)
const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot)
const user = useQuery(api.auth.currentUser)
return user && snapshot.hydrated ? <ReadyAppIntentBridge key={scope} /> : null
}
function ReadyAppIntentBridge() {
const convex = useConvex()
const cacheScope = useCacheScope()
const playback = usePlayback()
const user = useQuery(api.auth.currentUser)
const navigation = useAppNavigation()
const favorites = useQuery(api.favorites.getUserFavorites)
const catalogUserKey = user ? JSON.stringify([user._id, favorites]) : null
const store = useMemo(
() =>
getPlaybackStore(
cacheScope === ANONYMOUS_CACHE_SCOPE ? null : cacheScope
),
[cacheScope]
)
const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot)
const handledIds = useRef<Set<string> | null>(null)
const publishChain = useRef(Promise.resolve())
const publishGeneration = useRef(0)
const playbackRef = useRef(playback)
playbackRef.current = playback
useEffect(() => {
if (!AppIntents.isAvailable() || !user) return
const generation = ++publishGeneration.current
let stopped = false
let refreshing = false
const refresh = () => {
if (refreshing || stopped) return
refreshing = true
publishChain.current = publishChain.current
.catch(() => undefined)
.then(async () => {
for (const kind of ["artist", "album", "song", "playlist"] as const) {
const entities: AppIntentEntity[] = []
let cursor: string | null = null
do {
const result: {
page: AppIntentEntity[]
isDone: boolean
continueCursor: string
} = await convex.query(api.library.intentCatalogPage, {
kind,
paginationOpts: { cursor, numItems: 200 },
})
if (stopped || generation !== publishGeneration.current) return
entities.push(...result.page)
cursor = result.isDone ? null : result.continueCursor
} while (cursor !== null)
await publishMusicCatalog(kind, entities)
}
})
.catch((error) =>
console.warn("Could not publish music catalog.", error)
)
.finally(() => {
refreshing = false
})
trackMusicCatalogSync(publishChain.current)
}
refresh()
const subscription = AppState.addEventListener("change", (state) => {
if (state === "active") refresh()
})
const timer = setInterval(() => {
if (AppState.currentState === "active") refresh()
}, 5 * 60_000)
return () => {
stopped = true
++publishGeneration.current
subscription.remove()
clearInterval(timer)
}
}, [convex, cacheScope, catalogUserKey])
const currentSongId = playback.queueSongIds[0] ?? null
const currentSong = playback.currentSong
useEffect(() => {
if (!snapshot.hydrated || !AppIntents.isAvailable()) {
return
}
if (!currentSongId) {
void publishMusicCatalog("nowPlaying", []).catch((error) => {
console.warn("Could not clear the current song.", error)
})
return
}
if (!currentSong || currentSong.id !== currentSongId) {
return
}
void publishMusicCatalog("nowPlaying", [
songEntity({
id: currentSong.id,
title: currentSong.title,
artistName: currentSong.artist.name,
artistId: currentSong.artist.id,
albumTitle: currentSong.album.title,
albumId: currentSong.album.id,
durationSeconds: currentSong.durationSeconds,
}),
]).catch((error) => {
console.warn("Could not publish the current song.", error)
})
}, [currentSong, currentSongId, snapshot.hydrated])
AppIntents.useAppIntents(async (pendingIntents) => {
if (!handledIds.current) {
handledIds.current = await loadHandledIntentIds()
}
const handled = handledIds.current
for (const invocation of pendingIntents) {
if (handled.has(invocation.id)) {
const token = readString(invocation.params.completionToken)
if (token) await completeMusicInvocation(token, null)
await AppIntents.removePendingInvocationAsync(invocation.id)
continue
}
if (!KNOWN_INTENTS.has(invocation.name)) {
await AppIntents.removePendingInvocationAsync(invocation.id)
continue
}
const token = readString(invocation.params.completionToken)
try {
ensureActive(invocation)
await performInvocation(invocation)
if (
["playMusic", "warmupAudio", "transport", "createStation"].includes(
invocation.name
)
) {
const id = store.getState().queue[0]
const song = playbackRef.current.currentSong
if (!id) await publishMusicCatalog("nowPlaying", [])
else if (song?.id === id)
await publishMusicCatalog("nowPlaying", [
songEntity({
id: song.id,
title: song.title,
artistName: song.artist.name,
artistId: song.artist.id,
albumTitle: song.album.title,
albumId: song.album.id,
durationSeconds: song.durationSeconds,
}),
])
}
await rememberHandledIntentId(handled, invocation.id)
if (token) await completeMusicInvocation(token, null)
await AppIntents.removePendingInvocationAsync(invocation.id)
} catch (error) {
if (token) {
await completeMusicInvocation(
token,
error instanceof Error ? error.message : "oTunes couldn't do that."
)
}
if (token || error instanceof IntentRejected || !isTransient(error)) {
const message =
error instanceof Error ? error.message : "oTunes couldn't do that."
if (!(error instanceof IntentRejected) || message) {
showError(message)
}
try {
await rememberHandledIntentId(handled, invocation.id)
await AppIntents.removePendingInvocationAsync(invocation.id)
} catch (removeError) {
console.warn(
"App Intent remains pending",
invocation.id,
removeError
)
}
continue
}
console.warn("App Intent remains pending", invocation.id, error)
}
}
async function songIdsFor(kind: string, id: string) {
if (kind === "song") {
return [id as Id<"songs">]
}
if (kind === "album") {
return fetchCachedQuery(
convex,
cacheScope,
api.playlists.getAlbumSongIds,
{
albumId: id as Id<"albums">,
}
)
}
if (kind === "artist") {
return fetchCachedQuery(
convex,
cacheScope,
api.playlists.getOrderedArtistSongIds,
{ artistId: id as Id<"artists"> }
)
}
if (kind === "playlist") {
if (id === FAVORITES_PLAYLIST_ID) {
const favorites = await fetchCachedQuery(
convex,
cacheScope,
api.favorites.getUserFavorites,
{}
)
return favorites.favoriteSongs
}
return fetchCachedQuery(
convex,
cacheScope,
api.playlists.getPlaylistSongIds,
{ playlistId: id as Id<"playlists"> }
)
}
throw new IntentRejected("Choose a song, album, artist, or playlist.")
}
async function uniqueSongIds(sources: MusicSource[]) {
const ids: Id<"songs">[] = []
for (const source of sources) {
ids.push(...(await songIdsFor(source.kind, source.id)))
}
return [...new Set(ids)]
}
async function performInvocation(invocation: AppIntentInvocation) {
const actions = playbackRef.current
switch (invocation.name) {
case "openMusic": {
const kind = readString(invocation.params.kind)
const id = readString(invocation.params.id)
if (!id || !kind) throw new IntentRejected("Choose music to open.")
if (kind === "song") {
const song = await convex.query(api.library.getSong, {
id: id as Id<"songs">,
})
if (!song)
throw new IntentRejected("This song is no longer available.")
navigation.push(`/album/${song.album}`)
} else if (kind === "playlist" && id === FAVORITES_PLAYLIST_ID) {
navigation.push("/playlist/favorites")
} else if (["album", "artist", "playlist"].includes(kind)) {
navigation.push(`/${kind}/${id}`)
} else throw new IntentRejected("Unknown music type.")
return
}
case "playMusic":
await playMusic(invocation)
if (!["next", "tail"].includes(String(invocation.params.queue))) {
ensureActive(invocation)
await playbackRef.current.waitForPlaybackReady(true)
}
return
case "warmupAudio":
await warmup(invocation)
ensureActive(invocation)
await playbackRef.current.waitForPlaybackReady(false)
warmedAudioIds.add(invocation.id)
return
case "addToPlaylist":
await addToPlaylist(invocation)
return
case "addToUpNext":
await addToUpNext(invocation)
return
case "clearUpNext":
ensureActive(invocation)
await actions.clearUpNext()
return
case "createPlaylist":
await createPlaylist(invocation)
return
case "createStation":
await createStation(invocation)
ensureActive(invocation)
await playbackRef.current.waitForPlaybackReady(true)
return
case "updateAffinity":
await updateAffinity(invocation)
return
case "transport":
await transport(invocation)
if (store.getState().queue.length > 0) {
const command = invocation.params.command
await playbackRef.current.waitForPlaybackReady(
command === "resume"
? true
: command === "pause"
? false
: undefined
)
}
return
default:
return
}
}
async function playMusic(invocation: AppIntentInvocation) {
const actions = playbackRef.current
const queue = readString(invocation.params.queue) ?? "now"
const warmupId = readString(invocation.params.warmupId)
const repeat = repeatChoice(invocation.params.repeat)
if (repeat) {
ensureActive(invocation)
await actions.setRepeatMode(repeat)
}
if (queue === "next" || queue === "tail") {
const kind = readString(invocation.params.kind)
const id = readString(invocation.params.id)
if (!kind || !id) {
throw new IntentRejected("Choose music to add to Up Next.")
}
const shuffled = shuffleChoice(
invocation.params.shuffle,
actions.shuffleEnabled
)
if (shuffled !== actions.shuffleEnabled) {
ensureActive(invocation)
await actions.setShuffleEnabled(shuffled)
}
const ids = await songIdsFor(kind, id)
if (ids.length === 0) {
throw new IntentRejected("Nothing to add to Up Next.")
}
if (queue === "next") {
ensureActive(invocation)
await actions.addToQueueNext(ids)
} else {
ensureActive(invocation)
await actions.addToQueueLast(ids)
}
return
}
if (warmupId && warmedAudioIds.has(warmupId)) {
const shuffled = shuffleChoice(
invocation.params.shuffle,
actions.shuffleEnabled
)
if (shuffled !== actions.shuffleEnabled) {
ensureActive(invocation)
await actions.setShuffleEnabled(shuffled)
}
ensureActive(invocation)
actions.setIsPlaying(true)
return
}
const kind = readString(invocation.params.kind) ?? "resume"
if (kind === "resume") {
const shuffled = shuffleChoice(
invocation.params.shuffle,
actions.shuffleEnabled
)
if (shuffled !== actions.shuffleEnabled) {
ensureActive(invocation)
await actions.setShuffleEnabled(shuffled)
}
if (actions.queueSongIds.length === 0) {
const favorites = await fetchCachedQuery(
convex,
cacheScope,
api.favorites.getUserFavorites,
{}
)
if (favorites.favoriteSongs.length === 0) {
throw new IntentRejected(
"Nothing is queued, and your favorites are empty."
)
}
if (shuffled) {
ensureActive(invocation)
await actions.playShuffled(favorites.favoriteSongs)
} else {
ensureActive(invocation)
await actions.playInOrder(favorites.favoriteSongs)
}
return
}
ensureActive(invocation)
actions.setIsPlaying(true)
return
}
const id = readString(invocation.params.id)
if (!id) {
throw new IntentRejected("Choose music to play.")
}
const shuffled = shuffleChoice(
invocation.params.shuffle,
actions.shuffleEnabled
)
if (kind === "song") {
const song = await fetchCachedQuery(
convex,
cacheScope,
api.library.getSong,
{
id: id as Id<"songs">,
}
)
if (!song) {
throw new IntentRejected("That song is no longer in your library.")
}
const albumSongIds = await fetchCachedQuery(
convex,
cacheScope,
api.playlists.getAlbumSongIds,
{ albumId: song.album }
)
ensureActive(invocation)
await actions.startFromSong(
song._id,
albumSongIds.length > 0 ? albumSongIds : [song._id],
shuffled,
true
)
return
}
const ids = await songIdsFor(kind, id)
if (ids.length === 0) {
throw new IntentRejected("Nothing to play.")
}
if (shuffled) {
ensureActive(invocation)
await actions.playShuffled(ids)
} else {
ensureActive(invocation)
await actions.playInOrder(ids)
}
}
async function warmup(invocation: AppIntentInvocation) {
const kind = readString(invocation.params.kind)
const id = readString(invocation.params.id)
if (!kind || !id) {
throw new IntentRejected("Choose music to get ready.")
}
const shuffled = shuffleChoice(invocation.params.shuffle, false)
if (kind === "song") {
const song = await fetchCachedQuery(
convex,
cacheScope,
api.library.getSong,
{
id: id as Id<"songs">,
}
)
if (!song) {
throw new IntentRejected("That song is no longer in your library.")
}
const albumSongIds = await fetchCachedQuery(
convex,
cacheScope,
api.playlists.getAlbumSongIds,
{ albumId: song.album }
)
ensureActive(invocation)
await playbackRef.current.startFromSong(
song._id,
albumSongIds.length > 0 ? albumSongIds : [song._id],
shuffled,
false
)
} else {
const ids = await songIdsFor(kind, id)
if (ids.length === 0) {
throw new IntentRejected("Nothing to get ready.")
}
ensureActive(invocation)
await playbackRef.current.prepareQueue(ids, shuffled)
}
}
async function addToPlaylist(invocation: AppIntentInvocation) {
const playlistId = readString(invocation.params.playlistId)
const sources = readSources(invocation.params.sources)
if (!playlistId || sources.length === 0) {
throw new IntentRejected("Choose music and a playlist.")
}
const songIds = await uniqueSongIds(sources)
if (songIds.length === 0) {
throw new IntentRejected("Those items have no songs to add.")
}
if (playlistId === FAVORITES_PLAYLIST_ID) {
for (const source of sources) {
if (source.kind === "song") {
ensureActive(invocation)
await convex.mutation(api.favorites.favoriteSong, {
songId: source.id as Id<"songs">,
})
} else if (source.kind === "album") {
ensureActive(invocation)
await convex.mutation(api.favorites.favoriteAlbum, {
albumId: source.id as Id<"albums">,
})
} else if (source.kind === "artist") {
ensureActive(invocation)
await convex.mutation(api.favorites.favoriteArtist, {
artistId: source.id as Id<"artists">,
})
} else if (source.kind === "playlist") {
const ids = await songIdsFor(source.kind, source.id)
if (ids.length > 0) {
ensureActive(invocation)
await convex.mutation(api.favorites.favoriteSongs, {
songIds: ids,
})
}
} else {
throw new IntentRejected(
"Choose a song, album, artist, or playlist."
)
}
}
return
}
ensureActive(invocation)
await convex.mutation(api.playlists.addSongsToPlaylist, {
playlistId: playlistId as Id<"playlists">,
songIds,
})
}
async function addToUpNext(invocation: AppIntentInvocation) {
const sources = readSources(invocation.params.sources)
if (sources.length === 0) {
throw new IntentRejected("Choose music to add to Up Next.")
}
const ids = await uniqueSongIds(sources)
if (ids.length === 0) {
throw new IntentRejected("Nothing to add to Up Next.")
}
const position =
readString(invocation.params.position) === "last" ? "last" : "next"
if (position === "last") {
ensureActive(invocation)
await playbackRef.current.addToQueueLast(ids)
} else {
ensureActive(invocation)
await playbackRef.current.addToQueueNext(ids)
}
}
async function createPlaylist(invocation: AppIntentInvocation) {
const name = readString(invocation.params.name)
if (!name) {
throw new IntentRejected("A playlist needs a name.")
}
const songIds = await uniqueSongIds(
readSources(invocation.params.sources)
)
ensureActive(invocation)
await convex.mutation(api.playlists.createPlaylist, {
name,
songIds,
invocationId: invocation.id,
})
}
async function createStation(invocation: AppIntentInvocation) {
const artistId = readString(invocation.params.artistId)
if (!artistId) {
throw new IntentRejected("Nothing is playing in oTunes.")
}
const ids = await songIdsFor("artist", artistId)
if (ids.length === 0)
throw new IntentRejected("This artist has no songs to play.")
ensureActive(invocation)
await playbackRef.current.playShuffled(ids)
}
async function updateAffinity(invocation: AppIntentInvocation) {
const kind = readString(invocation.params.kind)
const id = readString(invocation.params.id)
const state = readString(invocation.params.state)
if (!kind || !id || (state !== "like" && state !== "unset")) {
throw new IntentRejected(
"oTunes can love or unlike a song, album, or artist."
)
}
if (kind === "playlist") {
throw new IntentRejected("oTunes can love songs, albums, and artists.")
}
if (state === "like") {
if (kind === "song") {
ensureActive(invocation)
await convex.mutation(api.favorites.favoriteSong, {
songId: id as Id<"songs">,
})
} else if (kind === "album") {
ensureActive(invocation)
await convex.mutation(api.favorites.favoriteAlbum, {
albumId: id as Id<"albums">,
})
} else if (kind === "artist") {
ensureActive(invocation)
await convex.mutation(api.favorites.favoriteArtist, {
artistId: id as Id<"artists">,
})
} else {
throw new IntentRejected(
"oTunes can love songs, albums, and artists."
)
}
return
}
if (kind === "song") {
ensureActive(invocation)
await convex.mutation(api.favorites.unfavoriteSong, {
songId: id as Id<"songs">,
})
} else if (kind === "album") {
ensureActive(invocation)
await convex.mutation(api.favorites.unfavoriteAlbum, {
albumId: id as Id<"albums">,
})
} else if (kind === "artist") {
ensureActive(invocation)
await convex.mutation(api.favorites.unfavoriteArtist, {
artistId: id as Id<"artists">,
})
} else {
throw new IntentRejected("oTunes can love songs, albums, and artists.")
}
}
async function transport(invocation: AppIntentInvocation) {
const actions = playbackRef.current
const command = readString(invocation.params.command)
if (command === "pause") {
ensureActive(invocation)
actions.setIsPlaying(false)
return
}
if (command === "resume") {
if (actions.queueSongIds.length === 0) {
throw new IntentRejected("Nothing is queued in oTunes.")
}
ensureActive(invocation)
actions.setIsPlaying(true)
return
}
if (command === "next") {
ensureActive(invocation)
await actions.skipNext()
return
}
if (command === "previous") {
ensureActive(invocation)
await actions.skipPrevious()
return
}
throw new IntentRejected("oTunes doesn't know that playback control.")
}
})
return null
}
@@ -1,108 +0,0 @@
import { StyleSheet, Text, View } from "react-native"
import Svg, { G, Path } from "react-native-svg"
import type { PlaybackFormat } from "@otunes/convex/playback-stream"
const LABEL_SIZE = 13
const MARK_HEIGHT = 11
function DolbyMark({ color }: { color: string }) {
return (
<Svg
width={(MARK_HEIGHT * 23) / 16}
height={MARK_HEIGHT}
viewBox="0 0 23 16"
>
<Path d="M0 0H2.5A8 8 0 0 1 2.5 16H0Z" fill={color} />
<Path d="M23 0H20.5A8 8 0 0 0 20.5 16H23Z" fill={color} />
</Svg>
)
}
const LOSSLESS_PEAKS = [110, 215, 320]
const LOSSLESS_THIN_WIDTH = 24
const LOSSLESS_STROKES: [peak: number, d: string][] = [
[110, "M-70 320C-62 245 -38 166 0 166"],
[215, "M-70 320C-62 245 -38 166 0 166"],
[320, "M-30 185C-22 173 -11 166 0 166"],
[110, "M166 413C176 413 186 406 194 395"],
[215, "M166 413C200 413 226 340 240 275"],
[320, "M166 413C200 413 226 340 240 275"],
]
const LOSSLESS_FALL =
"M0 178L4 179L8 181L12 184L16 189L20 196L23 204L27 213L30 223L34 233L39 243L43 254L48 266L53 278L58 289L62 301L66 313L71 325L75 336L79 347L83 357L86 364L89 370L93 377L97 382L101 387L105 392L109 397L113 401L117 405L121 408L126 412L130 415L134 417L139 419L143 421L148 423L152 424L157 424L161 425L166 425L166 401L163 401L161 400L159 400L157 399L154 397L152 396L151 394L149 392L147 389L145 386L143 383L142 380L140 376L138 371L137 367L135 362L134 357L132 351L130 345L127 339L124 330L120 319L116 308L111 297L107 285L102 272L98 260L93 248L88 235L82 223L76 212L69 201L61 192L53 183L45 175L37 168L28 163L19 158L10 155L0 154Z"
const LOSSLESS_FALL_GAP =
"M0 178L4 180L6 184L8 190L9 197L11 203L14 210L17 219L21 228L24 238L29 248L33 259L38 270L43 282L47 293L52 305L56 317L60 328L64 340L68 351L73 361L76 368L79 375L83 381L87 387L91 393L95 398L100 403L104 408L109 412L113 416L118 419L124 422L130 424L135 425L141 426L147 426L152 426L157 425L161 425L166 425L166 401L163 401L161 399L159 398L158 395L157 393L156 390L155 387L155 384L154 381L153 379L152 376L150 373L149 369L148 366L146 361L145 357L143 352L142 347L140 341L137 335L134 326L130 315L126 304L122 293L117 281L113 268L108 256L103 243L98 231L92 219L86 207L79 196L71 186L62 177L53 168L44 161L32 157L21 155L10 154L0 154Z"
/**
* Three overlapping waves. Each thick downstroke is outlined in the
* background color so it reads as passing over the strokes behind it.
*/
function LosslessMark({
color,
backgroundColor,
}: {
color: string
backgroundColor: string
}) {
return (
<Svg
width={(MARK_HEIGHT * 544) / 271}
height={MARK_HEIGHT}
viewBox="28 154 544 271"
>
{LOSSLESS_STROKES.map(([peak, d], index) => (
<Path
key={index}
d={d}
x={peak}
stroke={color}
strokeWidth={LOSSLESS_THIN_WIDTH}
strokeLinecap="round"
fill="none"
/>
))}
{LOSSLESS_PEAKS.map((peak) => (
<G key={peak} x={peak}>
<Path d={LOSSLESS_FALL_GAP} fill={backgroundColor} />
<Path d={LOSSLESS_FALL} fill={color} />
</G>
))}
</Svg>
)
}
/** The Dolby Atmos or Lossless label shown under the progress bar. */
export function AudioFormatBadge({
format,
color,
backgroundColor,
}: {
format: PlaybackFormat
color: string
backgroundColor: string
}) {
const label = format === "atmos" ? "Dolby Atmos" : "Lossless"
return (
<View style={styles.badge} accessibilityLabel={label}>
{format === "atmos" ? (
<DolbyMark color={color} />
) : (
<LosslessMark color={color} backgroundColor={backgroundColor} />
)}
<Text style={[styles.label, { color }]}>{label}</Text>
</View>
)
}
const styles = StyleSheet.create({
badge: {
flexDirection: "row",
alignItems: "center",
gap: 3,
},
label: {
fontSize: LABEL_SIZE,
fontWeight: "500",
},
})
@@ -1,71 +0,0 @@
import {
requireNativeView,
requireOptionalNativeModule,
type NativeModule,
} from "expo"
import {
Platform,
Pressable,
type StyleProp,
type ViewProps,
type ViewStyle,
} from "react-native"
import { PlayerSymbol } from "@/components/player-symbol"
import { showError } from "@/lib/toast"
type AudioOutputModule = NativeModule & {
showPicker: () => Promise<boolean>
}
const audioOutput =
requireOptionalNativeModule<AudioOutputModule>("AudioOutput")
const AirPlayPicker =
Platform.OS === "ios" && audioOutput
? requireNativeView<ViewProps & { tint: string }>("AudioOutput")
: null
export function AudioOutputButton({
color,
style,
}: {
color: string
style: StyleProp<ViewStyle>
}) {
if (AirPlayPicker) {
return <AirPlayPicker tint={color} style={style} />
}
const available =
Platform.OS === "android" && Platform.Version >= 33 && audioOutput !== null
async function showPicker() {
try {
if (!(await audioOutput?.showPicker())) {
showError("Audio output selection is unavailable on this device.")
}
} catch {
showError("Audio output selection could not be opened.")
}
}
return (
<Pressable
onPress={showPicker}
disabled={!available}
hitSlop={8}
accessibilityRole="button"
accessibilityLabel={Platform.OS === "ios" ? "AirPlay" : "Audio output"}
accessibilityState={{ disabled: !available }}
style={[style, !available && { opacity: 0.35 }]}
>
<PlayerSymbol
name="airplay.audio"
fallback={{ material: "cast" }}
size={27}
weight="semibold"
color={color}
/>
</Pressable>
)
}
+39 -45
View File
@@ -1,17 +1,21 @@
import { useAuthActions } from "@convex-dev/auth/react"
import { Link } from "expo-router"
import { useAuthActions, useConvexAuth } from "@convex-dev/auth/react"
import { Link, useRouter } from "expo-router"
import { useQuery } from "convex/react"
import { useState } from "react"
import { Pressable, StyleSheet, Text, View } from "react-native"
import { useEffect, useState } from "react"
import {
KeyboardAvoidingView,
Platform,
Pressable,
StyleSheet,
Text,
View,
} from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { KeyboardForm } from "@/components/keyboard-form"
import { Button, Card, Input } from "@/components/ui/primitives"
import { useServerConfig } from "@/contexts/server-config"
import { api } from "@otunes/convex/_generated/api"
import { spacing, useThemeColors } from "@/lib/theme"
import { showError } from "@/lib/toast"
type AuthFlow = "signIn" | "signUp"
@@ -46,8 +50,10 @@ const copy: Record<
export function AuthForm({ flow }: { flow: AuthFlow }) {
const { signIn } = useAuthActions()
const auth = useConvexAuth()
const router = useRouter()
const colors = useThemeColors()
const { config, clearServer } = useServerConfig()
const { config } = useServerConfig()
const appSettings = useQuery(api.users.getAppSettings)
const [name, setName] = useState("")
const [email, setEmail] = useState("")
@@ -55,6 +61,12 @@ export function AuthForm({ flow }: { flow: AuthFlow }) {
const [error, setError] = useState<string | null>(null)
const [submitting, setSubmitting] = useState(false)
useEffect(() => {
if (auth.isAuthenticated) {
router.replace("/(app)/(tabs)/home")
}
}, [auth.isAuthenticated, router])
const text = copy[flow]
const accountCreationDisabled = appSettings?.disableAccountCreation ?? false
const signupsDisabled = flow === "signUp" && accountCreationDisabled
@@ -87,15 +99,14 @@ export function AuthForm({ flow }: { flow: AuthFlow }) {
return (
<SafeAreaView style={[styles.safe, { backgroundColor: colors.background }]}>
<KeyboardForm style={styles.container}>
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : undefined}
style={styles.container}
>
<Card>
<View style={styles.header}>
<Text style={[styles.title, { color: colors.foreground }]}>
{text.title}
</Text>
<Text
style={[styles.description, { color: colors.mutedForeground }]}
>
<Text style={[styles.title, { color: colors.foreground }]}>{text.title}</Text>
<Text style={[styles.description, { color: colors.mutedForeground }]}>
{text.description}
</Text>
{config ? (
@@ -107,8 +118,8 @@ export function AuthForm({ flow }: { flow: AuthFlow }) {
{signupsDisabled ? (
<Text style={{ color: colors.mutedForeground }}>
New account registration is currently disabled. Contact an
administrator if you need access.
New account registration is currently disabled. Contact an administrator if you need
access.
</Text>
) : (
<View style={styles.form}>
@@ -133,28 +144,16 @@ export function AuthForm({ flow }: { flow: AuthFlow }) {
onChangeText={setPassword}
placeholder="Password"
secureTextEntry
autoComplete={
flow === "signIn" ? "current-password" : "new-password"
}
/>
{error ? (
<Text style={{ color: colors.destructive }}>{error}</Text>
) : null}
<Button
title={text.submit}
loading={submitting}
onPress={() => void handleSubmit()}
autoComplete={flow === "signIn" ? "current-password" : "new-password"}
/>
{error ? <Text style={{ color: colors.destructive }}>{error}</Text> : null}
<Button title={text.submit} loading={submitting} onPress={() => void handleSubmit()} />
{!hideSignUpLink ? (
<View style={styles.switchRow}>
<Text style={{ color: colors.mutedForeground }}>
{text.switchPrompt}{" "}
</Text>
<Text style={{ color: colors.mutedForeground }}>{text.switchPrompt} </Text>
<Link href={text.switchHref} asChild>
<Pressable>
<Text
style={{ color: colors.foreground, fontWeight: "600" }}
>
<Text style={{ color: colors.foreground, fontWeight: "600" }}>
{text.switchLabel}
</Text>
</Pressable>
@@ -165,17 +164,12 @@ export function AuthForm({ flow }: { flow: AuthFlow }) {
)}
</Card>
<Pressable
style={styles.changeServer}
onPress={() =>
void clearServer().catch(() =>
showError("Could not clear the server address.")
)
}
>
<Text style={{ color: colors.mutedForeground }}>Change server</Text>
</Pressable>
</KeyboardForm>
<Link href="/server" asChild>
<Pressable style={styles.changeServer}>
<Text style={{ color: colors.mutedForeground }}>Change server</Text>
</Pressable>
</Link>
</KeyboardAvoidingView>
</SafeAreaView>
)
}
@@ -0,0 +1,24 @@
import { useConvexAuth } from "@convex-dev/auth/react"
import { Redirect } from "expo-router"
import { LoadingView } from "@/components/ui/primitives"
export function AuthenticatedRedirect() {
const auth = useConvexAuth()
if (!auth) {
return <LoadingView />
}
const { isLoading, isAuthenticated } = auth
if (isLoading) {
return <LoadingView />
}
if (!isAuthenticated) {
return <Redirect href="/signin" />
}
return <Redirect href="/(app)/(tabs)/home" />
}
@@ -1,46 +0,0 @@
import { memo } from "react"
import { StyleSheet, Text, View } from "react-native"
import { useThemeColors } from "@/lib/theme"
/** Horizontal inset for rows and dividers in album and playlist track lists. */
export const collectionInset = 20
/** Separates a collection's header from its track list. */
export function CollectionDivider({ color }: { color?: string }) {
const colors = useThemeColors()
return (
<View
style={[styles.divider, { backgroundColor: color ?? colors.border }]}
/>
)
}
export const DiscHeader = memo(function DiscHeader({
label,
color,
}: {
label: string
color?: string
}) {
const colors = useThemeColors()
return (
<Text style={[styles.discHeader, { color: color ?? colors.foreground }]}>
{label}
</Text>
)
})
const styles = StyleSheet.create({
divider: {
height: StyleSheet.hairlineWidth,
marginHorizontal: collectionInset,
},
discHeader: {
fontSize: 17,
fontWeight: "700",
paddingHorizontal: collectionInset,
paddingTop: 24,
paddingBottom: 8,
},
})
@@ -1,359 +0,0 @@
import * as Haptics from "expo-haptics"
import { SymbolView } from "expo-symbols"
import { useCallback, useMemo, useState, type ReactNode } from "react"
import {
PlatformColor,
Pressable,
StyleSheet,
type LayoutChangeEvent,
} from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import Animated, {
cancelAnimation,
Extrapolation,
interpolate,
useAnimatedStyle,
useSharedValue,
withSpring,
withTiming,
} from "react-native-reanimated"
import { scheduleOnRN } from "react-native-worklets"
const ACTION_WIDTH = 82
const CARD_ROUNDING_REVEAL = 40
const PILL_MIN_MARGIN = 10
const PILL_COMMITTED_MARGIN = 6
const PILL_WIDTH_INPUT = [24, ACTION_WIDTH, 220]
const PILL_WIDTH_OUTPUT = [0, 62, 200]
const PILL_HEIGHT_INPUT = [0, 24, 62, 140, 200]
const PILL_HEIGHT_RATIO = [0, 0.3, 0.77, 0.82, 0.86]
const ICON_FULL_SIZE_REVEAL = 64
const FULL_SWIPE_RATIO = 0.55
const FLING_VELOCITY = 400
const SETTLE_SPRING = { duration: 450, dampingRatio: 1 }
const LABEL_SPRING = { duration: 300, dampingRatio: 0.85 }
const SLIDE_OUT = { duration: 200 }
const COLLAPSE = { duration: 250 }
/**
* Keeps at most one row open, like a `UITableView`: opening a row closes the
* previous one, and `closeOpenRow` closes whichever is open (call it when the
* list starts scrolling).
*/
export type SwipeRowGroup = {
setOpen: (close: () => void) => void
clear: (close: () => void) => void
closeOpenRow: () => void
}
export function useSwipeRowGroup(): SwipeRowGroup {
const [group] = useState<SwipeRowGroup>(() => {
let openRowClose: (() => void) | null = null
return {
setOpen(close) {
if (openRowClose && openRowClose !== close) openRowClose()
openRowClose = close
},
clear(close) {
if (openRowClose === close) openRowClose = null
},
closeOpenRow() {
openRowClose?.()
openRowClose = null
},
}
})
return group
}
type SwipeToRemoveRowProps = {
group: SwipeRowGroup
backgroundColor: string
actionAccessibilityLabel: string
/** Resolves `false` if the removal failed, which restores the row. */
onRemove: () => Promise<boolean>
children: ReactNode
}
/**
* The iOS 26 trailing swipe-to-delete row: the row lifts into a rounded card
* and a red pill grows in the revealed space. Release past half the pill to
* leave it open, or drag past the full-swipe point (haptic, the pill fills the
* space) to remove on release.
*/
export function SwipeToRemoveRow(props: SwipeToRemoveRowProps) {
const [generation, setGeneration] = useState(0)
const restore = useCallback(() => setGeneration((value) => value + 1), [])
return <SwipeRowBody key={generation} {...props} onRestore={restore} />
}
function SwipeRowBody({
group,
backgroundColor,
actionAccessibilityLabel,
onRemove,
onRestore,
children,
}: SwipeToRemoveRowProps & { onRestore: () => void }) {
const width = useSharedValue(0)
const height = useSharedValue(0)
const translateX = useSharedValue(0)
const startX = useSharedValue(0)
const committed = useSharedValue(false)
const commitProgress = useSharedValue(0)
const collapse = useSharedValue(0)
const removing = useSharedValue(false)
const [isOpen, setIsOpen] = useState(false)
const close = useCallback(() => {
if (removing.value) return
translateX.value = withSpring(0, SETTLE_SPRING)
setIsOpen(false)
}, [removing, translateX])
const handleSwipeStart = useCallback(() => group.setOpen(close), [close, group])
const handleSettle = useCallback(
(open: boolean) => {
setIsOpen(open)
if (!open) group.clear(close)
},
[close, group]
)
const handleRemove = useCallback(async () => {
group.clear(close)
if (!(await onRemove())) onRestore()
}, [close, group, onRemove, onRestore])
const animateRemoval = useCallback(() => {
"worklet"
removing.value = true
commitProgress.value = withSpring(1, LABEL_SPRING)
translateX.value = withTiming(-width.value, SLIDE_OUT, (slid) => {
if (!slid) return
collapse.value = withTiming(1, COLLAPSE, (collapsed) => {
if (collapsed) scheduleOnRN(handleRemove)
})
})
}, [collapse, commitProgress, handleRemove, removing, translateX, width])
const pan = useMemo(() => {
const gesture = Gesture.Pan()
.failOffsetY([-10, 10])
.onStart(() => {
if (removing.value) return
cancelAnimation(translateX)
startX.value = translateX.value
scheduleOnRN(handleSwipeStart)
})
.onUpdate((event) => {
if (removing.value) return
const rowWidth = width.value
const x = Math.max(
-rowWidth,
Math.min(0, startX.value + event.translationX)
)
translateX.value = x
const shouldCommit = -x > rowWidth * FULL_SWIPE_RATIO
if (shouldCommit !== committed.value) {
committed.value = shouldCommit
commitProgress.value = withSpring(shouldCommit ? 1 : 0, LABEL_SPRING)
scheduleOnRN(impact)
}
})
.onEnd((event) => {
if (removing.value) return
if (committed.value) {
animateRemoval()
return
}
const velocity = event.velocityX
const open =
velocity < -FLING_VELOCITY ||
(velocity <= FLING_VELOCITY && translateX.value < -ACTION_WIDTH / 2)
translateX.value = withSpring(open ? -ACTION_WIDTH : 0, {
...SETTLE_SPRING,
velocity,
})
scheduleOnRN(handleSettle, open)
})
return isOpen
? gesture.activeOffsetX([-10, 10])
: gesture.activeOffsetX(-10).failOffsetX(10)
}, [
animateRemoval,
commitProgress,
committed,
handleSettle,
handleSwipeStart,
isOpen,
removing,
startX,
translateX,
width,
])
const handleLayout = useCallback(
(event: LayoutChangeEvent) => {
if (removing.value) return
width.value = event.nativeEvent.layout.width
height.value = event.nativeEvent.layout.height
},
[height, removing, width]
)
const containerStyle = useAnimatedStyle(() =>
collapse.value > 0 ? { height: height.value * (1 - collapse.value) } : {}
)
const contentStyle = useAnimatedStyle(() => ({
borderRadius: interpolate(
-translateX.value,
[0, CARD_ROUNDING_REVEAL],
[0, height.value / 2],
Extrapolation.CLAMP
),
transform: [{ translateX: translateX.value }],
}))
const cardFillStyle = useAnimatedStyle(() => ({
opacity: interpolate(
-translateX.value,
[0, CARD_ROUNDING_REVEAL],
[0, 1],
Extrapolation.CLAMP
),
}))
const actionStyle = useAnimatedStyle(() => ({
width: -translateX.value,
}))
// The pill grows out of a dot centered in the revealed space; past the
// full-swipe point it stretches to fill that space.
const pillStyle = useAnimatedStyle(() => {
const revealed = -translateX.value
const rowHeight = height.value
const resting = Math.min(
revealed - PILL_MIN_MARGIN * 2,
interpolate(
revealed,
PILL_WIDTH_INPUT,
PILL_WIDTH_OUTPUT,
Extrapolation.EXTEND
)
)
const pillWidth = Math.max(
0,
resting +
(revealed - PILL_COMMITTED_MARGIN * 2 - resting) *
commitProgress.value
)
const restingHeight = interpolate(
pillWidth,
PILL_HEIGHT_INPUT,
PILL_HEIGHT_RATIO.map((ratio) => ratio * rowHeight),
Extrapolation.CLAMP
)
const pillHeight =
restingHeight +
(rowHeight - PILL_COMMITTED_MARGIN * 2 - restingHeight) *
commitProgress.value
return {
width: pillWidth,
height: pillHeight,
borderRadius: pillHeight / 2,
opacity: 1 - collapse.value,
}
})
const iconStyle = useAnimatedStyle(() => ({
transform: [
{
scale: interpolate(
-translateX.value,
[PILL_WIDTH_INPUT[0], ICON_FULL_SIZE_REVEAL],
[0, 1],
Extrapolation.CLAMP
),
},
],
}))
return (
<Animated.View
onLayout={handleLayout}
style={[styles.container, containerStyle]}
>
<Animated.View style={[styles.action, actionStyle]}>
<Pressable
accessibilityRole="button"
accessibilityLabel={actionAccessibilityLabel}
onPress={() => animateRemoval()}
style={styles.actionButton}
>
<Animated.View style={[styles.pill, pillStyle]}>
<Animated.View style={iconStyle}>
<SymbolView
name="minus.circle.fill"
size={20}
tintColor="white"
/>
</Animated.View>
</Animated.View>
</Pressable>
</Animated.View>
<GestureDetector gesture={pan}>
<Animated.View style={[styles.card, { backgroundColor }, contentStyle]}>
<Animated.View
pointerEvents="none"
style={[styles.cardFill, cardFillStyle]}
/>
{children}
{isOpen ? (
<Pressable
accessible={false}
onPress={close}
style={StyleSheet.absoluteFill}
/>
) : null}
</Animated.View>
</GestureDetector>
</Animated.View>
)
}
function impact() {
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium)
}
const styles = StyleSheet.create({
container: { overflow: "hidden" },
card: { overflow: "hidden" },
cardFill: {
...StyleSheet.absoluteFill,
backgroundColor: PlatformColor("tertiarySystemFill"),
},
action: {
position: "absolute",
top: 0,
right: 0,
bottom: 0,
},
actionButton: {
flex: 1,
alignItems: "center",
justifyContent: "center",
},
pill: {
alignItems: "center",
justifyContent: "center",
overflow: "hidden",
backgroundColor: PlatformColor("systemRed"),
},
})
-32
View File
@@ -1,32 +0,0 @@
import type { PropsWithChildren } from "react"
import {
KeyboardAvoidingView,
Platform,
ScrollView,
type StyleProp,
type ViewStyle,
} from "react-native"
/** Android resizes for the IME; scrolling keeps tall forms and actions reachable. */
export function KeyboardForm({
children,
style,
}: PropsWithChildren<{ style?: StyleProp<ViewStyle> }>) {
if (Platform.OS === "android") {
return (
<ScrollView
style={{ flex: 1 }}
contentContainerStyle={[style, { flex: undefined, flexGrow: 1 }]}
keyboardShouldPersistTaps="handled"
keyboardDismissMode="on-drag"
>
{children}
</ScrollView>
)
}
return (
<KeyboardAvoidingView behavior="padding" style={style}>
{children}
</KeyboardAvoidingView>
)
}
-100
View File
@@ -1,100 +0,0 @@
import { useEffect, useState } from "react"
import {
StyleSheet,
Text,
View,
type StyleProp,
type TextStyle,
} from "react-native"
import Animated, {
cancelAnimation,
Easing,
useAnimatedStyle,
useSharedValue,
withDelay,
withRepeat,
withSequence,
withTiming,
} from "react-native-reanimated"
const GAP = 48
const PAUSE_MS = 2500
const POINTS_PER_SECOND = 30
// Wide enough that the measured text is never wrapped or truncated.
const MEASURE_WIDTH = 10_000
/**
* One line of text that scrolls when it doesn't fit, pausing at the start of
* each loop like the Now Playing title in Apple Music.
*/
export function MarqueeText({
text,
style,
}: {
text: string
style: StyleProp<TextStyle>
}) {
const [containerWidth, setContainerWidth] = useState(0)
const [textWidth, setTextWidth] = useState(0)
const offset = useSharedValue(0)
const overflows = containerWidth > 0 && textWidth > containerWidth + 1
useEffect(() => {
cancelAnimation(offset)
offset.value = 0
if (!overflows) return
const distance = textWidth + GAP
offset.value = withRepeat(
withSequence(
withDelay(
PAUSE_MS,
withTiming(-distance, {
duration: (distance / POINTS_PER_SECOND) * 1000,
easing: Easing.linear,
})
),
withTiming(0, { duration: 0 })
),
-1
)
return () => cancelAnimation(offset)
}, [offset, overflows, text, textWidth])
const trackStyle = useAnimatedStyle(() => ({
transform: [{ translateX: offset.value }],
}))
return (
<View
style={styles.container}
onLayout={(event) => setContainerWidth(event.nativeEvent.layout.width)}
accessible
accessibilityLabel={text}
>
<Animated.View style={[styles.track, trackStyle]}>
<Text
style={style}
numberOfLines={1}
onLayout={(event) => setTextWidth(event.nativeEvent.layout.width)}
>
{text}
</Text>
{overflows ? (
<Text style={[style, { marginLeft: GAP }]} numberOfLines={1}>
{text}
</Text>
) : null}
</Animated.View>
</View>
)
}
const styles = StyleSheet.create({
container: {
overflow: "hidden",
},
track: {
flexDirection: "row",
width: MEASURE_WIDTH,
},
})
+15 -50
View File
@@ -1,11 +1,8 @@
import { MusicEntityView } from "@/components/music-entity-view"
import { Ionicons } from "@expo/vector-icons"
import { memo, useCallback, type ReactElement } from "react"
import {
FlatList,
Platform,
Pressable,
ScrollView,
StyleSheet,
Text,
View,
@@ -35,7 +32,6 @@ import {
export type MediaItem = BrowseAlbum | BrowseArtist | PlaylistSummary
const GRID_INITIAL_ROWS = 5
const MAX_NON_VIRTUAL_CAROUSEL_ITEMS = 10
export const AlbumCard = memo(function AlbumCard({
album,
@@ -78,14 +74,11 @@ export const AlbumCard = memo(function AlbumCard({
return (
<MediaContextMenu
favorited={isAlbumFavorite(album.id)}
stationArtistId={album.artist.id}
navigation={{ artist: { id: album.artist.id } }}
share={{ type: "album", albumId: album.id, title: album.title }}
share={{ type: "album", albumId: album.id }}
onAction={(action) => void handleAlbumAction(album, action)}
>
<MusicEntityView kind="album" id={album.id}>
{card}
</MusicEntityView>
{card}
</MediaContextMenu>
)
})
@@ -125,12 +118,10 @@ export const ArtistCard = memo(function ArtistCard({
return (
<MediaContextMenu
favorited={isArtistFavorite(artist.id)}
share={{ type: "artist", artistId: artist.id, title: artist.name }}
share={{ type: "artist", artistId: artist.id }}
onAction={(action) => void handleArtistAction(artist, action)}
>
<MusicEntityView kind="artist" id={artist.id}>
{card}
</MusicEntityView>
{card}
</MediaContextMenu>
)
})
@@ -176,16 +167,10 @@ export const PlaylistCard = memo(function PlaylistCard({
return (
<MediaContextMenu
showFavorite={false}
share={{
type: "playlist",
playlistId: playlist.id,
title: playlist.title,
}}
share={{ type: "playlist", playlistId: playlist.id }}
onAction={(action) => void handlePlaylistAction(playlist, action)}
>
<MusicEntityView kind="playlist" id={playlist.id}>
{card}
</MusicEntityView>
{card}
</MediaContextMenu>
)
})
@@ -226,7 +211,7 @@ export function MediaGridList({
content: MediaItem[]
paddingBottom: number
onEndReached?: () => void
ListHeaderComponent?: ReactElement
ListHeaderComponent?: ReactElement | null
contentInset?: boolean
}) {
const cardWidth = useTwoColumnCardWidth()
@@ -313,30 +298,14 @@ function ContentCarouselBody({
/>
) : null}
</Pressable>
{Platform.OS === "android" &&
content.length <= MAX_NON_VIRTUAL_CAROUSEL_ITEMS ? (
<ScrollView
horizontal
style={styles.androidCarousel}
showsHorizontalScrollIndicator={false}
contentContainerStyle={styles.carouselContent}
>
{content.map((item) => (
<View key={mediaItemKey(item)}>
<CarouselCard item={item} width={carouselCardWidth} />
</View>
))}
</ScrollView>
) : (
<FlatList
data={content}
keyExtractor={mediaItemKey}
renderItem={renderCarouselItem}
horizontal
showsHorizontalScrollIndicator={false}
contentContainerStyle={styles.carouselContent}
/>
)}
<FlatList
data={content}
keyExtractor={mediaItemKey}
renderItem={renderCarouselItem}
horizontal
showsHorizontalScrollIndicator={false}
contentContainerStyle={styles.carouselContent}
/>
</View>
)
}
@@ -366,10 +335,6 @@ const styles = StyleSheet.create({
fontSize: 22,
fontWeight: "700",
},
androidCarousel: {
// Horizontal lists should measure their cards, not stretch the Home sections.
flexGrow: 0,
},
carouselContent: {
gap: spacing.md,
},
+4 -18
View File
@@ -1,10 +1,8 @@
import type { MenuAction } from "@expo/ui/community/menu"
import { MenuView } from "@/components/media-menu"
import { MenuView, type MenuAction } from "@expo/ui/community/menu"
import { requireNativeView } from "expo"
import type { ComponentType, ReactNode } from "react"
import {
Platform,
View,
type StyleProp,
type ViewProps,
type ViewStyle,
@@ -21,7 +19,6 @@ export type MediaAction =
| "play-next"
| "play-last"
| "shuffle"
| "create-station"
| "favorite"
| "go-artist"
| "go-album"
@@ -37,7 +34,6 @@ export type MediaMenuConfig = {
playlistLabel?: string
favorited?: boolean
showFavorite?: boolean
stationArtistId?: string
navigation?: MediaNavigation
share?: MediaShareContext
includeActions?: MediaAction[]
@@ -81,11 +77,6 @@ const MEDIA_ACTION_ITEMS: {
label: (countSuffix) => `Shuffle${countSuffix}`,
image: "shuffle",
},
{
action: "create-station",
label: () => "Create Station",
image: "shuffle",
},
{
action: "go-artist",
label: () => "Go to Artist",
@@ -113,10 +104,6 @@ function isActionIncluded(
action: MediaAction,
config: Omit<MediaMenuConfig, "onAction">
): boolean {
if (action === "create-station" && !config.stationArtistId) {
return false
}
if (config.includeActions) {
return config.includeActions.includes(action)
}
@@ -172,7 +159,8 @@ export function buildMediaMenuActions(
actions.push({
id: item.action,
title: item.label(countSuffix, favorited, playlistLabel),
image: item.action === "favorite" && favorited ? "star.fill" : item.image,
image:
item.action === "favorite" && favorited ? "star.fill" : item.image,
})
}
@@ -253,9 +241,7 @@ function NativeMediaContextMenu({
return (
<NativeContextMenuView style={{ display: "contents" }} disableForceFlatten>
{/* The native menu retains its first trigger. Keep that view mounted when
focus changes replace the Siri entity wrapper inside it. */}
<View collapsable={false}>{children}</View>
{children}
{buildMediaMenuActions({ ...actionConfig, share }).map((action) => (
<NativeContextMenuAction
key={action.id}
@@ -1,140 +0,0 @@
import { Ionicons } from "@expo/vector-icons"
import type { ComponentProps } from "react"
import type { MediaAction } from "@/components/media-context-menu"
import type { MenuComponentProps } from "@expo/ui/community/menu"
import {
DropdownMenu,
DropdownMenuItem,
Host,
RNHostView,
Text,
} from "@expo/ui/jetpack-compose"
import { useState } from "react"
import { Pressable, View } from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import { appleMusic } from "@/lib/theme"
const actionIcons = {
share: "share-outline",
playlist: "list-outline",
"play-next": "play-forward-outline",
"play-last": "list",
shuffle: "shuffle",
"create-station": "radio-outline",
favorite: "star-outline",
"go-artist": "person-outline",
"go-album": "disc-outline",
"delete-playlist": "trash-outline",
} satisfies Record<MediaAction, ComponentProps<typeof Ionicons>["name"]>
// The community MenuView creates a dynamic-color Host internally. Own this
// Android host so menus use the same fixed palette as the rest of the app.
export function MenuView({
actions,
children,
style,
shouldOpenOnLongPress,
onPressAction,
}: MenuComponentProps) {
const [expanded, setExpanded] = useState(false)
const longPress = Gesture.LongPress()
.runOnJS(true)
.onStart(() => setExpanded(true))
return (
<View style={style}>
<Host
colorScheme="dark"
seedColor={appleMusic.pink}
colorOverrides={{
primary: appleMusic.pink,
onPrimary: "#FFFFFF",
surface: "#000000",
onSurface: "#FFFFFF",
onSurfaceVariant: "#FFFFFF",
surfaceContainer: "#1C1C1E",
surfaceContainerHigh: "#1C1C1E",
surfaceTint: "#000000",
outline: "#545458",
outlineVariant: "#545458",
error: "#FF453A",
}}
// Rows fill their parent width; compact action buttons keep intrinsic sizing.
matchContents={shouldOpenOnLongPress ? { vertical: true } : true}
>
<DropdownMenu
expanded={expanded}
onDismissRequest={() => setExpanded(false)}
color={appleMusic.elevated}
cornerRadius={4}
shadowElevation={0}
properties={{ clippingEnabled: false }}
>
<DropdownMenu.Trigger>
<RNHostView
matchContents={shouldOpenOnLongPress ? { vertical: true } : true}
>
{shouldOpenOnLongPress ? (
<GestureDetector gesture={longPress}>
<View collapsable={false}>{children}</View>
</GestureDetector>
) : (
<Pressable
onPress={() => setExpanded(true)}
accessible={false}
focusable={false}
android_disableSound
>
<View pointerEvents="none">{children}</View>
</Pressable>
)}
</RNHostView>
</DropdownMenu.Trigger>
<DropdownMenu.Items>
{actions
.filter((action) => !action.attributes?.hidden)
.map((action) => (
<DropdownMenuItem
key={action.id ?? action.title}
enabled={!action.attributes?.disabled}
elementColors={{
textColor: action.attributes?.destructive
? "#FF453A"
: "#FFFFFF",
}}
onClick={() => {
setExpanded(false)
onPressAction?.({
nativeEvent: { event: action.id ?? action.title },
})
}}
>
<DropdownMenuItem.LeadingIcon>
<RNHostView matchContents>
<Ionicons
name={
action.id === "favorite" &&
action.image === "star.fill"
? "star"
: (actionIcons[action.id as MediaAction] ??
"ellipsis-horizontal")
}
size={20}
color={
action.attributes?.destructive ? "#FF453A" : "#FFFFFF"
}
accessible={false}
/>
</RNHostView>
</DropdownMenuItem.LeadingIcon>
<DropdownMenuItem.Text>
<Text>{action.title}</Text>
</DropdownMenuItem.Text>
</DropdownMenuItem>
))}
</DropdownMenu.Items>
</DropdownMenu>
</Host>
</View>
)
}
-1
View File
@@ -1 +0,0 @@
export { MenuView } from "@expo/ui/community/menu"
+53 -85
View File
@@ -1,20 +1,20 @@
import {
useAndroidTabPalette,
useAndroidTabHasArtworkPalette,
} from "@/contexts/android-tab-theme"
import { Ionicons } from "@expo/vector-icons"
import { NativeTabs } from "expo-router/native-tabs"
import { NativeTabs } from "expo-router/unstable-native-tabs"
import { useRouter } from "expo-router"
import { Platform, Pressable, StyleSheet, Text, View } from "react-native"
import { useSafeAreaInsets } from "react-native-safe-area-context"
import { CoverImage } from "@/components/cover-image"
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { albumCoverUrl } from "@/lib/urls"
import { miniPlayerHeight, tabBarHeight, useThemeColors } from "@/lib/theme"
import {
miniPlayerHeight,
tabBarHeight,
useBlurTint,
useMiniPlayerBackground,
useThemeColors,
} from "@/lib/theme"
function MiniPlayerContent({
placement,
@@ -25,19 +25,10 @@ function MiniPlayerContent({
variant: "bar" | "accessory"
onOpenPlayer: () => void
}) {
const theme = useThemeColors()
const palette = useAndroidTabPalette()
const colors =
Platform.OS === "android"
? {
...theme,
foreground: palette.foreground,
mutedForeground: palette.secondaryForeground,
}
: theme
const colors = useThemeColors()
const { config } = useServerConfig()
const { currentSong, isPlaying } = usePlaybackQueue()
const { setIsPlaying, skipNext, skipPrevious } = usePlaybackActions()
const { setIsPlaying, skipNext } = usePlaybackActions()
if (!currentSong || !config) {
return null
@@ -121,20 +112,6 @@ function MiniPlayerContent({
</Text>
</View>
<View style={styles.controls}>
{Platform.OS === "android" && !isAccessory ? (
<Pressable
style={styles.controlButton}
accessibilityRole="button"
accessibilityLabel="Previous track"
onPress={(event) => {
event.stopPropagation()
void skipPrevious()
}}
hitSlop={6}
>
<Ionicons name="play-back" size={24} color={colors.foreground} />
</Pressable>
) : null}
<Pressable
style={styles.controlButton}
onPress={(event) => {
@@ -165,28 +142,13 @@ function MiniPlayerContent({
}
function MiniPlayerChrome({ children }: { children: React.ReactNode }) {
const palette = useAndroidTabPalette()
const hasArtworkPalette = useAndroidTabHasArtworkPalette()
const colors = useThemeColors()
const backgroundColor = useMiniPlayerBackground()
return (
<View style={[styles.androidBar, { backgroundColor: palette.background }]}>
<View style={[styles.androidBar, { backgroundColor }]}>
<View style={[styles.topBorder, { backgroundColor: colors.border }]} />
{children}
{hasArtworkPalette ? (
<View
style={[
styles.separator,
styles.topBorder,
{ backgroundColor: palette.secondaryForeground },
]}
/>
) : null}
<View
style={[
styles.separator,
styles.bottomBorder,
{ backgroundColor: palette.secondaryForeground },
]}
/>
</View>
)
}
@@ -216,31 +178,43 @@ export function TabBottomAccessory() {
return content
}
/** NativeTabs.BottomAccessory only renders on iOS. */
export function AndroidMiniPlayer() {
const router = useRouter()
const insets = useSafeAreaInsets()
const { currentSong, queueSongIds } = usePlaybackQueue()
if (Platform.OS !== "android" || !currentSong || queueSongIds.length === 0) {
return null
}
return (
<View
style={[
styles.floatingContainer,
{ bottom: tabBarHeight + insets.bottom },
]}
>
<MiniPlayerChrome>
<MiniPlayerContent
placement="regular"
variant="bar"
onOpenPlayer={() => router.push("/player")}
/>
</MiniPlayerChrome>
</View>
)
}
//
// function useFloatingMiniPlayerLayout() {
// const segments = useSegments() as string[]
// const insets = useSafeAreaInsets()
//
// const onPlayerModal = segments.includes("player")
// const onAuthFlow =
// segments.includes("signin") ||
// segments.includes("signup") ||
// segments.includes("server")
// const onTabs = segments.includes("(tabs)")
//
// const bottom = insets.bottom + (onTabs ? 0 : 0)
//
// return {
// bottom,
// hidden: onPlayerModal || onAuthFlow || onTabs,
// }
// }
//
// export function FloatingMiniPlayer() {
// const router = useRouter()
// const { bottom, hidden } = useFloatingMiniPlayerLayout()
// const { currentSong, queueSongIds } = usePlayback()
//
// if (hidden || !currentSong || queueSongIds.length === 0) {
// return null
// }
//
// return (
// <View pointerEvents="box-none" style={[styles.floatingContainer, { bottom }]}>
// <MiniPlayerChrome>
// <MiniPlayerContent onOpenPlayer={() => router.push("/player")} />
// </MiniPlayerChrome>
// </View>
// )
// }
const styles = StyleSheet.create({
floatingContainer: {
@@ -260,15 +234,9 @@ const styles = StyleSheet.create({
androidBar: {
overflow: "hidden",
},
separator: {
position: "absolute",
left: 0,
right: 0,
height: 1,
zIndex: 1,
topBorder: {
height: StyleSheet.hairlineWidth,
},
topBorder: { top: 0 },
bottomBorder: { bottom: 0 },
content: {
flexDirection: "row",
alignItems: "center",
@@ -1,27 +0,0 @@
import { useIsFocused } from "expo-router"
import { AppEntityView } from "expo-app-intents"
import type { PropsWithChildren } from "react"
import { View, type ViewProps } from "react-native"
import type { MusicEntityKind } from "@/lib/app-intents"
/** Only the focused screen contributes entities to Siri's on-screen context. */
export function MusicEntityView({
kind,
id,
children,
...props
}: PropsWithChildren<
ViewProps & {
kind: MusicEntityKind
id: string
}
>) {
const focused = useIsFocused()
return focused ? (
<AppEntityView entity={kind} entityId={id} {...props}>
{children}
</AppEntityView>
) : (
<View {...props}>{children}</View>
)
}
@@ -1,802 +0,0 @@
import * as Haptics from "expo-haptics"
import {
memo,
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react"
import {
FlatList,
Platform,
Pressable,
StyleSheet,
Text,
View,
type LayoutChangeEvent,
type StyleProp,
type ViewStyle,
} from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import Animated, {
useAnimatedStyle,
useSharedValue,
withDelay,
withTiming,
type SharedValue,
} from "react-native-reanimated"
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg"
import { scheduleOnRN } from "react-native-worklets"
import { CoverImage } from "@/components/cover-image"
import {
SwipeToRemoveRow,
useSwipeRowGroup,
type SwipeRowGroup,
} from "@/components/ios-swipe-to-remove-row"
import { PlayerSymbol } from "@/components/player-symbol"
import { usePlayback } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { NowPlayingColors } from "@/lib/now-playing-colors"
import { useSong } from "@/lib/song-cache"
import { albumCoverUrl } from "@/lib/urls"
export const QUEUE_HORIZONTAL_INSET = 26
const ROW_HEIGHT = 64
const HISTORY_HEADER_HEIGHT = 48
const CURRENT_HEIGHT = 92
const CONTROLS_HEIGHT = 108
const TOGGLES_ONLY_HEIGHT = 64
const BOTTOM_FADE_HEIGHT = 36
const DRAG_SETTLE = { duration: 180 }
const DRAG_HIGHLIGHT_Z_INDEX = 5
const TAP_HIGHLIGHT_DELAY_MS = 80
type QueueListItem =
| { type: "history-header"; key: string }
| { type: "history"; key: string; songId: Id<"songs">; historyIndex: number }
| { type: "current"; key: string }
| { type: "controls"; key: string; showTitle: boolean }
| { type: "upcoming"; key: string; songId: Id<"songs">; queueIndex: number }
| { type: "empty"; key: string; height: number }
function itemHeight(item: QueueListItem) {
switch (item.type) {
case "history-header":
return HISTORY_HEADER_HEIGHT
case "current":
return CURRENT_HEIGHT
case "controls":
return item.showTitle ? CONTROLS_HEIGHT : TOGGLES_ONLY_HEIGHT
case "empty":
return item.height
default:
return ROW_HEIGHT
}
}
type DragState = {
from: SharedValue<number>
to: SharedValue<number>
y: SharedValue<number>
/** Set once a drag is released so it settles and drops only once. */
dropping: SharedValue<boolean>
}
/**
* The queue shown in place of the artwork: history above (scrolled out of view
* at first), then the current song, the shuffle and repeat toggles, and the
* upcoming songs, which can be dragged to reorder or swiped away.
*/
export function NowPlayingQueue({
colors,
viewportHeight,
currentHeader,
}: {
colors: NowPlayingColors
viewportHeight: number
currentHeader: ReactNode
}) {
const {
queueSongIds,
queueHistorySongIds,
shuffleEnabled,
repeatEnabled,
toggleShuffle,
cycleRepeat,
clearHistory,
reorderQueue,
skipToQueueIndex,
skipToHistoryIndex,
} = usePlayback()
const swipeGroup = useSwipeRowGroup()
const [scrollEnabled, setScrollEnabled] = useState(true)
const dragFrom = useSharedValue(-1)
const dragTo = useSharedValue(-1)
const dragY = useSharedValue(0)
const dragDropping = useSharedValue(false)
const drag = useMemo<DragState>(
() => ({ from: dragFrom, to: dragTo, y: dragY, dropping: dragDropping }),
[dragDropping, dragFrom, dragTo, dragY]
)
const listRef = useRef<FlatList<QueueListItem>>(null)
const queueRef = useRef(queueSongIds)
queueRef.current = queueSongIds
const resetDragOnCommit = useRef(false)
const items = useMemo(() => {
const list: QueueListItem[] = []
if (queueHistorySongIds.length > 0) {
list.push({ type: "history-header", key: "history-header" })
queueHistorySongIds.forEach((songId, historyIndex) =>
list.push({
type: "history",
key: `history:${historyIndex}:${songId}`,
songId,
historyIndex,
})
)
}
list.push({ type: "current", key: "current" })
const hasUpcoming = queueSongIds.length > 1
list.push({ type: "controls", key: "controls", showTitle: hasUpcoming })
const occurrences = new Map<string, number>()
queueSongIds.forEach((songId, queueIndex) => {
const occurrence = occurrences.get(songId) ?? 0
occurrences.set(songId, occurrence + 1)
if (queueIndex === 0) return
list.push({
type: "upcoming",
key: `${songId}:${occurrence}`,
songId,
queueIndex,
})
})
if (!hasUpcoming) {
// Fills the rest of the page so the message sits in its middle.
list.push({
type: "empty",
key: "empty",
height: Math.max(
ROW_HEIGHT * 2,
viewportHeight - CURRENT_HEIGHT - TOGGLES_ONLY_HEIGHT
),
})
}
return list
}, [queueHistorySongIds, queueSongIds, viewportHeight])
const offsets = useMemo(() => {
const result: number[] = []
let offset = 0
for (const item of items) {
result.push(offset)
offset += itemHeight(item)
}
return result
}, [items])
const currentIndex = items.findIndex((item) => item.type === "current")
const controlsIndex = currentIndex + 1
const belowCurrentHeight = items
.slice(currentIndex)
.reduce((sum, item) => sum + itemHeight(item), 0)
// Lets the current song scroll to the top even when little is queued.
const footerHeight = Math.max(
BOTTOM_FADE_HEIGHT,
viewportHeight - belowCurrentHeight
)
// Keep the current song at the top as playback moves through the queue.
const currentSongId = queueSongIds[0]
const currentOffset = offsets[currentIndex] ?? 0
const scrolledSongId = useRef(currentSongId)
useEffect(() => {
if (scrolledSongId.current === currentSongId) return
scrolledSongId.current = currentSongId
listRef.current?.scrollToOffset({ offset: currentOffset, animated: true })
}, [currentOffset, currentSongId])
const getItemLayout = useCallback(
(data: ArrayLike<QueueListItem> | null | undefined, index: number) => ({
length: data ? itemHeight(data[index]) : ROW_HEIGHT,
offset: offsets[index] ?? 0,
index,
}),
[offsets]
)
const resetDrag = useCallback(() => {
drag.from.value = -1
drag.to.value = -1
drag.y.value = 0
drag.dropping.value = false
}, [drag])
useLayoutEffect(() => {
if (!resetDragOnCommit.current) return
resetDragOnCommit.current = false
resetDrag()
}, [queueSongIds, resetDrag])
const handleDragStart = useCallback(() => {
setScrollEnabled(false)
swipeGroup.closeOpenRow()
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium)
}, [swipeGroup])
const handleDrop = useCallback(
(songId: Id<"songs">, from: number, to: number) => {
setScrollEnabled(true)
const queue = queueRef.current
if (
from === to ||
queue[from] !== songId ||
to < 1 ||
to >= queue.length
) {
resetDrag()
return
}
const next = [...queue]
const [moved] = next.splice(from, 1)
next.splice(to, 0, moved)
resetDragOnCommit.current = true
void reorderQueue(next)
},
[reorderQueue, resetDrag]
)
const handleRemove = useCallback(
async (queueIndex: number) => {
const queue = queueRef.current
if (queueIndex < 1 || queueIndex >= queue.length) return false
await reorderQueue(queue.filter((_, index) => index !== queueIndex))
return true
},
[reorderQueue]
)
const CellRenderer = useMemo(
() =>
function QueueCell({
item,
style,
children,
onLayout,
}: {
item: QueueListItem
style: StyleProp<ViewStyle>
children: ReactNode
onLayout?: (event: LayoutChangeEvent) => void
}) {
const queueIndex = item.type === "upcoming" ? item.queueIndex : -1
const lift = useAnimatedStyle(() => ({
zIndex:
queueIndex > 0 && drag.from.value === queueIndex
? DRAG_HIGHLIGHT_Z_INDEX
: 0,
}))
return (
<Animated.View style={[style, lift]} onLayout={onLayout}>
{children}
</Animated.View>
)
},
[drag]
)
const renderItem = ({ item }: { item: QueueListItem }) => {
switch (item.type) {
case "history-header":
return (
<View style={styles.historyHeader}>
<Text style={[styles.sectionTitle, { color: colors.foreground }]}>
History
</Text>
<Pressable onPress={() => void clearHistory()} hitSlop={10}>
<Text
style={[styles.clear, { color: colors.secondaryForeground }]}
>
Clear
</Text>
</Pressable>
</View>
)
case "history":
return (
<HistoryRow
songId={item.songId}
historyIndex={item.historyIndex}
colors={colors}
onPress={skipToHistoryIndex}
/>
)
case "current":
return <View style={styles.current}>{currentHeader}</View>
case "controls":
return (
<View
style={[
styles.controls,
{
height: item.showTitle ? CONTROLS_HEIGHT : TOGGLES_ONLY_HEIGHT,
backgroundColor: colors.background,
},
]}
>
<View style={styles.toggles}>
<QueueToggle
colors={colors}
selected={shuffleEnabled}
label="Shuffle"
symbol="shuffle"
fallback="shuffle"
onPress={toggleShuffle}
/>
<QueueToggle
colors={colors}
selected={repeatEnabled !== "none"}
label={repeatEnabled === "once" ? "Repeat one" : "Repeat"}
symbol={repeatEnabled === "once" ? "repeat.1" : "repeat"}
fallback="repeat"
onPress={cycleRepeat}
/>
</View>
{item.showTitle ? (
<Text style={[styles.sectionTitle, { color: colors.foreground }]}>
Continue Playing
</Text>
) : null}
</View>
)
case "upcoming":
return (
<UpcomingRow
songId={item.songId}
queueIndex={item.queueIndex}
lastIndex={queueSongIds.length - 1}
colors={colors}
drag={drag}
swipeGroup={swipeGroup}
onPress={skipToQueueIndex}
onRemove={handleRemove}
onDragStart={handleDragStart}
onDrop={handleDrop}
/>
)
case "empty":
return (
<View style={[styles.empty, { height: item.height }]}>
<Text
style={[styles.emptyText, { color: colors.secondaryForeground }]}
>
Nothing else is queued.
</Text>
</View>
)
}
}
return (
<View style={styles.root}>
<FlatList
ref={listRef}
data={items}
keyExtractor={(item) => item.key}
renderItem={renderItem}
getItemLayout={getItemLayout}
CellRendererComponent={CellRenderer}
initialScrollIndex={currentIndex}
stickyHeaderIndices={[controlsIndex]}
scrollEnabled={scrollEnabled}
onScrollBeginDrag={swipeGroup.closeOpenRow}
showsVerticalScrollIndicator={false}
initialNumToRender={16}
maxToRenderPerBatch={10}
windowSize={9}
ListFooterComponent={<View style={{ height: footerHeight }} />}
/>
<Svg
pointerEvents="none"
style={styles.bottomFade}
width="100%"
height={BOTTOM_FADE_HEIGHT}
>
<Defs>
<LinearGradient id="queue-fade" x1="0" y1="0" x2="0" y2="1">
<Stop offset="0" stopColor={colors.background} stopOpacity={0} />
<Stop offset="1" stopColor={colors.background} stopOpacity={1} />
</LinearGradient>
</Defs>
<Rect width="100%" height="100%" fill="url(#queue-fade)" />
</Svg>
</View>
)
}
function QueueToggle({
colors,
selected,
label,
symbol,
fallback,
onPress,
}: {
colors: NowPlayingColors
selected: boolean
label: string
symbol: "shuffle" | "repeat" | "repeat.1"
fallback: "shuffle" | "repeat"
onPress: () => Promise<void>
}) {
return (
<Pressable
accessibilityRole="switch"
accessibilityLabel={label}
accessibilityState={{ checked: selected }}
onPress={() => {
void Haptics.selectionAsync()
void onPress()
}}
style={({ pressed }) => [
styles.toggle,
{
backgroundColor: selected ? colors.selected : colors.control,
opacity: pressed ? 0.7 : 1,
},
]}
>
<PlayerSymbol
name={symbol}
fallback={fallback}
size={24}
weight="semibold"
color={selected ? colors.selectedForeground : colors.foreground}
/>
</Pressable>
)
}
function QueueSongContent({
songId,
colors,
trailing,
}: {
songId: Id<"songs">
colors: NowPlayingColors
trailing?: ReactNode
}) {
const { config } = useServerConfig()
const song = useSong(songId)
return (
<View style={styles.row}>
<CoverImage
uri={
song && config ? albumCoverUrl(config.serverUrl, song.album.id) : ""
}
hasCover={song ? song.album.cover != null : false}
style={styles.rowArtwork}
/>
<View style={styles.rowMeta}>
<Text
style={[styles.rowTitle, { color: colors.foreground }]}
numberOfLines={1}
>
{song?.title ?? " "}
</Text>
<Text
style={[styles.rowSubtitle, { color: colors.secondaryForeground }]}
numberOfLines={1}
>
{song?.artist.name ?? " "}
</Text>
</View>
{trailing}
</View>
)
}
/**
* A row tap that takes part in gesture arbitration, so swiping the row or
* dragging its handle cancels it. A `Pressable` would still fire, since the row
* moves with the finger.
*/
function RowTap({
colors,
onPress,
children,
}: {
colors: NowPlayingColors
onPress: () => void
children: ReactNode
}) {
const pressed = useSharedValue(0)
const tap = useMemo(
() =>
Gesture.Tap()
.maxDistance(10)
.onBegin(() => {
pressed.value = withDelay(
TAP_HIGHLIGHT_DELAY_MS,
withTiming(1, { duration: 0 })
)
})
.onEnd((_event, success) => {
if (success) scheduleOnRN(onPress)
})
.onFinalize(() => {
pressed.value = withTiming(0, { duration: 150 })
}),
[onPress, pressed]
)
const highlightStyle = useAnimatedStyle(() => ({ opacity: pressed.value }))
return (
<GestureDetector gesture={tap}>
<View accessible accessibilityRole="button" onAccessibilityTap={onPress}>
{children}
<Animated.View
pointerEvents="none"
style={[
StyleSheet.absoluteFill,
{ backgroundColor: colors.highlight },
highlightStyle,
]}
/>
</View>
</GestureDetector>
)
}
const HistoryRow = memo(function HistoryRow({
songId,
historyIndex,
colors,
onPress,
}: {
songId: Id<"songs">
historyIndex: number
colors: NowPlayingColors
onPress: (historyIndex: number) => Promise<void>
}) {
const handlePress = useCallback(
() => void onPress(historyIndex),
[historyIndex, onPress]
)
return (
<RowTap colors={colors} onPress={handlePress}>
<QueueSongContent songId={songId} colors={colors} />
</RowTap>
)
})
const UpcomingRow = memo(function UpcomingRow({
songId,
queueIndex,
lastIndex,
colors,
drag,
swipeGroup,
onPress,
onRemove,
onDragStart,
onDrop,
}: {
songId: Id<"songs">
queueIndex: number
lastIndex: number
colors: NowPlayingColors
drag: DragState
swipeGroup: SwipeRowGroup
onPress: (queueIndex: number) => Promise<void>
onRemove: (queueIndex: number) => Promise<boolean>
onDragStart: () => void
onDrop: (songId: Id<"songs">, from: number, to: number) => void
}) {
const handlePan = useMemo(() => {
const tick = () => void Haptics.selectionAsync()
return Gesture.Pan()
.minDistance(0)
.shouldCancelWhenOutside(false)
.onStart(() => {
if (drag.dropping.value) return
drag.from.value = queueIndex
drag.to.value = queueIndex
drag.y.value = 0
scheduleOnRN(onDragStart)
})
.onUpdate((event) => {
if (drag.from.value !== queueIndex || drag.dropping.value) return
drag.y.value = event.translationY
const to = Math.min(
lastIndex,
Math.max(1, Math.round(queueIndex + event.translationY / ROW_HEIGHT))
)
if (to !== drag.to.value) {
drag.to.value = to
scheduleOnRN(tick)
}
})
.onFinalize(() => {
if (drag.from.value !== queueIndex || drag.dropping.value) return
drag.dropping.value = true
const to = drag.to.value
drag.y.value = withTiming(
(to - queueIndex) * ROW_HEIGHT,
DRAG_SETTLE,
() => scheduleOnRN(onDrop, songId, queueIndex, to)
)
})
}, [drag, lastIndex, onDragStart, onDrop, queueIndex, songId])
const shiftStyle = useAnimatedStyle(() => {
const from = drag.from.value
if (from < 0) return { transform: [{ translateY: 0 }] }
if (from === queueIndex) {
return { transform: [{ translateY: drag.y.value }] }
}
const to = drag.to.value
let shift = 0
if (from < to && queueIndex > from && queueIndex <= to) shift = -ROW_HEIGHT
if (from > to && queueIndex < from && queueIndex >= to) shift = ROW_HEIGHT
return { transform: [{ translateY: withTiming(shift, DRAG_SETTLE) }] }
})
const liftStyle = useAnimatedStyle(() => ({
opacity: withTiming(drag.from.value === queueIndex ? 1 : 0, DRAG_SETTLE),
}))
const handleRemove = useCallback(
() => onRemove(queueIndex),
[onRemove, queueIndex]
)
const handlePress = useCallback(
() => void onPress(queueIndex),
[onPress, queueIndex]
)
const content = (
<RowTap colors={colors} onPress={handlePress}>
<QueueSongContent
songId={songId}
colors={colors}
trailing={
<GestureDetector gesture={handlePan}>
<View
style={styles.handle}
accessibilityLabel="Reorder"
accessibilityHint="Drag to move this song in the queue"
>
<PlayerSymbol
name="line.3.horizontal"
fallback="reorder-three"
size={20}
color={colors.secondaryForeground}
/>
</View>
</GestureDetector>
}
/>
<Animated.View
pointerEvents="none"
style={[
StyleSheet.absoluteFill,
{ backgroundColor: colors.highlight },
liftStyle,
]}
/>
</RowTap>
)
return (
<Animated.View style={shiftStyle}>
{Platform.OS === "ios" ? (
<SwipeToRemoveRow
group={swipeGroup}
backgroundColor={colors.background}
actionAccessibilityLabel="Remove from queue"
onRemove={handleRemove}
>
{content}
</SwipeToRemoveRow>
) : (
<View style={{ backgroundColor: colors.background }}>{content}</View>
)}
</Animated.View>
)
})
const styles = StyleSheet.create({
root: {
flex: 1,
},
historyHeader: {
height: HISTORY_HEADER_HEIGHT,
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingHorizontal: QUEUE_HORIZONTAL_INSET,
},
sectionTitle: {
fontSize: 17,
fontWeight: "700",
},
clear: {
fontSize: 17,
},
current: {
height: CURRENT_HEIGHT,
justifyContent: "center",
paddingHorizontal: QUEUE_HORIZONTAL_INSET,
},
controls: {
justifyContent: "center",
gap: 18,
paddingHorizontal: QUEUE_HORIZONTAL_INSET,
},
toggles: {
flexDirection: "row",
gap: 12,
},
toggle: {
flex: 1,
height: 36,
borderRadius: 18,
alignItems: "center",
justifyContent: "center",
},
row: {
height: ROW_HEIGHT,
flexDirection: "row",
alignItems: "center",
gap: 14,
paddingLeft: QUEUE_HORIZONTAL_INSET,
paddingRight: QUEUE_HORIZONTAL_INSET - 10,
},
rowArtwork: {
width: 48,
height: 48,
borderRadius: 6,
},
rowMeta: {
flex: 1,
minWidth: 0,
},
rowTitle: {
fontSize: 16,
},
rowSubtitle: {
fontSize: 14,
marginTop: 2,
},
handle: {
width: 44,
height: ROW_HEIGHT,
alignItems: "center",
justifyContent: "center",
},
empty: {
alignItems: "center",
justifyContent: "center",
paddingHorizontal: QUEUE_HORIZONTAL_INSET,
},
emptyText: {
fontSize: 20,
fontWeight: "600",
textAlign: "center",
},
bottomFade: {
position: "absolute",
left: 0,
right: 0,
bottom: 0,
},
})
-207
View File
@@ -1,207 +0,0 @@
import { useEffect, useMemo, useRef, type ReactNode } from "react"
import { StyleSheet, View } from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import Animated, {
cancelAnimation,
interpolate,
interpolateColor,
useAnimatedStyle,
useSharedValue,
withSpring,
withTiming,
} from "react-native-reanimated"
import { scheduleOnRN } from "react-native-worklets"
const IDLE_HEIGHT = 7
const ACTIVE_HEIGHT = 13
const TOUCH_HEIGHT = 36
const ACTIVE_STRETCH = 1.03
// Playback position lags a seek; hold the committed value until it catches up.
const COMMIT_HOLD_MS = 800
/**
* A thumbless bar that thickens while touched. Drags move the value relative to
* where the finger started rather than jumping to the touch point.
*/
export function PlayerSlider({
value,
maximumValue,
fillColor,
activeFillColor,
trackColor,
onValueChange,
onSlidingStart,
onSlidingComplete,
leading,
trailing,
accessibilityLabel,
commitHoldMs = COMMIT_HOLD_MS,
animateValueChanges = false,
}: {
value: number
maximumValue: number
fillColor: string
activeFillColor: string
trackColor: string
onValueChange?: (value: number) => void
onSlidingStart?: () => void
onSlidingComplete?: (value: number) => void
leading?: ReactNode
trailing?: ReactNode
accessibilityLabel: string
animateValueChanges?: boolean
/** Seeking needs a hold while playback catches up; system volume does not. */
commitHoldMs?: number
}) {
const max = maximumValue > 0 ? maximumValue : 1
const fraction = useSharedValue(clamp(value / max))
const startFraction = useSharedValue(0)
const width = useSharedValue(0)
const active = useSharedValue(0)
const dragging = useSharedValue(false)
const holdUntil = useRef(0)
useEffect(() => {
if (dragging.value || Date.now() < holdUntil.current) return
const next = clamp(value / max)
fraction.value = animateValueChanges
? withTiming(next, { duration: 160 })
: next
}, [animateValueChanges, dragging, fraction, max, value])
const callbacks = useRef({
onValueChange,
onSlidingStart,
onSlidingComplete,
value,
commitHoldMs,
max,
})
callbacks.current = {
onValueChange,
onSlidingStart,
onSlidingComplete,
value,
commitHoldMs,
max,
}
const gesture = useMemo(() => {
const start = () => callbacks.current.onSlidingStart?.()
const change = (next: number) =>
callbacks.current.onValueChange?.(next * callbacks.current.max)
const complete = (next: number) => {
holdUntil.current = Date.now() + callbacks.current.commitHoldMs
if (callbacks.current.commitHoldMs === 0) {
fraction.value = clamp(callbacks.current.value / callbacks.current.max)
}
callbacks.current.onSlidingComplete?.(next * callbacks.current.max)
}
return Gesture.Pan()
.activeOffsetX([-2, 2])
.failOffsetY([-24, 24])
.shouldCancelWhenOutside(false)
.onBegin(() => {
active.value = withSpring(1, { duration: 250, dampingRatio: 0.8 })
})
.onStart(() => {
cancelAnimation(fraction)
dragging.value = true
startFraction.value = fraction.value
scheduleOnRN(start)
})
.onUpdate((event) => {
if (width.value <= 0) return
const next = Math.min(
1,
Math.max(0, startFraction.value + event.translationX / width.value)
)
fraction.value = next
scheduleOnRN(change, next)
})
.onEnd(() => {
scheduleOnRN(complete, fraction.value)
})
.onFinalize(() => {
dragging.value = false
active.value = withTiming(0, { duration: 250 })
})
}, [active, dragging, fraction, startFraction, width])
const trackStyle = useAnimatedStyle(() => {
const height = interpolate(
active.value,
[0, 1],
[IDLE_HEIGHT, ACTIVE_HEIGHT]
)
return {
height,
borderRadius: height / 2,
transform: [
{ scaleX: interpolate(active.value, [0, 1], [1, ACTIVE_STRETCH]) },
],
}
})
const fillStyle = useAnimatedStyle(() => ({
width: `${fraction.value * 100}%`,
backgroundColor: interpolateColor(
active.value,
[0, 1],
[fillColor, activeFillColor]
),
}))
return (
<View style={styles.row}>
{leading}
<GestureDetector gesture={gesture}>
<View
style={styles.touchArea}
onLayout={(event) => {
width.value = event.nativeEvent.layout.width
}}
accessible
accessibilityRole="adjustable"
accessibilityLabel={accessibilityLabel}
accessibilityValue={{
min: 0,
max: Math.round(max),
now: Math.round(value),
}}
>
<Animated.View
style={[styles.track, { backgroundColor: trackColor }, trackStyle]}
>
<Animated.View style={[styles.fill, fillStyle]} />
</Animated.View>
</View>
</GestureDetector>
{trailing}
</View>
)
}
function clamp(fraction: number) {
return Number.isFinite(fraction) ? Math.min(1, Math.max(0, fraction)) : 0
}
const styles = StyleSheet.create({
row: {
flexDirection: "row",
alignItems: "center",
gap: 10,
},
touchArea: {
flex: 1,
height: TOUCH_HEIGHT,
justifyContent: "center",
},
track: {
overflow: "hidden",
},
fill: {
height: "100%",
},
})
-32
View File
@@ -1,32 +0,0 @@
import { Ionicons, MaterialIcons } from "@expo/vector-icons"
import { SymbolView, type SFSymbol } from "expo-symbols"
import { Platform } from "react-native"
type Fallback =
| keyof typeof Ionicons.glyphMap
| { material: keyof typeof MaterialIcons.glyphMap }
/** An SF Symbol on iOS, or the closest Ionicon or Material icon elsewhere. */
export function PlayerSymbol({
name,
fallback,
size,
color,
weight = "regular",
}: {
name: SFSymbol
fallback: Fallback
size: number
color: string
weight?: "regular" | "medium" | "semibold" | "bold"
}) {
if (Platform.OS === "ios") {
return (
<SymbolView name={name} size={size} tintColor={color} weight={weight} />
)
}
if (typeof fallback === "object") {
return <MaterialIcons name={fallback.material} size={size} color={color} />
}
return <Ionicons name={fallback} size={size} color={color} />
}
+20 -73
View File
@@ -1,5 +1,3 @@
import { MusicEntityView } from "@/components/music-entity-view"
import { collectionInset } from "@/components/collection-list"
import { CoverImage } from "@/components/cover-image"
import { useServerConfig } from "@/contexts/server-config"
import type { BrowseSong } from "@otunes/convex/types"
@@ -8,7 +6,7 @@ import { formatDuration } from "@/lib/format"
import { albumCoverUrl } from "@/lib/urls"
import { miniPlayerHeight, spacing, useThemeColors } from "@/lib/theme"
import { memo, useCallback } from "react"
import { Platform, Pressable, StyleSheet, Text, View } from "react-native"
import { Pressable, StyleSheet, Text, View } from "react-native"
import {
MediaContextMenu,
@@ -22,7 +20,6 @@ export const SongRow = memo(function SongRow({
contextMenu,
trailing,
palette,
inset = false,
}: {
song: BrowseSong
onPress?: () => void
@@ -31,8 +28,6 @@ export const SongRow = memo(function SongRow({
}
trailing?: React.ReactNode
palette?: Pick<CoverPalette, "foreground" | "secondaryForeground" | "divider">
/** Album/playlist layout: the divider starts at the title, not the artwork. */
inset?: boolean
}) {
const { config } = useServerConfig()
const colors = useThemeColors()
@@ -41,36 +36,13 @@ export const SongRow = memo(function SongRow({
const foreground = palette?.foreground ?? colors.foreground
const secondaryForeground =
palette?.secondaryForeground ?? colors.mutedForeground
const divider = palette?.divider ?? colors.border
const content = (
<>
<View style={styles.rowMeta}>
<Text
style={[styles.rowTitle, { color: foreground }]}
numberOfLines={1}
>
{song.title}
</Text>
<Text
style={[styles.rowSubtitle, { color: secondaryForeground }]}
numberOfLines={1}
>
{song.artist.name} · {song.album.title}
</Text>
</View>
<Text style={[styles.duration, { color: secondaryForeground }]}>
{formatDuration(song.durationSeconds)}
</Text>
{trailing}
</>
)
const row = (
<Pressable
style={
inset ? styles.insetRow : [styles.row, { borderBottomColor: divider }]
}
style={[
styles.row,
{ borderBottomColor: palette?.divider ?? colors.border },
]}
onPress={onPress}
>
<CoverImage
@@ -78,29 +50,28 @@ export const SongRow = memo(function SongRow({
hasCover={song.album.cover != null}
style={styles.rowArtwork}
/>
{inset ? (
<View style={[styles.insetContent, { borderBottomColor: divider }]}>
{content}
</View>
) : (
content
)}
<View style={styles.rowMeta}>
<Text style={[styles.rowTitle, { color: foreground }]} numberOfLines={1}>
{song.title}
</Text>
<Text style={[styles.rowSubtitle, { color: secondaryForeground }]} numberOfLines={1}>
{song.artist.name} · {song.album.title}
</Text>
</View>
<Text style={[styles.duration, { color: secondaryForeground }]}>
{formatDuration(song.durationSeconds)}
</Text>
{trailing}
</Pressable>
)
if (!contextMenu) {
return (
<MusicEntityView kind="song" id={song.id}>
{row}
</MusicEntityView>
)
return row
}
return (
<MediaContextMenu {...contextMenu}>
<MusicEntityView kind="song" id={song.id}>
{row}
</MusicEntityView>
{row}
</MediaContextMenu>
)
})
@@ -115,7 +86,6 @@ export const SongListRow = memo(function SongListRow({
favorited,
playlistLabel,
palette,
inset,
onPlay,
onAction,
}: {
@@ -123,7 +93,6 @@ export const SongListRow = memo(function SongListRow({
favorited: boolean
playlistLabel?: string
palette?: Pick<CoverPalette, "foreground" | "secondaryForeground" | "divider">
inset?: boolean
onPlay: (song: BrowseSong) => void
onAction: (song: BrowseSong, action: MediaAction) => void
}) {
@@ -133,10 +102,8 @@ export const SongListRow = memo(function SongListRow({
<SongRow
song={song}
palette={palette}
inset={inset}
onPress={handlePress}
contextMenu={{
stationArtistId: song.artist.id,
favorited,
playlistLabel,
navigation: {
@@ -147,7 +114,6 @@ export const SongListRow = memo(function SongListRow({
type: "song",
albumId: song.album.id,
songId: song.id,
title: `${song.title} - ${song.album.title}`,
},
onAction: (action) => onAction(song, action),
}}
@@ -156,8 +122,7 @@ export const SongListRow = memo(function SongListRow({
})
export const tabContentBottomInset = spacing.lg
export const contentBottomInset =
Platform.OS === "android" ? spacing.lg : miniPlayerHeight + spacing.lg
export const contentBottomInset = miniPlayerHeight + spacing.lg
const styles = StyleSheet.create({
row: {
@@ -169,24 +134,6 @@ const styles = StyleSheet.create({
paddingHorizontal: spacing.lg,
borderBottomWidth: StyleSheet.hairlineWidth,
},
insetRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
paddingLeft: collectionInset,
},
insetContent: {
flex: 1,
minWidth: 0,
flexDirection: "row",
alignItems: "center",
alignSelf: "stretch",
gap: spacing.md,
minHeight: 64,
paddingVertical: 10,
marginRight: collectionInset,
borderBottomWidth: StyleSheet.hairlineWidth,
},
rowArtwork: {
width: 44,
height: 44,
@@ -1,56 +0,0 @@
import { useCallback, useMemo } from "react"
import { Platform } from "react-native"
import { Stack } from "expo-router"
import { useDebouncedSearch } from "@/hooks/use-debounced-search"
import { useThemeColors } from "@/lib/theme"
import type { BrowseSong } from "@otunes/convex/types"
export function usePlaylistSearch(songs: BrowseSong[]) {
const search = useDebouncedSearch()
const filteredSongs = useMemo(() => {
const query = search.searchQuery.toLowerCase()
if (!query) return songs
return songs.filter((song) =>
[song.title, song.artist.name, song.album.title].some((value) =>
value.toLowerCase().includes(query)
)
)
}, [songs, search.searchQuery])
return { ...search, filteredSongs }
}
export function PlaylistSearchBar({
onQueryChange,
onSearchSubmit,
}: Pick<
ReturnType<typeof useDebouncedSearch>,
"onQueryChange" | "onSearchSubmit"
>) {
const colors = useThemeColors()
const handleChangeText = useCallback(
(event: { nativeEvent: { text: string } }) => {
onQueryChange(event.nativeEvent.text)
},
[onQueryChange]
)
return (
<Stack.SearchBar
placeholder="Search playlist"
onChangeText={handleChangeText}
onSearchButtonPress={onSearchSubmit}
autoCapitalize="none"
{...(Platform.OS === "android"
? {
barTintColor: colors.background,
textColor: colors.foreground,
tintColor: colors.primary,
hintTextColor: colors.mutedForeground,
headerIconColor: colors.foreground,
}
: {})}
/>
)
}
+1 -1
View File
@@ -122,7 +122,7 @@ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
<View style={styles.section}>
<ContentCarousel title="Playlists" content={playlistResults} />
</View>
) : undefined
) : null
}
/>
)
+33 -71
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, type ReactNode } from "react"
import { useEffect, useRef } from "react"
import {
Animated,
ScrollView,
@@ -18,30 +18,6 @@ import {
useTwoColumnCardWidth,
} from "@/lib/theme"
/** Match the inset-adjusted lists used once screen data is available. */
function SkeletonContent({
children,
embedded = false,
}: {
children: ReactNode
embedded?: boolean
}) {
const colors = useThemeColors()
if (embedded) return <>{children}</>
return (
<ScrollView
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
scrollEnabled={false}
accessibilityLabel="Loading"
>
{children}
</ScrollView>
)
}
export function Skeleton({ style }: { style?: StyleProp<ViewStyle> }) {
const colors = useThemeColors()
const opacity = useRef(new Animated.Value(1)).current
@@ -98,21 +74,13 @@ export function SongRowSkeleton() {
)
}
export function SongListSkeleton({
rows = 10,
embedded = false,
}: {
rows?: number
embedded?: boolean
}) {
export function SongListSkeleton({ rows = 10 }: { rows?: number }) {
return (
<SkeletonContent embedded={embedded}>
<View accessibilityLabel="Loading" accessibilityRole="progressbar">
{Array.from({ length: rows }, (_, index) => (
<SongRowSkeleton key={index} />
))}
</View>
</SkeletonContent>
<View accessibilityLabel="Loading" accessibilityRole="progressbar">
{Array.from({ length: rows }, (_, index) => (
<SongRowSkeleton key={index} />
))}
</View>
)
}
@@ -141,28 +109,24 @@ function CardSkeleton({
export function MediaGridSkeleton({
items = 6,
contentInset = true,
embedded = false,
}: {
items?: number
contentInset?: boolean
embedded?: boolean
}) {
const cardWidth = useTwoColumnCardWidth()
return (
<SkeletonContent embedded={embedded}>
<View
accessibilityLabel="Loading"
accessibilityRole="progressbar"
style={[
styles.grid,
contentInset ? styles.gridInset : styles.gridRowInset,
]}
>
{Array.from({ length: items }, (_, index) => (
<CardSkeleton key={index} width={cardWidth} />
))}
</View>
</SkeletonContent>
<View
accessibilityLabel="Loading"
accessibilityRole="progressbar"
style={[
styles.grid,
contentInset ? styles.gridInset : styles.gridRowInset,
]}
>
{Array.from({ length: items }, (_, index) => (
<CardSkeleton key={index} width={cardWidth} />
))}
</View>
)
}
@@ -228,9 +192,9 @@ export function CollectionDetailSkeleton({
</View>
</View>
{round ? (
<MediaGridSkeleton items={4} contentInset={false} embedded />
<MediaGridSkeleton items={4} contentInset={false} />
) : (
<SongListSkeleton rows={8} embedded />
<SongListSkeleton rows={8} />
)}
</ScrollView>
)
@@ -239,19 +203,17 @@ export function CollectionDetailSkeleton({
export function ArtistListSkeleton({ rows = 12 }: { rows?: number }) {
const colors = useThemeColors()
return (
<SkeletonContent>
<View accessibilityLabel="Loading" accessibilityRole="progressbar">
{Array.from({ length: rows }, (_, index) => (
<View
key={index}
style={[styles.artistRow, { borderBottomColor: colors.border }]}
>
<Skeleton style={styles.artistAvatar} />
<TextLine width="50%" height={16} />
</View>
))}
</View>
</SkeletonContent>
<View accessibilityLabel="Loading" accessibilityRole="progressbar">
{Array.from({ length: rows }, (_, index) => (
<View
key={index}
style={[styles.artistRow, { borderBottomColor: colors.border }]}
>
<Skeleton style={styles.artistAvatar} />
<TextLine width="50%" height={16} />
</View>
))}
</View>
)
}
@@ -271,7 +233,7 @@ const styles = StyleSheet.create({
grid: { flexDirection: "row", flexWrap: "wrap", gap: spacing.md },
gridInset: { padding: spacing.lg },
gridRowInset: { paddingHorizontal: spacing.lg },
carousel: { gap: spacing.md, overflow: "hidden" },
carousel: { gap: spacing.md },
carouselRow: { flexDirection: "row", gap: spacing.md },
home: { padding: spacing.lg, gap: spacing.xl },
hero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm },
+1 -14
View File
@@ -1,6 +1,5 @@
import {
ActivityIndicator,
Platform,
Pressable,
PressableProps,
StyleProp,
@@ -86,13 +85,6 @@ export function Input({ style, ...props }: TextInputProps) {
return (
<TextInput
{...props}
{...(Platform.OS === "android"
? {
selectionColor: colors.primary,
cursorColor: colors.primary,
selectionHandleColor: colors.primary,
}
: {})}
placeholderTextColor={colors.mutedForeground}
style={[
styles.input,
@@ -110,12 +102,7 @@ export function Input({ style, ...props }: TextInputProps) {
export function Card({ children }: { children: React.ReactNode }) {
const colors = useThemeColors()
return (
<View
style={[
styles.card,
{ backgroundColor: colors.card, borderColor: colors.border },
]}
>
<View style={[styles.card, { backgroundColor: colors.card, borderColor: colors.border }]}>
{children}
</View>
)
+5 -4
View File
@@ -1,15 +1,16 @@
import { Toaster as SonnerToaster } from "sonner-native"
import { useColorScheme } from "react-native"
import { radius, useIsDark, useThemeColors } from "@/lib/theme"
import { colors, radius } from "@/lib/theme"
export function Toaster() {
const isDark = useIsDark()
const themeColors = useThemeColors()
const scheme = useColorScheme()
const themeColors = scheme === "dark" ? colors.dark : colors.light
return (
<SonnerToaster
position="top-center"
theme={isDark ? "dark" : "light"}
theme={scheme === "dark" ? "dark" : "light"}
toastOptions={{
style: {
backgroundColor: themeColors.card,
+89 -82
View File
@@ -1,4 +1,3 @@
import { AndroidSheet } from "@/components/android-sheet"
import { useConvex, useMutation } from "convex/react"
import {
createContext,
@@ -26,8 +25,8 @@ import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
import { api } from "@otunes/convex/_generated/api"
import type { OwnedPlaylistForAdd } from "@otunes/convex/types"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { showError, showSuccess } from "@/lib/toast"
import { useAppNavigation } from "@/lib/app-navigation"
import { showError } from "@/lib/toast"
import { useThemeColors } from "@/lib/theme"
type AddToPlaylistContextValue = {
@@ -170,17 +169,27 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
}, [])
const handleAddToPlaylist = useCallback(
async (playlistId: Id<"playlists">, existing: Id<"songs">[]) => {
async (
playlistId: Id<"playlists">,
title: string,
existing: Id<"songs">[]
) => {
if (addingToPlaylistId) return
const existingSet = new Set(existing)
const toAdd = pendingSongIds.filter((id) => !existingSet.has(id))
if (toAdd.length === 0) {
showSuccess(`All selected songs are already in ${title}`)
closeAddToPlaylist()
return
}
setAddingToPlaylistId(playlistId)
try {
await addSongs({ playlistId, songIds: toAdd })
showSuccess(
toAdd.length > 1
? `Added ${toAdd.length} songs to ${title}`
: `Added to ${title}`
)
closeAddToPlaylist()
} catch (error) {
showError(
@@ -202,6 +211,7 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
name,
songIds: pendingSongIds,
})
showSuccess("Playlist created")
setCreateOpen(false)
closeAddToPlaylist()
push(`/playlist/${playlistId}`)
@@ -247,53 +257,55 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
transparent
onRequestClose={closeAddToPlaylist}
>
<AndroidSheet>
<Pressable style={styles.overlay} onPress={closeAddToPlaylist}>
<Pressable
style={[
styles.sheet,
{ backgroundColor: colors.card, borderColor: colors.border },
]}
onPress={(event) => event.stopPropagation()}
>
<Text style={[styles.title, { color: colors.foreground }]}>
Add to Playlist
</Text>
<FlatList
style={styles.list}
data={ownedPlaylists ?? []}
keyExtractor={(playlist) => playlist.id}
renderItem={({
item: playlist,
}: {
item: OwnedPlaylistForAdd
}) => (
<Pressable
style={[styles.row, { borderBottomColor: colors.border }]}
disabled={addingToPlaylistId !== null}
onPress={() =>
void handleAddToPlaylist(playlist.id, playlist.songIds)
}
>
<Text style={{ color: colors.foreground }}>
{playlist.title}
</Text>
</Pressable>
)}
/>
<Button
title="New Playlist"
variant="secondary"
onPress={() => {
selectionRequestIdRef.current += 1
setOpen(false)
setNewPlaylistName("")
setCreateOpen(true)
}}
/>
</Pressable>
<Pressable style={styles.overlay} onPress={closeAddToPlaylist}>
<Pressable
style={[
styles.sheet,
{ backgroundColor: colors.card, borderColor: colors.border },
]}
onPress={(event) => event.stopPropagation()}
>
<Text style={[styles.title, { color: colors.foreground }]}>
Add to Playlist
</Text>
<FlatList
style={styles.list}
data={ownedPlaylists ?? []}
keyExtractor={(playlist) => playlist.id}
renderItem={({
item: playlist,
}: {
item: OwnedPlaylistForAdd
}) => (
<Pressable
style={styles.row}
disabled={addingToPlaylistId !== null}
onPress={() =>
void handleAddToPlaylist(
playlist.id,
playlist.title,
playlist.songIds
)
}
>
<Text style={{ color: colors.foreground }}>
{playlist.title}
</Text>
</Pressable>
)}
/>
<Button
title="New Playlist"
variant="secondary"
onPress={() => {
selectionRequestIdRef.current += 1
setOpen(false)
setNewPlaylistName("")
setCreateOpen(true)
}}
/>
</Pressable>
</AndroidSheet>
</Pressable>
</Modal>
<Modal
@@ -302,43 +314,38 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
transparent
onRequestClose={() => setCreateOpen(false)}
>
<AndroidSheet>
<Pressable style={styles.overlay} onPress={() => setCreateOpen(false)}>
<Pressable
style={styles.overlay}
onPress={() => setCreateOpen(false)}
style={[
styles.createSheet,
{ backgroundColor: colors.card, borderColor: colors.border },
]}
onPress={(event) => event.stopPropagation()}
>
<Pressable
style={[
styles.createSheet,
{ backgroundColor: colors.card, borderColor: colors.border },
]}
onPress={(event) => event.stopPropagation()}
>
<Text style={[styles.title, { color: colors.foreground }]}>
New Playlist
</Text>
<Input
value={newPlaylistName}
onChangeText={setNewPlaylistName}
placeholder="Playlist name"
autoFocus
<Text style={[styles.title, { color: colors.foreground }]}>
New Playlist
</Text>
<Input
value={newPlaylistName}
onChangeText={setNewPlaylistName}
placeholder="Playlist name"
autoFocus
/>
<View style={styles.createActions}>
<Button
title="Cancel"
variant="ghost"
onPress={() => setCreateOpen(false)}
/>
<View style={styles.createActions}>
<Button
title="Cancel"
variant="ghost"
onPress={() => setCreateOpen(false)}
/>
<Button
title="Create"
loading={submitting}
disabled={!newPlaylistName.trim()}
onPress={() => void handleCreatePlaylist()}
/>
</View>
</Pressable>
<Button
title="Create"
loading={submitting}
disabled={!newPlaylistName.trim()}
onPress={() => void handleCreatePlaylist()}
/>
</View>
</Pressable>
</AndroidSheet>
</Pressable>
</Modal>
</AddToPlaylistContext.Provider>
)
-137
View File
@@ -1,137 +0,0 @@
import {
useIsFocused,
useNavigation,
usePreventRemove,
useRoute,
type NativeStackNavigationProp,
} from "expo-router"
import {
createContext,
useCallback,
useContext,
useLayoutEffect,
useMemo,
useState,
type PropsWithChildren,
} from "react"
import { Platform } from "react-native"
import { themeCoverPalette, type CoverPalette } from "@/lib/cover-palette"
import { useIsDark, useThemeColors } from "@/lib/theme"
type TabTheme = {
palette: CoverPalette
selectedColor: string
hasArtworkPalette: boolean
setPalette: (palette: CoverPalette | null, owner: string) => void
}
const AndroidTabTheme = createContext<TabTheme | null>(null)
function useDefaultPalette() {
const theme = useThemeColors()
const isDark = useIsDark()
return useMemo(() => themeCoverPalette(theme, isDark), [theme, isDark])
}
export function AndroidTabThemeProvider({ children }: PropsWithChildren) {
const defaultPalette = useDefaultPalette()
const [screen, setScreen] = useState<{
palette: CoverPalette
owner: string
} | null>(null)
const palette = screen?.palette ?? null
const setPalette = useCallback(
(palette: CoverPalette | null, owner: string) => {
setScreen((current) =>
palette ? { palette, owner } : current?.owner === owner ? null : current
)
},
[]
)
const artworkPalette =
palette &&
(palette.background !== defaultPalette.background ||
palette.foreground !== defaultPalette.foreground ||
palette.secondaryForeground !== defaultPalette.secondaryForeground ||
palette.accent !== defaultPalette.accent)
? palette
: null
const value = useMemo(
() => ({
palette: artworkPalette ?? defaultPalette,
selectedColor: artworkPalette?.foreground ?? defaultPalette.accentText,
hasArtworkPalette: artworkPalette !== null,
setPalette,
}),
[defaultPalette, artworkPalette, setPalette]
)
return (
<AndroidTabTheme.Provider value={value}>
{children}
</AndroidTabTheme.Provider>
)
}
export function useAndroidTabPalette() {
const theme = useContext(AndroidTabTheme)
const defaultPalette = useDefaultPalette()
return theme?.palette ?? defaultPalette
}
export function useAndroidTabHasArtworkPalette() {
return useContext(AndroidTabTheme)?.hasArtworkPalette ?? false
}
export function useAndroidTabSelectedColor() {
const theme = useContext(AndroidTabTheme)
const defaultPalette = useDefaultPalette()
return theme?.selectedColor ?? defaultPalette.accentText
}
/** Keep Android artwork screens and shared bars on the same displayed palette. */
export function useAndroidScreenPalette(palette: CoverPalette) {
const isFocused = useIsFocused()
const owner = useRoute().key
const navigation =
useNavigation<NativeStackNavigationProp<Record<string, undefined>>>()
const [appeared, setAppeared] = useState(false)
const [leaving, setLeaving] = useState(false)
const [laidOut, setLaidOut] = useState(false)
const onLayout = useCallback(() => setLaidOut(true), [])
const theme = useContext(AndroidTabTheme)
const setPalette = theme?.setPalette
useLayoutEffect(() => {
if (Platform.OS !== "android") return
return navigation.addListener("transitionEnd", ({ data }) => {
setAppeared(!data.closing)
})
}, [navigation])
usePreventRemove(Platform.OS === "android" && !leaving, ({ repeat }) => {
setLeaving(true)
setPalette?.(null, owner)
// Let the page and bars paint their shared destination colors before the
// native stack removes the page. React blur happens too early for this.
requestAnimationFrame(() => requestAnimationFrame(repeat))
})
useLayoutEffect(() => {
if (
Platform.OS !== "android" ||
!setPalette ||
!isFocused ||
!laidOut ||
!appeared ||
leaving
)
return
setPalette(palette, owner)
return () => setPalette(null, owner)
}, [appeared, isFocused, laidOut, leaving, owner, palette, setPalette])
return {
palette: Platform.OS === "android" && theme ? theme.palette : palette,
onLayout: Platform.OS === "android" ? onLayout : undefined,
}
}
-5
View File
@@ -5,7 +5,6 @@ import { useCallback, useMemo, useState, type ReactNode } from "react"
import { ConvexAuthSessionProvider } from "@/contexts/convex-auth-session"
import { PersistentCacheProvider } from "@/contexts/persistent-cache"
import { useServerConfig } from "@/contexts/server-config"
import { clearAppIntentCatalogs } from "@/lib/app-intent-handled"
import { clearStoredAuthTokens, secureStorage } from "@/lib/auth-storage"
export function ConvexAppProvider({ children }: { children: ReactNode }) {
@@ -23,10 +22,6 @@ export function ConvexAppProvider({ children }: { children: ReactNode }) {
}
await clearStoredAuthTokens(config.convexUrl)
setAuthEpoch((epoch) => epoch + 1)
// Native catalog cleanup can be slow; it must not hold the signed-in UI open.
void clearAppIntentCatalogs().catch((error) => {
console.warn("Could not clear app intent catalogs.", error)
})
}, [config])
if (!client || !config) {
+12 -1
View File
@@ -13,7 +13,7 @@ import {
import { useCachedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { showError } from "@/lib/toast"
import { showError, showSuccess } from "@/lib/toast"
/**
* `useMutation(...).withOptimisticUpdate(...)` with a stable identity. The
@@ -178,8 +178,10 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
try {
if (idsRef.current.songIds.has(songId)) {
await unfavoriteSong({ songId })
showSuccess("Removed from favorites")
} else {
await favoriteSong({ songId })
showSuccess("Added to favorites")
}
} catch (error) {
showError(
@@ -195,8 +197,10 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
try {
if (idsRef.current.albumIds.has(albumId)) {
await unfavoriteAlbum({ albumId })
showSuccess("Removed from favorites")
} else {
await favoriteAlbum({ albumId })
showSuccess("Added to favorites")
}
} catch (error) {
showError(
@@ -212,8 +216,10 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
try {
if (idsRef.current.artistIds.has(artistId)) {
await unfavoriteArtist({ artistId })
showSuccess("Removed from favorites")
} else {
await favoriteArtist({ artistId })
showSuccess("Added to favorites")
}
} catch (error) {
showError(
@@ -230,6 +236,11 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
if (unique.length === 0) return
try {
await favoriteSongsMutation({ songIds: unique })
showSuccess(
unique.length > 1
? `Favorited ${unique.length} songs`
: "Added to favorites"
)
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to update favorites"
+115 -340
View File
@@ -1,8 +1,6 @@
import { dolbyAtmosSupported } from "@/lib/playback-capabilities"
import {
createAudioPlaylist,
setAudioModeAsync,
setIsAudioActiveAsync,
type AudioMetadata,
type AudioPlaylist,
type AudioPlaylistStatus,
@@ -21,6 +19,7 @@ import {
type ReactNode,
} from "react"
import { AppState } from "react-native"
import AsyncStorage from "@react-native-async-storage/async-storage"
import {
ANONYMOUS_CACHE_SCOPE,
@@ -40,7 +39,6 @@ import { getAuthCookieHeader } from "@/lib/auth-cookies"
import { flushPersistentCache } from "@/lib/persistent-cache"
import { loadPlaybackSongs } from "@/lib/playback-files"
import { rememberSongs, useSong, useSongs } from "@/lib/song-cache"
import { donateMusicPlay, type MusicEntityKind } from "@/lib/app-intents"
import { showError } from "@/lib/toast"
import { albumCoverUrl, songAudioSource } from "@/lib/urls"
import {
@@ -49,7 +47,6 @@ import {
updatePlaylistLockScreenMetadata,
} from "@/lib/audio-playlist-lock-screen"
import {
nativePlaylistEdits,
nativePlaylistNeedsRebuild,
nativePlaylistSongIds,
repeatToPlaylistLoop,
@@ -58,6 +55,8 @@ import {
const PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS = 5
const PROGRESS_SAVE_INTERVAL_MS = 5000
const PREFETCH_UPCOMING_SONGS = 5
const VOLUME_STORAGE_KEY = "otunes:volume"
const DEFAULT_VOLUME = 0.8
function lockScreenMetadata(
song: BrowseSong,
@@ -78,20 +77,17 @@ type PlaybackContextValue = {
shuffleEnabled: boolean
repeatEnabled: RepeatMode
isPlaying: boolean
volume: number
currentTime: number
duration: number
seekTo: (seconds: number) => void
waitForPlaybackReady: (playing?: boolean) => Promise<void>
setIsPlaying: (playing: boolean) => void
setVolume: (volume: number) => void
playInOrder: (songIds: Id<"songs">[]) => Promise<void>
playShuffled: (songIds: Id<"songs">[]) => Promise<void>
addToQueueNext: (songIds: Id<"songs">[]) => Promise<void>
addToQueueLast: (songIds: Id<"songs">[]) => Promise<void>
playFromSong: (
songId: Id<"songs">,
songIds: Id<"songs">[],
origin?: string
) => Promise<void>
playFromSong: (songId: Id<"songs">, songIds: Id<"songs">[]) => Promise<void>
playFromLibrarySong: (
songId: Id<"songs">,
sort: {
@@ -115,22 +111,10 @@ type PlaybackContextValue = {
songIds?: Id<"songs">[]
) => Promise<void>
toggleShuffle: () => Promise<void>
setShuffleEnabled: (enabled: boolean) => Promise<void>
cycleRepeat: () => Promise<void>
setRepeatMode: (mode: RepeatMode) => Promise<void>
prepareQueue: (songIds: Id<"songs">[], shuffled: boolean) => Promise<void>
startFromSong: (
songId: Id<"songs">,
songIds: Id<"songs">[],
shuffled: boolean,
play: boolean
) => Promise<void>
clearQueue: () => Promise<void>
clearUpNext: () => Promise<void>
clearHistory: () => Promise<void>
reorderQueue: (songIds: Id<"songs">[]) => Promise<void>
skipToQueueIndex: (index: number) => Promise<void>
skipToHistoryIndex: (index: number) => Promise<void>
skipNext: () => Promise<void>
skipPrevious: () => Promise<void>
}
@@ -151,17 +135,10 @@ type PlaybackActionsValue = Pick<
| "playPlaylist"
| "playPlaylistShuffled"
| "toggleShuffle"
| "setShuffleEnabled"
| "cycleRepeat"
| "setRepeatMode"
| "prepareQueue"
| "startFromSong"
| "clearQueue"
| "clearUpNext"
| "clearHistory"
| "reorderQueue"
| "skipToQueueIndex"
| "skipToHistoryIndex"
| "skipNext"
| "skipPrevious"
>
@@ -266,18 +243,19 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
const prevIsPlayingRef = useRef(false)
const currentTimeRef = useRef(0)
const pendingSeekRef = useRef<number | null>(null)
const seekInFlightRef = useRef(false)
const loadRequestIdRef = useRef(0)
const queueOriginRef = useRef<string | undefined>(undefined)
const playRequestRef = useRef(0)
const volumeRef = useRef(DEFAULT_VOLUME)
const volumeChangedRef = useRef(false)
const volumeSaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const ignoreTrackChangeTimerRef = useRef<ReturnType<
typeof setTimeout
> | null>(null)
const [queueStartVersion, setQueueStartVersion] = useState(0)
const [isPlaying, setIsPlayingState] = useState(false)
const [currentTime, setCurrentTime] = useState(0)
const [measuredDuration, setDuration] = useState(0)
const [volume, setVolumeState] = useState(DEFAULT_VOLUME)
const [progressToRestore, setProgressToRestore] = useState<number | null>(
null
)
@@ -321,7 +299,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
? JSON.stringify([
user._id,
user.playbackQuality,
dolbyAtmosSupported && (user.preferAtmos ?? false),
user.preferAtmos ?? false,
])
: ""
@@ -354,21 +332,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
loadedLoadKeyRef.current = null
}, [])
// A new queue must not inherit the native player's position or a pending seek.
const resetQueuePlayback = useCallback(() => {
loadRequestIdRef.current += 1
destroyPlaylist()
pendingSeekRef.current = null
seekInFlightRef.current = false
progressRestoredForSongRef.current = null
lastSavedProgressRef.current = -1
currentTimeRef.current = 0
setCurrentTime(0)
setDuration(0)
setProgressToRestore(null)
setQueueStartVersion((version) => version + 1)
}, [destroyPlaylist])
const handlePlaylistStatusUpdate = useCallback(
(status: AudioPlaylistStatus) => {
if (!status.isLoaded) return
@@ -377,6 +340,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
return
}
currentTimeRef.current = status.currentTime
setCurrentTime(status.currentTime)
if (status.duration > 0) {
setDuration(status.duration)
}
@@ -384,19 +349,9 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
if (pendingSeekRef.current !== null && pendingSeekRef.current > 0) {
const seekSeconds = pendingSeekRef.current
pendingSeekRef.current = null
const playlist = playlistRef.current
if (playlist) {
// Statuses report the old position until the seek lands.
seekInFlightRef.current = true
void playlist.seekTo(seekSeconds).finally(() => {
seekInFlightRef.current = false
})
}
void playlistRef.current?.seekTo(seekSeconds)
currentTimeRef.current = seekSeconds
setCurrentTime(seekSeconds)
} else if (!seekInFlightRef.current) {
currentTimeRef.current = status.currentTime
setCurrentTime(status.currentTime)
}
if (status.playing) {
@@ -444,17 +399,13 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
const handleTrackChanged = useCallback(
(data: { currentIndex: number; previousIndex: number }) => {
if (ignoreTrackChangeRef.current) return
// The window is history then queue, so the current track sits at
// `history.length`. Android's `previousIndex` goes stale when tracks
// are inserted or removed before it.
const steps =
data.currentIndex - storeRef.current.getState().history.length
if (steps === 0) return
if (data.currentIndex === data.previousIndex) return
autoPlayNextRef.current = true
isPlayingRef.current = true
setIsPlayingState(true)
const steps = data.currentIndex - data.previousIndex
storeRef.current.update((state) => {
if (steps === 1) return playbackQueue.skipNext(state)
if (steps > 1) return playbackQueue.skipToQueueIndex(state, steps)
@@ -480,8 +431,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
updateInterval: 500,
loop: repeatToPlaylistLoop(storeRef.current.getState().repeatEnabled),
})
// System volume controls loudness; keep the player gain at full scale.
playlist.volume = 1
playlist.volume = volumeRef.current
statusSubscriptionRef.current = playlist.addListener(
"playlistStatusUpdate",
handlePlaylistStatusUpdate
@@ -513,12 +463,42 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
}
})
void AsyncStorage.getItem(VOLUME_STORAGE_KEY)
.then((stored) => {
if (!cancelled && !volumeChangedRef.current && stored) {
const parsed = Number(stored)
if (Number.isFinite(parsed)) {
const restoredVolume = Math.min(1, Math.max(0, parsed))
volumeRef.current = restoredVolume
setVolumeState(restoredVolume)
}
}
})
.catch(() => {})
return () => {
cancelled = true
if (volumeSaveTimerRef.current) {
clearTimeout(volumeSaveTimerRef.current)
volumeSaveTimerRef.current = null
}
if (volumeChangedRef.current) {
void AsyncStorage.setItem(
VOLUME_STORAGE_KEY,
String(volumeRef.current)
).catch(() => {})
}
destroyPlaylist()
}
}, [destroyPlaylist])
useEffect(() => {
volumeRef.current = volume
if (playlistRef.current) {
playlistRef.current.volume = volume
}
}, [volume])
useEffect(() => {
const playlist = playlistRef.current
if (playlist) {
@@ -538,6 +518,25 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
}
}, [])
const setVolume = useCallback((nextVolume: number) => {
const clamped = Math.min(1, Math.max(0, nextVolume))
volumeChangedRef.current = true
volumeRef.current = clamped
setVolumeState(clamped)
if (volumeSaveTimerRef.current) {
clearTimeout(volumeSaveTimerRef.current)
}
volumeSaveTimerRef.current = setTimeout(() => {
volumeSaveTimerRef.current = null
void AsyncStorage.setItem(VOLUME_STORAGE_KEY, String(clamped)).catch(
() => {}
)
}, 250)
if (playlistRef.current) {
playlistRef.current.volume = clamped
}
}, [])
const seekTo = useCallback(
async (seconds: number) => {
const playlist = playlistRef.current
@@ -586,12 +585,11 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
if (progressRestoredForSongRef.current === currentSongId) return
progressRestoredForSongRef.current = currentSongId
lastSavedProgressRef.current = -1
pendingSeekRef.current = null
currentTimeRef.current = 0
setCurrentTime(0)
setDuration(0)
setProgressToRestore(store.getState().progressSeconds)
}, [currentSongId, destroyPlaylist, queueStartVersion, store])
}, [currentSongId, destroyPlaylist, store])
useEffect(() => {
if (progressToRestore === null || progressToRestore <= 0) return
@@ -649,7 +647,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
}
if (!isCurrentLoad()) return
const loadKey = `${user.playbackQuality}:${dolbyAtmosSupported && (user.preferAtmos ?? false)}:${cookieHeader}`
const loadKey = `${user.playbackQuality}:${user.preferAtmos ?? false}:${cookieHeader}`
const needsRebuild =
loadedLoadKeyRef.current !== loadKey ||
nativePlaylistNeedsRebuild(
@@ -671,6 +669,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
playlist.skipTo(currentIndex)
}
playlist.loop = repeatToPlaylistLoop(repeatEnabled)
playlist.volume = volumeRef.current
if (metadata) {
updatePlaylistLockScreenMetadata(playlist, metadata)
}
@@ -683,89 +682,33 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
return
}
const buildSources = async (songIds: Id<"songs">[]) => {
const songs = await loadPlaybackSongs(convex, cacheScope, songIds)
const sources = new Map<Id<"songs">, AudioSource>()
for (const song of songs) {
if (!song) return null
const plan = playbackStreamPlan(
song.files,
user.playbackQuality,
dolbyAtmosSupported && (user.preferAtmos ?? false)
)
sources.set(
song.id,
songAudioSource(
config.serverUrl,
song.id,
plan.playbackQuality,
plan.preferAtmos,
plan.useHls,
{ cookieHeader, songTitle: song.title }
)
)
}
return sources
}
const songs = await loadPlaybackSongs(convex, cacheScope, windowSongIds)
if (!isCurrentLoad()) return
// Queue and history edits around the playing track are applied in place
// so playback isn't interrupted.
const loadedPlaylist = playlistRef.current
const edits =
loadedPlaylist && loadedLoadKeyRef.current === loadKey
? nativePlaylistEdits(
loadedSongIdsRef.current,
loadedPlaylist.currentIndex,
windowSongIds,
currentIndex
)
: null
if (loadedPlaylist && edits) {
const addedSongIds = edits.flatMap((edit) =>
edit.type === "remove" ? [] : [edit.songId]
)
const sources = await buildSources([...new Set(addedSongIds)])
if (!isCurrentLoad()) return
if (!sources) {
const sources: AudioSource[] = []
for (let i = 0; i < windowSongIds.length; i++) {
const song = songs[i]
if (!song) {
handlePlaybackLoadFailure()
return
}
ignoreTrackChangeRef.current = true
for (const edit of edits) {
if (edit.type === "remove") {
loadedPlaylist.remove(edit.index)
} else if (edit.type === "insert") {
loadedPlaylist.insert(sources.get(edit.songId)!, edit.index)
} else {
loadedPlaylist.add(sources.get(edit.songId)!)
}
}
loadedSongIdsRef.current = windowSongIds
loadedPlaylist.loop = repeatToPlaylistLoop(repeatEnabled)
scheduleTrackChangeHandling()
if (shouldPlay && !loadedPlaylist.playing) {
isPlayingRef.current = true
setIsPlayingState(true)
loadedPlaylist.play()
}
return
const plan = playbackStreamPlan(
song.files,
user.playbackQuality,
user.preferAtmos ?? false
)
sources.push(
songAudioSource(
config.serverUrl,
song.id,
plan.playbackQuality,
plan.preferAtmos,
plan.useHls,
{ cookieHeader, songTitle: song.title }
)
)
}
const sourcesById = await buildSources(windowSongIds)
if (!isCurrentLoad()) return
if (!sourcesById) {
handlePlaybackLoadFailure()
return
}
const sources = windowSongIds.map((songId) => sourcesById.get(songId)!)
// Keep the position when only the stream settings changed.
const resumeSeconds =
loadedPlaylist &&
loadedSongIdsRef.current[loadedPlaylist.currentIndex] === currentSongId
? currentTimeRef.current
: null
ignoreTrackChangeRef.current = true
destroyPlaylist()
if (!isCurrentLoad()) {
@@ -773,21 +716,17 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
return
}
if (resumeSeconds !== null && resumeSeconds > 0) {
pendingSeekRef.current = resumeSeconds
}
// Start at the current track and put history in front of it, so an
// earlier song is never loaded first.
const playlist = ensurePlaylist(sources.slice(currentIndex))
for (let index = 0; index < currentIndex; index++) {
playlist.insert(sources[index], index)
}
const playlist = ensurePlaylist(sources)
loadedSongIdsRef.current = windowSongIds
loadedLoadKeyRef.current = loadKey
playlist.volume = volumeRef.current
playlist.loop = repeatToPlaylistLoop(repeatEnabled)
if (currentIndex > 0) {
playlist.skipTo(currentIndex)
}
activatePlaylistLockScreen(
playlist,
metadata ?? { title: currentSong?.title }
metadata ?? { title: songs[currentIndex]?.title }
)
scheduleTrackChangeHandling()
@@ -797,14 +736,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
playlist.play()
} else {
playlist.pause()
// Enable audio for the restored queue without starting playback.
try {
await setIsAudioActiveAsync(true)
} catch {
if (isCurrentLoad()) {
showError("Audio playback could not be initialized.")
}
}
}
}
@@ -829,7 +760,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
handlePlaybackLoadFailure,
historySyncKey,
queueSyncKey,
queueStartVersion,
repeatEnabled,
scheduleTrackChangeHandling,
userPlaybackKey,
@@ -848,63 +778,32 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
recipe: (
state: playbackQueue.PlaybackQueueState
) => playbackQueue.PlaybackQueueState,
recorded: {
playlistId?: Id<"playlists">
origin?: string
entity?: { kind: MusicEntityKind; id: string }
} = {}
recorded: { playlistId?: Id<"playlists"> } = {}
) => {
playRequestRef.current += 1
queueOriginRef.current =
recorded.origin ??
(recorded.playlistId ? `playlist:${recorded.playlistId}` : undefined)
resetQueuePlayback()
const previousSongId = store.getState().queue[0]
store.update(recipe)
const firstSongId = store.getState().queue[0]
if (!firstSongId) return
if (firstSongId === previousSongId) {
void seekTo(0)
}
setIsPlaying(true)
void (async () => {
const deadline = Date.now() + 20_000
while (
Date.now() < deadline &&
store.getState().queue[0] === firstSongId
) {
const player = playlistRef.current
if (
player?.isLoaded &&
player.playing &&
loadedSongIdsRef.current[player.currentIndex] === firstSongId
) {
await donateMusicPlay(
recorded.entity?.kind ??
(recorded.playlistId ? "playlist" : "song"),
recorded.entity?.id ?? recorded.playlistId ?? firstSongId,
store.getState().shuffleEnabled
)
return
}
await new Promise((resolve) => setTimeout(resolve, 250))
}
})()
recordPlay(
recorded.playlistId
? { playlistId: recorded.playlistId }
: { songId: firstSongId }
)
},
[store, resetQueuePlayback, setIsPlaying, recordPlay]
[store, seekTo, setIsPlaying, recordPlay]
)
const playCollection = useCallback(
async (
songIds: Id<"songs">[] | Promise<Id<"songs">[]>,
shuffled: boolean,
recorded: {
playlistId?: Id<"playlists">
origin?: string
entity?: { kind: MusicEntityKind; id: string }
} = {}
recorded: { playlistId?: Id<"playlists"> } = {}
) => {
const request = ++playRequestRef.current
let resolvedSongIds: Id<"songs">[]
@@ -967,19 +866,12 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
)
const playFromSong = useCallback(
async (songId: Id<"songs">, songIds: Id<"songs">[], origin?: string) => {
if (
origin &&
queueOriginRef.current === origin &&
store.getState().queue[0] === songId
)
return
startPlayback(
(state) => playbackQueue.startQueueFromSong(state, songId, songIds),
{ origin }
async (songId: Id<"songs">, songIds: Id<"songs">[]) => {
startPlayback((state) =>
playbackQueue.startQueueFromSong(state, songId, songIds)
)
},
[startPlayback, store]
[startPlayback]
)
const playFromLibrarySong = useCallback(
@@ -1047,35 +939,25 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
const playAlbum = useCallback(
(albumId: Id<"albums">, songIds?: Id<"songs">[]) =>
playCollection(loadAlbumSongIds(albumId, songIds), false, {
entity: { kind: "album", id: albumId },
origin: `album:${albumId}`,
}),
playCollection(loadAlbumSongIds(albumId, songIds), false),
[playCollection, loadAlbumSongIds]
)
const playAlbumShuffled = useCallback(
(albumId: Id<"albums">, songIds?: Id<"songs">[]) =>
playCollection(loadAlbumSongIds(albumId, songIds), true, {
entity: { kind: "album", id: albumId },
origin: `album:${albumId}`,
}),
playCollection(loadAlbumSongIds(albumId, songIds), true),
[playCollection, loadAlbumSongIds]
)
const playArtist = useCallback(
(artistId: Id<"artists">) =>
playCollection(loadArtistSongIds(artistId), false, {
entity: { kind: "artist", id: artistId },
}),
playCollection(loadArtistSongIds(artistId), false),
[playCollection, loadArtistSongIds]
)
const playArtistShuffled = useCallback(
(artistId: Id<"artists">) =>
playCollection(loadArtistSongIds(artistId), true, {
entity: { kind: "artist", id: artistId },
}),
playCollection(loadArtistSongIds(artistId), true),
[playCollection, loadArtistSongIds]
)
@@ -1099,72 +981,16 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
store.update(playbackQueue.toggleShuffle)
}, [store])
const setShuffleEnabled = useCallback(
async (enabled: boolean) => {
store.update((state) => playbackQueue.setShuffleEnabled(state, enabled))
},
[store]
)
const cycleRepeat = useCallback(async () => {
store.update(playbackQueue.cycleRepeat)
}, [store])
const setRepeatMode = useCallback(
async (mode: RepeatMode) => {
store.update((state) => playbackQueue.setRepeatMode(state, mode))
},
[store]
)
const prepareQueue = useCallback(
async (songIds: Id<"songs">[], shuffled: boolean) => {
if (songIds.length === 0) return
playRequestRef.current += 1
queueOriginRef.current = undefined
resetQueuePlayback()
store.update((state) =>
playbackQueue.startQueue(state, songIds, shuffled)
)
setIsPlaying(false)
},
[store, resetQueuePlayback, setIsPlaying]
)
const startFromSong = useCallback(
async (
songId: Id<"songs">,
songIds: Id<"songs">[],
shuffled: boolean,
play: boolean
) => {
playRequestRef.current += 1
queueOriginRef.current = undefined
resetQueuePlayback()
store.update((state) => playbackQueue.setShuffleEnabled(state, shuffled))
store.update((state) =>
playbackQueue.startQueueFromSong(state, songId, songIds)
)
setIsPlaying(play)
},
[store, resetQueuePlayback, setIsPlaying]
)
const clearQueue = useCallback(async () => {
playRequestRef.current += 1
queueOriginRef.current = undefined
store.update(playbackQueue.clearQueue)
setIsPlaying(false)
}, [store, setIsPlaying])
const clearUpNext = useCallback(async () => {
store.update(playbackQueue.clearUpNext)
}, [store])
const clearHistory = useCallback(async () => {
store.update(playbackQueue.clearHistory)
}, [store])
const reorderQueue = useCallback(
async (songIds: Id<"songs">[]) => {
store.update((state) => playbackQueue.reorderQueue(state, songIds))
@@ -1181,15 +1007,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
[store]
)
const skipToHistoryIndex = useCallback(
async (index: number) => {
if (index < 0 || index >= store.getState().history.length) return
autoPlayNextRef.current = true
store.update((state) => playbackQueue.skipToHistoryIndex(state, index))
},
[store]
)
const skipNext = useCallback(async () => {
const before = store.getState()
if (before.repeatEnabled === "none" && before.queue.length <= 1) {
@@ -1222,36 +1039,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
store.update(playbackQueue.skipPrevious)
}, [store, seekTo])
// Queue changes return before React has loaded the native audio source. Siri
// must observe the native player, rather than treating a state update as success.
const waitForPlaybackReady = useCallback(
async (playing?: boolean) => {
const expectedId = store.getState().queue[0]
if (!expectedId) throw new Error("Nothing is queued to play.")
const deadline = Date.now() + 20_000
while (Date.now() < deadline) {
if (store.getState().queue[0] !== expectedId) {
throw new Error(
"The playback queue changed before the request finished."
)
}
const player = playlistRef.current
if (
player &&
loadedSongIdsRef.current[player.currentIndex] === expectedId &&
player.isLoaded &&
(playing === undefined || player.playing === playing)
)
return
await new Promise((resolve) => setTimeout(resolve, 100))
}
throw new Error(
"The audio did not become ready. Check your connection and try again."
)
},
[store]
)
const actionsValue = useMemo<PlaybackActionsValue>(
() => ({
setIsPlaying,
@@ -1268,31 +1055,18 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
playPlaylist,
playPlaylistShuffled,
toggleShuffle,
setShuffleEnabled,
cycleRepeat,
setRepeatMode,
prepareQueue,
startFromSong,
clearQueue,
clearUpNext,
clearHistory,
reorderQueue,
skipToQueueIndex,
skipToHistoryIndex,
skipNext,
skipPrevious,
}),
[
addToQueueNext,
addToQueueLast,
clearHistory,
clearQueue,
clearUpNext,
cycleRepeat,
prepareQueue,
startFromSong,
setRepeatMode,
setShuffleEnabled,
playAlbum,
playAlbumShuffled,
playArtist,
@@ -1307,7 +1081,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
setIsPlaying,
skipNext,
skipPrevious,
skipToHistoryIndex,
skipToQueueIndex,
toggleShuffle,
]
@@ -1328,20 +1101,20 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
const value = useMemo<PlaybackContextValue>(
() => ({
...actionsValue,
waitForPlaybackReady,
queueSongIds,
queueHistorySongIds,
currentSong,
shuffleEnabled: playback.shuffleEnabled,
repeatEnabled,
isPlaying: isPlaybackActive,
volume,
currentTime,
duration,
seekTo,
setVolume,
}),
[
actionsValue,
waitForPlaybackReady,
currentSong,
currentTime,
duration,
@@ -1351,6 +1124,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
queueSongIds,
repeatEnabled,
seekTo,
setVolume,
volume,
]
)
-9
View File
@@ -5,22 +5,13 @@
},
"build": {
"development": {
"env": {
"APP_VARIANT": "development"
},
"developmentClient": true,
"distribution": "internal"
},
"preview": {
"env": {
"APP_VARIANT": "preview"
},
"distribution": "internal"
},
"production": {
"env": {
"APP_VARIANT": "production"
},
"autoIncrement": true
}
},
@@ -1,19 +0,0 @@
import { useEffect, useState } from "react"
import { Keyboard, Platform } from "react-native"
export function useAndroidKeyboardVisible() {
const [visible, setVisible] = useState(false)
useEffect(() => {
if (Platform.OS !== "android") return
setVisible(Keyboard.isVisible())
const show = Keyboard.addListener("keyboardDidShow", () => setVisible(true))
const hide = Keyboard.addListener("keyboardDidHide", () =>
setVisible(false)
)
return () => {
show.remove()
hide.remove()
}
}, [])
return visible
}
+7 -25
View File
@@ -7,7 +7,7 @@ import { useCacheScope } from "@/contexts/persistent-cache"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback"
import { useAppNavigation } from "@/lib/app-navigation"
import { showError } from "@/lib/toast"
import { showError, showSuccess } from "@/lib/toast"
import { api } from "@otunes/convex/_generated/api"
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
import type { Id } from "@otunes/convex/_generated/dataModel"
@@ -46,8 +46,7 @@ export function useMediaMenuActions() {
toggleSongFavorite,
favoriteSongs,
} = useFavorites()
const { addToQueueNext, addToQueueLast, playShuffled, playArtistShuffled } =
usePlaybackActions()
const { addToQueueNext, addToQueueLast, playShuffled } = usePlaybackActions()
const runQueueAction = useCallback(
async (action: MediaAction, songIds: Id<"songs">[]) => {
@@ -56,9 +55,11 @@ export function useMediaMenuActions() {
switch (action) {
case "play-next":
await addToQueueNext(songIds)
showSuccess("Queued to play next")
break
case "play-last":
await addToQueueLast(songIds)
showSuccess("Queued to play last")
break
case "shuffle":
await playShuffled(songIds)
@@ -75,11 +76,6 @@ export function useMediaMenuActions() {
async (song: BrowseSong, action: MediaAction) => {
const songIds = [song.id as Id<"songs">]
switch (action) {
case "create-station":
await runMediaAction(() =>
playArtistShuffled(song.artist.id as Id<"artists">)
)
break
case "playlist":
openAddToPlaylist(songIds)
break
@@ -101,22 +97,13 @@ export function useMediaMenuActions() {
break
}
},
[
openAddToPlaylist,
push,
runQueueAction,
toggleSongFavorite,
playArtistShuffled,
]
[openAddToPlaylist, push, runQueueAction, toggleSongFavorite]
)
const handleAlbumAction = useCallback(
async (album: BrowseAlbum, action: MediaAction) => {
await runMediaAction(async () => {
switch (action) {
case "create-station":
await playArtistShuffled(album.artist.id as Id<"artists">)
break
case "playlist":
await openAddAlbumToPlaylist(album.id as Id<"albums">)
break
@@ -147,7 +134,6 @@ export function useMediaMenuActions() {
convex,
cacheScope,
openAddAlbumToPlaylist,
playArtistShuffled,
push,
runQueueAction,
toggleAlbumFavorite,
@@ -223,13 +209,9 @@ export function useMediaMenuActions() {
async (
albumId: Id<"albums">,
songIds: Id<"songs">[],
action: MediaAction,
artistId: Id<"artists">
action: MediaAction
) => {
switch (action) {
case "create-station":
await runMediaAction(() => playArtistShuffled(artistId))
break
case "favorite":
await toggleAlbumFavorite(albumId)
break
@@ -245,7 +227,7 @@ export function useMediaMenuActions() {
break
}
},
[openAddToPlaylist, runQueueAction, toggleAlbumFavorite, playArtistShuffled]
[openAddToPlaylist, runQueueAction, toggleAlbumFavorite]
)
const handleAlbumTrackAction = useCallback(
-72
View File
@@ -1,72 +0,0 @@
import { requireOptionalNativeModule, type EventEmitter } from "expo"
import { useFocusEffect } from "expo-router"
import { useCallback, useEffect, useState } from "react"
import { AppState, Platform } from "react-native"
type VolumeState = { volume: number; available: boolean }
type VolumeEvents = { onVolumeChange: (state: VolumeState) => void }
interface SystemVolumeModule extends EventEmitter<VolumeEvents> {
setPlayerVisible?(visible: boolean): Promise<void>
getState(): Promise<VolumeState>
setVolume(volume: number): Promise<void>
}
const native = requireOptionalNativeModule<SystemVolumeModule>("SystemVolume")
/** The device owns volume. Never restore an app-specific level on launch. */
export function useSystemVolume() {
const [state, setState] = useState<VolumeState>({
volume: 0,
available: false,
})
useFocusEffect(
useCallback(() => {
if (Platform.OS !== "ios" || !native?.setPlayerVisible) return
void native.setPlayerVisible(true).catch(() => {})
return () => {
void native.setPlayerVisible?.(false).catch(() => {})
}
}, [])
)
useEffect(() => {
if (!native) return
let active = true
let revision = 0
const listener = native.addListener("onVolumeChange", (next) => {
revision++
if (active) setState(next)
})
const refresh = async () => {
const requestedRevision = ++revision
try {
const next = await native.getState()
if (active && requestedRevision === revision) setState(next)
} catch {
if (active && requestedRevision === revision) {
setState((value) => ({ ...value, available: false }))
}
}
}
void refresh()
const foreground = AppState.addEventListener("change", (next) => {
if (next === "active") void refresh()
})
return () => {
active = false
listener.remove()
foreground.remove()
}
}, [])
const setVolume = useCallback((value: number) => {
if (!native || !Number.isFinite(value)) return
const volume = Math.min(1, Math.max(0, value))
void native.setVolume(volume).catch(() => {
setState((current) => ({ ...current, available: false }))
})
}, [])
return { ...state, setVolume }
}
-59
View File
@@ -1,59 +0,0 @@
import AsyncStorage from "@react-native-async-storage/async-storage"
import * as AppIntents from "expo-app-intents"
import { publishMusicCatalog } from "@/lib/app-intents"
export const FAVORITES_PLAYLIST_ID = "otunes:favorites"
const HANDLED_KEY = "otunes:handled-app-intents"
const MAX_HANDLED = 200
const CATALOG_KINDS = [
"song",
"album",
"artist",
"playlist",
"nowPlaying",
] as const
export async function clearAppIntentCatalogs() {
if (!AppIntents.isAvailable()) {
return
}
const results = await Promise.allSettled([
AppIntents.deleteDonationsAsync({ intent: "playMusic" }),
AppIntents.clearPendingInvocationsAsync(),
...CATALOG_KINDS.map((kind) => publishMusicCatalog(kind, [])),
])
const failed = results.find((result) => result.status === "rejected")
if (failed?.status === "rejected") throw failed.reason
}
export async function loadHandledIntentIds() {
const raw = await AsyncStorage.getItem(HANDLED_KEY)
if (!raw) {
return new Set<string>()
}
try {
const parsed = JSON.parse(raw) as unknown
if (!Array.isArray(parsed)) {
return new Set<string>()
}
return new Set(parsed.filter((id) => typeof id === "string"))
} catch {
return new Set<string>()
}
}
export async function rememberHandledIntentId(ids: Set<string>, id: string) {
ids.add(id)
const list = [...ids]
const trimmed =
list.length > MAX_HANDLED ? list.slice(list.length - MAX_HANDLED) : list
if (trimmed.length !== list.length) {
ids.clear()
for (const item of trimmed) {
ids.add(item)
}
}
await AsyncStorage.setItem(HANDLED_KEY, JSON.stringify(trimmed))
}
-147
View File
@@ -1,147 +0,0 @@
const { test } = require("node:test")
const assert = require("node:assert/strict")
const fs = require("node:fs")
const vm = require("node:vm")
const ts = require("typescript")
// Exercise the app's catalog lifecycle without requiring a React Native runtime.
function runtime() {
const disk = new Map()
const catalogs = new Map()
const deleted = []
const donated = []
const native = {
catalogJSON: async (kind) => JSON.stringify(disk.get(kind) ?? []),
replaceCatalog: async (kind, json) => disk.set(kind, JSON.parse(json)),
completeInvocation: async () => {},
}
const expo = {
isAvailable: () => true,
getEntityCatalogAsync: async (kind) => catalogs.get(kind) ?? [],
setEntityCatalogAsync: async (kind, entities) =>
catalogs.set(kind, entities),
deleteDonationsAsync: async (filter) => deleted.push(filter),
donateIntentAsync: async (name, params) => donated.push({ name, params }),
}
const module = { exports: {} }
const source = ts.transpileModule(
fs.readFileSync(`${__dirname}/app-intents.ts`, "utf8"),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
},
}
).outputText
vm.runInNewContext(source, {
module,
exports: module.exports,
console: { warn() {} },
require: (name) => {
if (name === "expo") return { requireOptionalNativeModule: () => native }
if (name === "expo-app-intents") return expo
throw new Error(`Unexpected import ${name}`)
},
})
return { api: module.exports, native, expo, disk, catalogs, deleted, donated }
}
function song(id, favorite = false) {
return {
id: String(id),
title: `Song ${id}`,
metadata: { favorite: favorite ? "1" : "0" },
}
}
function deferred() {
let resolve
const promise = new Promise((done) => {
resolve = done
})
return { promise, resolve }
}
test("large libraries remain fully searchable on disk while suggestions stay bounded", async () => {
const { api, disk, catalogs } = runtime()
const songs = Array.from({ length: 10_000 }, (_, id) => song(id, id === 9999))
await api.publishMusicCatalog("song", songs)
assert.equal(disk.get("song").length, 10_000)
assert.equal(catalogs.get("song").length, 100)
assert.equal(catalogs.get("song")[0].id, "9999")
})
test("deleting a song outside the suggestion subset removes its donations", async () => {
const { api, deleted } = runtime()
const songs = Array.from({ length: 200 }, (_, id) => song(id))
await api.publishMusicCatalog("song", songs)
await api.publishMusicCatalog("song", songs.slice(0, -1))
assert.equal(deleted.length, 1)
assert.equal(deleted[0].entity, "song")
assert.equal(deleted[0].id, "199")
})
test("a queued clear finishes after an in-flight publication and leaves no stale index", async () => {
const { api, native, disk, catalogs } = runtime()
const gate = deferred()
const original = native.replaceCatalog
native.replaceCatalog = async (...args) => {
await gate.promise
return original(...args)
}
const publish = api.publishMusicCatalog("song", [song(1)])
const clear = api.publishMusicCatalog("song", [])
gate.resolve()
await Promise.all([publish, clear])
assert.equal(disk.get("song").length, 0)
assert.equal(catalogs.get("song").length, 0)
})
test("a storage failure does not poison subsequent catalog cleanup", async () => {
const { api, native, catalogs } = runtime()
const original = native.replaceCatalog
native.replaceCatalog = async () => {
throw new Error("Disk unavailable")
}
await assert.rejects(
api.publishMusicCatalog("song", [song(1)]),
/Disk unavailable/
)
native.replaceCatalog = original
await api.publishMusicCatalog("song", [])
assert.equal(catalogs.get("song").length, 0)
})
test("donations wait for catalog synchronization and failures do not reject playback", async () => {
const { api, donated, expo } = runtime()
const sync = deferred()
api.trackMusicCatalogSync(sync.promise)
const donation = api.donateMusicPlay("album", "album-1")
await new Promise((resolve) => setImmediate(resolve))
assert.equal(donated.length, 0)
sync.resolve()
await donation
assert.equal(donated[0].params.id, "album-1")
expo.donateIntentAsync = async () => {
throw new Error("Suggestions unavailable")
}
await api.donateMusicPlay("album", "album-1")
})
test("failed donation cleanup retains deleted records so the next sync can retry", async () => {
const { api, disk, expo, deleted } = runtime()
await api.publishMusicCatalog("song", [song(1), song(2)])
const cleanup = expo.deleteDonationsAsync
expo.deleteDonationsAsync = async () => {
throw new Error("Cleanup failed")
}
await assert.rejects(
api.publishMusicCatalog("song", [song(1)]),
/Cleanup failed/
)
assert.equal(disk.get("song").length, 2)
expo.deleteDonationsAsync = cleanup
await api.publishMusicCatalog("song", [song(1)])
assert.equal(deleted[0].id, "2")
assert.equal(disk.get("song").length, 1)
})
-74
View File
@@ -1,74 +0,0 @@
import { requireOptionalNativeModule } from "expo"
import * as AppIntents from "expo-app-intents"
import type { AppIntentEntity } from "expo-app-intents"
type MusicIntentModule = {
replaceCatalog: (kind: string, json: string) => Promise<void>
catalogJSON: (kind: string) => Promise<string>
completeInvocation: (token: string, error: string | null) => Promise<void>
}
const native = requireOptionalNativeModule<MusicIntentModule>("AppIntentsSetup")
export type MusicEntityKind = "song" | "album" | "artist" | "playlist"
const SPOTLIGHT_LIMIT = 100
let publishing: Promise<void> = Promise.resolve()
let catalogSync: Promise<void> = Promise.resolve()
export function trackMusicCatalogSync(sync: Promise<void>) {
catalogSync = sync
}
/** Serialize writes so sign-out cleanup cannot be overtaken by an older publish. */
export function publishMusicCatalog(kind: string, entities: AppIntentEntity[]) {
const write = publishing
.catch(() => undefined)
.then(async () => {
if (!native || !AppIntents.isAvailable()) return
const oldDiskCatalog = JSON.parse(
await native.catalogJSON(kind)
) as AppIntentEntity[]
const suggestions = [...entities]
.sort(
(a, b) =>
Number(b.metadata?.favorite === "1") -
Number(a.metadata?.favorite === "1")
)
.slice(0, SPOTLIGHT_LIMIT)
const previous = await AppIntents.getEntityCatalogAsync(kind)
const remaining = new Set(entities.map((entity) => entity.id))
for (const entity of new Map(
[...oldDiskCatalog, ...previous].map((item) => [item.id, item])
).values()) {
if (!remaining.has(entity.id) && kind !== "nowPlaying") {
await AppIntents.deleteDonationsAsync({ entity: kind, id: entity.id })
}
}
await native.replaceCatalog(kind, JSON.stringify(entities))
await AppIntents.setEntityCatalogAsync(kind, suggestions)
})
publishing = write
return write
}
export async function completeMusicInvocation(
token: string,
error: string | null
) {
await native?.completeInvocation(token, error)
}
/** Donation errors never turn a completed user action into a playback failure. */
export async function donateMusicPlay(
kind: MusicEntityKind,
id: string,
shuffle = false
) {
if (!native || !AppIntents.isAvailable()) return
try {
await catalogSync
await publishing
await AppIntents.donateIntentAsync("playMusic", { kind, id, shuffle })
} catch (error) {
console.warn("Could not donate music playback.", error)
}
}
-7
View File
@@ -38,13 +38,6 @@ export function useAppNavigation() {
const router = useRouter()
const push = useCallback((path: string) => {
if (activeSegmentsRef.current.includes("player")) {
// Leave the root player modal before navigating into the library stack.
router.dismiss()
router.navigate(tabPath("library", path))
return
}
router.push(tabPath(getActiveTabFromRef(), path))
}, [router])
+51 -10
View File
@@ -1,21 +1,47 @@
import type {
AudioLockScreenOptions,
AudioMetadata,
AudioPlaylist,
} from "expo-audio"
import type { AudioMetadata, AudioPlaylist } from "expo-audio"
const TRACK_SKIP_LOCK_SCREEN_OPTIONS: AudioLockScreenOptions = {
/**
* Lock-screen options added in Expo SDK 58 (`expo-audio` playlist lock screen).
* SDK 57 only understands seek-forward/back; next/previous are ignored until upgrade.
*/
export type PlaylistLockScreenOptions = {
isLiveStream?: boolean
showNextTrack?: boolean
showPreviousTrack?: boolean
showSeekBackward?: boolean
showSeekForward?: boolean
}
type PlaylistLockScreenApi = {
setActiveForLockScreen: (
active: boolean,
metadata?: AudioMetadata,
options?: PlaylistLockScreenOptions
) => void
updateLockScreenMetadata?: (metadata: AudioMetadata) => void
clearLockScreenControls?: () => void
}
const TRACK_SKIP_LOCK_SCREEN_OPTIONS: PlaylistLockScreenOptions = {
showNextTrack: true,
showPreviousTrack: true,
showSeekForward: false,
showSeekBackward: false,
}
function lockScreenApi(playlist: AudioPlaylist): PlaylistLockScreenApi | null {
const candidate = playlist as AudioPlaylist & Partial<PlaylistLockScreenApi>
if (typeof candidate.setActiveForLockScreen !== "function") {
return null
}
return candidate as PlaylistLockScreenApi
}
export function activatePlaylistLockScreen(
playlist: AudioPlaylist,
metadata: AudioMetadata
) {
playlist.setActiveForLockScreen(
lockScreenApi(playlist)?.setActiveForLockScreen(
true,
metadata,
TRACK_SKIP_LOCK_SCREEN_OPTIONS
@@ -26,14 +52,29 @@ export function updatePlaylistLockScreenMetadata(
playlist: AudioPlaylist,
metadata: AudioMetadata
) {
playlist.updateLockScreenMetadata(metadata)
const api = lockScreenApi(playlist)
if (typeof api?.updateLockScreenMetadata === "function") {
api.updateLockScreenMetadata(metadata)
return
}
api?.setActiveForLockScreen(true, metadata, TRACK_SKIP_LOCK_SCREEN_OPTIONS)
}
export function deactivatePlaylistLockScreen(playlist: AudioPlaylist) {
playlist.clearLockScreenControls()
const api = lockScreenApi(playlist)
if (typeof api?.clearLockScreenControls === "function") {
api.clearLockScreenControls()
return
}
api?.setActiveForLockScreen(false)
}
export function releaseAudioPlaylist(playlist: AudioPlaylist) {
deactivatePlaylistLockScreen(playlist)
playlist.destroy()
const withDestroy = playlist as AudioPlaylist & {
destroy?: () => void
}
if (typeof withDestroy.destroy === "function") {
withDestroy.destroy()
}
}
-30
View File
@@ -1,30 +0,0 @@
// Keep the destination while server setup or sign-in is on screen.
const listeners = new Set<() => void>()
export function subscribeIncomingMediaLink(listener: () => void) {
listeners.add(listener)
return () => {
listeners.delete(listener)
}
}
let pendingLink: { path: string; serverOrigin: string } | null = null
export function incomingMediaLink(serverUrl: string) {
if (!pendingLink) return null
return new URL(serverUrl).origin === pendingLink.serverOrigin
? pendingLink.path
: null
}
export function takeIncomingMediaLink(serverUrl: string) {
const path = incomingMediaLink(serverUrl)
pendingLink = null
for (const listener of listeners) listener()
return path
}
export function rememberIncomingMediaLink(path: string, serverOrigin: string) {
pendingLink = { path, serverOrigin }
for (const listener of listeners) listener()
}
Loaded 100 of 172 files, more files were not shown because too many files have changed in this diff. Show more