Compare commits

...
43 changed files with 1014 additions and 126 deletions

No files matched your search

+19
View File
@@ -23,3 +23,22 @@ 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.
+8 -3
View File
@@ -1,7 +1,7 @@
import type { ConfigContext, ExpoConfig } from "expo/config"
export default ({ config }: ConfigContext): ExpoConfig => {
const variant =
const variant: string =
process.env.APP_VARIANT ?? process.env.EAS_BUILD_PROFILE ?? "production"
if (
variant !== "development" &&
@@ -19,9 +19,10 @@ export default ({ config }: ConfigContext): ExpoConfig => {
: variant === "preview"
? " (Preview)"
: ""
// Expo writes this filename into Xcode build settings without quoting it.
const composer = {
development: "oTunes Dev",
preview: "oTunes Preview",
development: "oTunesDev",
preview: "oTunesPreview",
production: "oTunes",
}[variant]
@@ -35,6 +36,10 @@ export default ({ config }: ConfigContext): ExpoConfig => {
...config.ios,
bundleIdentifier: `${config.ios!.bundleIdentifier}${suffix}`,
icon: `./assets/${composer}.icon`,
infoPlist: {
...config.ios?.infoPlist,
NSUserActivityTypes: [`com.abunchofknowitalls.otunes${suffix}.media`],
},
},
android: {
...config.android,
@@ -111,7 +111,9 @@ export default function AlbumScreen() {
songIds={songIds}
palette={palette}
favorited={isSongFavorite(item.track.id)}
onPlay={playFromSong}
onPlay={(songId, ids) =>
playFromSong(songId, ids, `album:${album.id}`)
}
onAction={handleAlbumTrackAction}
/>
) : null
@@ -184,7 +186,7 @@ export default function AlbumScreen() {
stationArtistId={album.artist.id}
selectedCount={album.tracks.length}
favorited={isAlbumFav(album.id)}
share={{ type: "album", albumId: album.id }}
share={{ type: "album", albumId: album.id, title: album.title }}
onAction={(action) =>
void handleAlbumDetailAction(
album.id as Id<"albums">,
@@ -404,6 +406,7 @@ 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)}
>
@@ -75,7 +75,11 @@ export default function ArtistScreen() {
<MediaActionMenu
selectedCount={data.albums.length}
favorited={isArtistFav(data.artist.id)}
share={{ type: "artist", artistId: data.artist.id }}
share={{
type: "artist",
artistId: data.artist.id,
title: data.artist.name,
}}
onAction={(action) =>
void handleArtistAction(data.artist, action)
}
@@ -142,7 +142,7 @@ const ArtistRow = memo(function ArtistRow({
return (
<MediaContextMenu
favorited={favorited}
share={{ type: "artist", artistId: artist.id }}
share={{ type: "artist", artistId: artist.id, title: artist.name }}
onAction={(action) => void onAction(artist, action)}
>
<Pressable
@@ -1,3 +1,7 @@
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"
@@ -158,11 +162,14 @@ function PlaylistContent({
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 handlePlaySong = useCallback(
(song: BrowseSong) => void playFromSong(song.id, songIds),
[playFromSong, songIds]
(song: BrowseSong) =>
void playFromSong(song.id, songIds, `playlist:${playlistId}`),
[playFromSong, songIds, playlistId]
)
const handleSongMenuAction = useCallback(
@@ -253,6 +260,7 @@ function PlaylistContent({
share={{
type: "playlist",
playlistId: playlistId ?? "favorites",
title: playlist?.title ?? "oTunes",
}}
includeActions={canEdit ? OWNER_MENU_ACTIONS : undefined}
onAction={handlePlaylistMenuAction}
@@ -275,6 +283,7 @@ function PlaylistContent({
palette.background,
palette.isDark,
playlistId,
playlist?.title,
router,
songIds,
])
@@ -309,10 +318,14 @@ function PlaylistContent({
<StatusBar style={palette.isDark ? "light" : "dark"} />
) : null}
<Stack.Screen options={screenOptions} />
<PlaylistSearchBar
onQueryChange={onQueryChange}
onSearchSubmit={onSearchSubmit}
/>
<FlatList
onLayout={onLayout}
{...longListProps}
data={songs}
data={filteredSongs}
keyExtractor={songKey}
renderItem={renderItem}
style={{ flex: 1, backgroundColor: palette.background }}
@@ -320,6 +333,16 @@ function PlaylistContent({
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>
}
ListHeaderComponent={
<PlaylistHero
entityId={playlistId ?? "otunes:favorites"}
@@ -515,6 +538,7 @@ const PlaylistHero = memo(function PlaylistHero({
})
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,3 +1,7 @@
import {
PlaylistSearchBar,
usePlaylistSearch,
} from "@/components/playlist-search-bar"
import { memo, useCallback, useEffect, useMemo } from "react"
import {
FlatList,
@@ -37,6 +41,8 @@ export default function FavoritesScreen() {
const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions()
const songIds = useMemo(() => songs.map((song) => song.id), [songs])
const { filteredSongs, onQueryChange, onSearchSubmit } =
usePlaylistSearch(songs)
useEffect(() => {
if (favorites) rememberSongs(favorites.songs)
@@ -99,14 +105,25 @@ export default function FavoritesScreen() {
return (
<>
<Stack.Screen options={SCREEN_OPTIONS} />
<PlaylistSearchBar
onQueryChange={onQueryChange}
onSearchSubmit={onSearchSubmit}
/>
<FlatList
{...longListProps}
data={songs}
data={filteredSongs}
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>
}
ListHeaderComponent={
<FavoritesHero
title={favorites.title}
@@ -173,6 +190,7 @@ const FavoritesHero = memo(function FavoritesHero({
})
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 },
+20 -1
View File
@@ -1,3 +1,10 @@
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,
@@ -5,7 +12,7 @@ import {
} from "convex/react"
import { Stack } from "expo-router"
import { Platform } from "react-native"
import { useEffect } from "react"
import { useEffect, useSyncExternalStore } from "react"
import { AppIntentBridge } from "@/components/app-intent-bridge"
import { ConvexAuthRecovery } from "@/components/convex-auth-recovery"
@@ -24,6 +31,18 @@ export default function AppLayout() {
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 (
+57
View File
@@ -0,0 +1,57 @@
import { loadServerConfig, parseServerHostname } from "@/lib/server-config"
import { secureGetItem } from "@/lib/auth-storage"
import {
isMediaRoute,
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 ||
!isMediaRoute(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 "/"
}
}
+3
View File
@@ -9,6 +9,8 @@ import { Toaster } from "@/components/ui/toaster"
import { ConvexAppProvider } from "@/contexts/convex-app"
import { ServerConfigProvider, useServerConfig } from "@/contexts/server-config"
import { HandoffBridge } from "@/components/handoff-bridge"
const navigationTheme = {
...DarkTheme,
colors: { ...DarkTheme.colors, background: "#000", card: "#000" },
@@ -56,6 +58,7 @@ export default function RootLayout() {
<ConvexAppProvider>
<StatusBar style={isDark ? "light" : "dark"} />
<ThemeProvider value={navigationTheme}>
<HandoffBridge />
<RootNavigator />
</ThemeProvider>
<Toaster />
+10 -2
View File
@@ -1,5 +1,6 @@
import { useConvexAuth } from "@convex-dev/auth/react"
import { Redirect } from "expo-router"
import { incomingMediaLink } from "@/lib/incoming-media-link"
import { Redirect, type Href } from "expo-router"
import { useServerConfig } from "@/contexts/server-config"
@@ -11,9 +12,16 @@ export default function Index() {
return <Redirect href="/server" />
}
const destination = auth?.isAuthenticated
? incomingMediaLink(config.serverUrl)
: null
return (
<Redirect
href={auth?.isAuthenticated ? "/(app)/(tabs)/library" : "/signin"}
href={
(destination as Href) ??
(auth?.isAuthenticated ? "/(app)/(tabs)/library" : "/signin")
}
/>
)
}
+10 -2
View File
@@ -1,4 +1,5 @@
import { useState } from "react"
import { useLocalSearchParams } from "expo-router"
import { useEffect, useState } from "react"
import { StyleSheet, Text, View } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
@@ -11,7 +12,14 @@ import { spacing, useThemeColors } from "@/lib/theme"
export default function ServerScreen() {
const colors = useThemeColors()
const { setServerHostname } = useServerConfig()
const [hostname, setHostname] = useState("")
const { hostname: linkedHostname } = useLocalSearchParams<{
hostname?: string
}>()
const [hostname, setHostname] = useState(linkedHostname ?? "")
useEffect(() => {
if (linkedHostname) setHostname(linkedHostname)
}, [linkedHostname])
const [error, setError] = useState<string | null>(null)
const [submitting, setSubmitting] = useState(false)
File renamed without changes.

Before

Width:  |  Height:  |  Size: 8.8 KiB

After

Width:  |  Height:  |  Size: 8.8 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 8.8 KiB

After

Width:  |  Height:  |  Size: 8.8 KiB

+81
View File
@@ -0,0 +1,81 @@
import { useConvexAuth } from "@convex-dev/auth/react"
import { requireOptionalNativeModule, type NativeModule } from "expo"
import { usePathname } from "expo-router"
import { useEffect } from "react"
import { Platform } from "react-native"
import { useServerConfig } from "@/contexts/server-config"
import {
isMediaRoute,
rememberIncomingMediaLink,
} from "@/lib/incoming-media-link"
import { showError } from "@/lib/toast"
type Activity = { server: string; route: string }
declare class HandoffModule extends NativeModule<{ onActivity: () => void }> {
takeActivity(): Promise<Activity | null>
publish(server: string | null, route: string | null): Promise<void>
}
const handoff =
Platform.OS === "ios"
? requireOptionalNativeModule<HandoffModule>("Handoff")
: null
export function HandoffBridge() {
const { config, isLoading } = useServerConfig()
const auth = useConvexAuth()
const pathname = usePathname()
useEffect(() => {
if (!handoff || isLoading) return
let active = true
async function receive() {
const activity = await handoff!.takeActivity()
if (!active || !activity) return
try {
const source = new URL(activity.server)
if (!config || source.origin !== new URL(config.serverUrl).origin) {
showError("This activity belongs to a different oTunes server.")
return
}
if (
!["http:", "https:"].includes(source.protocol) ||
source.username ||
source.password ||
!isMediaRoute(activity.route)
)
return
rememberIncomingMediaLink(
`/(app)/(tabs)/home${activity.route}`,
source.origin
)
} catch {
// Ignore malformed activities without navigating or changing servers.
}
}
const subscription = handoff.addListener("onActivity", () => {
void receive()
})
void receive()
return () => {
active = false
subscription.remove()
}
}, [config, isLoading])
useEffect(() => {
if (!handoff) return
const route = pathname.replace(/^\/(home|search|library)/, "")
const canPublish = config && auth?.isAuthenticated && isMediaRoute(route)
void handoff.publish(
canPublish ? config.serverUrl : null,
canPublish ? route : null
)
return () => {
void handoff.publish(null, null)
}
}, [config, auth?.isAuthenticated, pathname])
return null
}
+7 -3
View File
@@ -80,7 +80,7 @@ export const AlbumCard = memo(function AlbumCard({
favorited={isAlbumFavorite(album.id)}
stationArtistId={album.artist.id}
navigation={{ artist: { id: album.artist.id } }}
share={{ type: "album", albumId: album.id }}
share={{ type: "album", albumId: album.id, title: album.title }}
onAction={(action) => void handleAlbumAction(album, action)}
>
<MusicEntityView kind="album" id={album.id}>
@@ -125,7 +125,7 @@ export const ArtistCard = memo(function ArtistCard({
return (
<MediaContextMenu
favorited={isArtistFavorite(artist.id)}
share={{ type: "artist", artistId: artist.id }}
share={{ type: "artist", artistId: artist.id, title: artist.name }}
onAction={(action) => void handleArtistAction(artist, action)}
>
<MusicEntityView kind="artist" id={artist.id}>
@@ -176,7 +176,11 @@ export const PlaylistCard = memo(function PlaylistCard({
return (
<MediaContextMenu
showFavorite={false}
share={{ type: "playlist", playlistId: playlist.id }}
share={{
type: "playlist",
playlistId: playlist.id,
title: playlist.title,
}}
onAction={(action) => void handlePlaylistAction(playlist, action)}
>
<MusicEntityView kind="playlist" id={playlist.id}>
@@ -59,7 +59,8 @@ export function MenuView({
outlineVariant: "#545458",
error: "#FF453A",
}}
matchContents
// Rows fill their parent width; compact action buttons keep intrinsic sizing.
matchContents={shouldOpenOnLongPress ? { vertical: true } : true}
>
<DropdownMenu
expanded={expanded}
@@ -70,7 +71,9 @@ export function MenuView({
properties={{ clippingEnabled: false }}
>
<DropdownMenu.Trigger>
<RNHostView matchContents>
<RNHostView
matchContents={shouldOpenOnLongPress ? { vertical: true } : true}
>
{shouldOpenOnLongPress ? (
<GestureDetector gesture={longPress}>
<View collapsable={false}>{children}</View>
+1
View File
@@ -147,6 +147,7 @@ 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),
}}
@@ -0,0 +1,56 @@
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,
}
: {})}
/>
)
}
+71 -33
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef } from "react"
import { useEffect, useRef, type ReactNode } from "react"
import {
Animated,
ScrollView,
@@ -18,6 +18,30 @@ 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
@@ -74,13 +98,21 @@ export function SongRowSkeleton() {
)
}
export function SongListSkeleton({ rows = 10 }: { rows?: number }) {
export function SongListSkeleton({
rows = 10,
embedded = false,
}: {
rows?: number
embedded?: boolean
}) {
return (
<View accessibilityLabel="Loading" accessibilityRole="progressbar">
{Array.from({ length: rows }, (_, index) => (
<SongRowSkeleton key={index} />
))}
</View>
<SkeletonContent embedded={embedded}>
<View accessibilityLabel="Loading" accessibilityRole="progressbar">
{Array.from({ length: rows }, (_, index) => (
<SongRowSkeleton key={index} />
))}
</View>
</SkeletonContent>
)
}
@@ -109,24 +141,28 @@ function CardSkeleton({
export function MediaGridSkeleton({
items = 6,
contentInset = true,
embedded = false,
}: {
items?: number
contentInset?: boolean
embedded?: boolean
}) {
const cardWidth = useTwoColumnCardWidth()
return (
<View
accessibilityLabel="Loading"
accessibilityRole="progressbar"
style={[
styles.grid,
contentInset ? styles.gridInset : styles.gridRowInset,
]}
>
{Array.from({ length: items }, (_, index) => (
<CardSkeleton key={index} width={cardWidth} />
))}
</View>
<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>
)
}
@@ -192,9 +228,9 @@ export function CollectionDetailSkeleton({
</View>
</View>
{round ? (
<MediaGridSkeleton items={4} contentInset={false} />
<MediaGridSkeleton items={4} contentInset={false} embedded />
) : (
<SongListSkeleton rows={8} />
<SongListSkeleton rows={8} embedded />
)}
</ScrollView>
)
@@ -203,17 +239,19 @@ export function CollectionDetailSkeleton({
export function ArtistListSkeleton({ rows = 12 }: { rows?: number }) {
const colors = useThemeColors()
return (
<View accessibilityLabel="Loading" accessibilityRole="progressbar">
{Array.from({ length: rows }, (_, index) => (
<View
key={index}
style={[styles.artistRow, { borderBottomColor: colors.border }]}
>
<Skeleton style={styles.artistAvatar} />
<TextLine width="50%" height={16} />
</View>
))}
</View>
<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>
)
}
@@ -233,7 +271,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 },
carousel: { gap: spacing.md, overflow: "hidden" },
carouselRow: { flexDirection: "row", gap: spacing.md },
home: { padding: spacing.lg, gap: spacing.xl },
hero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm },
+52 -13
View File
@@ -87,7 +87,11 @@ type PlaybackContextValue = {
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">[]) => Promise<void>
playFromSong: (
songId: Id<"songs">,
songIds: Id<"songs">[],
origin?: string
) => Promise<void>
playFromLibrarySong: (
songId: Id<"songs">,
sort: {
@@ -264,11 +268,13 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
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 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)
@@ -348,6 +354,21 @@ 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
@@ -565,11 +586,12 @@ 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, store])
}, [currentSongId, destroyPlaylist, queueStartVersion, store])
useEffect(() => {
if (progressToRestore === null || progressToRestore <= 0) return
@@ -807,6 +829,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
handlePlaybackLoadFailure,
historySyncKey,
queueSyncKey,
queueStartVersion,
repeatEnabled,
scheduleTrackChangeHandling,
userPlaybackKey,
@@ -827,18 +850,19 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
) => playbackQueue.PlaybackQueueState,
recorded: {
playlistId?: Id<"playlists">
origin?: string
entity?: { kind: MusicEntityKind; id: string }
} = {}
) => {
playRequestRef.current += 1
const previousSongId = store.getState().queue[0]
queueOriginRef.current =
recorded.origin ??
(recorded.playlistId ? `playlist:${recorded.playlistId}` : undefined)
resetQueuePlayback()
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
@@ -869,7 +893,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
: { songId: firstSongId }
)
},
[store, seekTo, setIsPlaying, recordPlay]
[store, resetQueuePlayback, setIsPlaying, recordPlay]
)
const playCollection = useCallback(
@@ -878,6 +902,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
shuffled: boolean,
recorded: {
playlistId?: Id<"playlists">
origin?: string
entity?: { kind: MusicEntityKind; id: string }
} = {}
) => {
@@ -942,12 +967,19 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
)
const playFromSong = useCallback(
async (songId: Id<"songs">, songIds: Id<"songs">[]) => {
startPlayback((state) =>
playbackQueue.startQueueFromSong(state, songId, songIds)
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 }
)
},
[startPlayback]
[startPlayback, store]
)
const playFromLibrarySong = useCallback(
@@ -1017,6 +1049,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
(albumId: Id<"albums">, songIds?: Id<"songs">[]) =>
playCollection(loadAlbumSongIds(albumId, songIds), false, {
entity: { kind: "album", id: albumId },
origin: `album:${albumId}`,
}),
[playCollection, loadAlbumSongIds]
)
@@ -1025,6 +1058,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
(albumId: Id<"albums">, songIds?: Id<"songs">[]) =>
playCollection(loadAlbumSongIds(albumId, songIds), true, {
entity: { kind: "album", id: albumId },
origin: `album:${albumId}`,
}),
[playCollection, loadAlbumSongIds]
)
@@ -1087,12 +1121,14 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
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, setIsPlaying]
[store, resetQueuePlayback, setIsPlaying]
)
const startFromSong = useCallback(
@@ -1103,17 +1139,20 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
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, setIsPlaying]
[store, resetQueuePlayback, setIsPlaying]
)
const clearQueue = useCallback(async () => {
playRequestRef.current += 1
queueOriginRef.current = undefined
store.update(playbackQueue.clearQueue)
setIsPlaying(false)
}, [store, setIsPlaying])
+35
View File
@@ -0,0 +1,35 @@
// 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()
}
// Shared by native links and Handoff. Only concrete media screens are routable.
export function isMediaRoute(path: string) {
return /^\/(album|artist|playlist)\/[a-zA-Z0-9_-]+$/.test(path)
}
+2 -1
View File
@@ -1,8 +1,9 @@
export type MediaShareContext =
export type MediaShareContext = (
| { type: "album"; albumId: string }
| { type: "song"; albumId: string; songId: string }
| { type: "playlist"; playlistId: string; isFavorites?: boolean }
| { type: "artist"; artistId: string }
) & { title: string }
export function shouldShowShare(
share: MediaShareContext | undefined,
+27 -2
View File
@@ -1,3 +1,4 @@
import { requireOptionalNativeModule } from "expo"
import * as Sharing from "expo-sharing"
import { Platform, Share } from "react-native"
@@ -5,6 +6,10 @@ import type { MediaShareContext } from "@/lib/media-links"
import { mediaShareUrl } from "@/lib/media-links"
import { showError } from "@/lib/toast"
const nativeShare = requireOptionalNativeModule<{
share: (url: string, artwork: string, title: string) => Promise<void>
}>("MediaLinkShare")
export async function shareMediaLink(
serverUrl: string,
share: MediaShareContext
@@ -17,12 +22,32 @@ export async function shareMediaLink(
showError("Sharing is not available on this device")
return
}
await Sharing.shareAsync(url, { dialogTitle: "Share" })
await Sharing.shareAsync(url, { dialogTitle: share.title })
return
}
if (nativeShare) {
const type = share.type === "song" ? "album" : share.type
const id =
share.type === "album" || share.type === "song"
? share.albumId
: share.type === "artist"
? share.artistId
: share.isFavorites
? "favorites"
: share.playlistId
await nativeShare.share(
url,
`${serverUrl.replace(/\/+$/, "")}/api/${type}/${id}/cover?size=512`,
share.title
)
return
}
await Share.share(
Platform.OS === "ios" ? { url } : { message: url }
Platform.OS === "ios"
? { url, title: share.title }
: { message: url, title: share.title }
)
} catch (error) {
if (error instanceof Error && /cancel/i.test(error.message)) {
@@ -0,0 +1,7 @@
{
"platforms": ["apple"],
"apple": {
"modules": ["HandoffModule"],
"appDelegateSubscribers": ["HandoffAppDelegateSubscriber"]
}
}
@@ -0,0 +1,16 @@
Pod::Spec.new do |s|
s.name = 'Handoff'
s.version = '1.0.0'
s.summary = 'Native media screen Handoff for oTunes'
s.description = s.summary
s.license = { :type => 'MIT' }
s.author = 'oTunes'
s.homepage = 'https://otunes.abunchofknowitalls.com'
s.platforms = { :ios => '16.4' }
s.swift_version = '5.9'
s.source = { :git => '' }
s.static_framework = true
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
s.dependency 'ExpoModulesCore'
s.source_files = '**/*.swift'
end
@@ -0,0 +1,70 @@
import ExpoModulesCore
import UIKit
// Retain the latest continuation until JS is mounted, including cold launches.
private enum HandoffState {
static var activity: NSUserActivity?
static var pending: [String: String]?
static var notify: (() -> Void)?
static var activityType: String {
"\(Bundle.main.bundleIdentifier!).media"
}
}
public final class HandoffAppDelegateSubscriber: ExpoAppDelegateSubscriber {
public func application(
_ application: UIApplication,
continue userActivity: NSUserActivity,
restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void
) -> Bool {
guard userActivity.activityType == HandoffState.activityType,
let server = userActivity.userInfo?["server"] as? String,
let route = userActivity.userInfo?["route"] as? String
else { return false }
HandoffState.pending = ["server": server, "route": route]
HandoffState.notify?()
return true
}
}
public final class HandoffModule: Module {
public func definition() -> ModuleDefinition {
Name("Handoff")
Events("onActivity")
OnStartObserving {
HandoffState.notify = { [weak self] in self?.sendEvent("onActivity") }
if HandoffState.pending != nil { HandoffState.notify?() }
}
OnStopObserving { HandoffState.notify = nil }
AsyncFunction("takeActivity") { () -> [String: String]? in
defer { HandoffState.pending = nil }
return HandoffState.pending
}.runOnQueue(.main)
AsyncFunction("publish") { (server: String?, route: String?) in
HandoffState.activity?.invalidate()
HandoffState.activity = nil
guard let server, let route else { return }
let activity = NSUserActivity(activityType: HandoffState.activityType)
activity.title = "oTunes"
activity.userInfo = ["server": server, "route": route]
activity.requiredUserInfoKeys = ["server", "route"]
activity.isEligibleForHandoff = true
activity.isEligibleForSearch = false
activity.isEligibleForPublicIndexing = false
HandoffState.activity = activity
activity.becomeCurrent()
}.runOnQueue(.main)
OnDestroy {
DispatchQueue.main.async {
HandoffState.activity?.invalidate()
HandoffState.activity = nil
HandoffState.notify = nil
}
}
}
}
+5
View File
@@ -0,0 +1,5 @@
{
"name": "otunes-handoff",
"version": "1.0.0",
"private": true
}
+53
View File
@@ -0,0 +1,53 @@
package com.abunchofknowitalls.otunes
import android.content.ClipData
import android.content.Intent
import androidx.core.content.FileProvider
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
import java.io.File
import java.net.URL
class MediaLinkShare : Module() {
override fun definition() = ModuleDefinition {
Name("MediaLinkShare")
AsyncFunction("share") { link: String, artwork: String, title: String ->
val context = requireNotNull(appContext.reactContext)
val intent = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
putExtra(Intent.EXTRA_TEXT, link)
putExtra(Intent.EXTRA_TITLE, title)
putExtra(Intent.EXTRA_SUBJECT, title)
}
// ClipData supplies the chooser thumbnail while the shared item stays a URL.
try {
val connection = URL(artwork).openConnection().apply {
connectTimeout = 8000
readTimeout = 8000
}
context.cacheDir.listFiles()?.filter {
it.name.startsWith("media-link-cover-") && it.lastModified() < System.currentTimeMillis() - 86400000
}?.forEach { it.delete() }
val extension = when (connection.contentType?.substringBefore(";")) {
"image/webp" -> "webp"
"image/png" -> "png"
"image/jpeg" -> "jpg"
"image/gif" -> "gif"
else -> error("Artwork format is not supported")
}
val file = File(context.cacheDir, "media-link-cover-${java.util.UUID.randomUUID()}.${extension}")
connection.getInputStream().use { input ->
file.outputStream().use { output -> input.copyTo(output) }
}
val uri = FileProvider.getUriForFile(context, context.packageName + ".SharingFileProvider", file)
intent.clipData = ClipData.newUri(context.contentResolver, "Artwork", uri)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
} catch (_: Exception) {
// A failed artwork download must not prevent sharing the link.
}
appContext.throwingActivity.runOnUiThread {
appContext.throwingActivity.startActivity(Intent.createChooser(intent, "Share"))
}
}
}
}
+55
View File
@@ -0,0 +1,55 @@
import UIKit
import LinkPresentation
internal import ExpoModulesCore
private final class MediaLinkItem: NSObject, UIActivityItemSource {
let url: URL
let image: UIImage?
let title: String
init(url: URL, image: UIImage?, title: String) {
self.url = url
self.image = image
self.title = title
}
func activityViewControllerPlaceholderItem(_ controller: UIActivityViewController) -> Any { url }
func activityViewController(_ controller: UIActivityViewController, itemForActivityType: UIActivity.ActivityType?) -> Any? { url }
func activityViewControllerLinkMetadata(_ controller: UIActivityViewController) -> LPLinkMetadata? {
let metadata = LPLinkMetadata()
metadata.originalURL = url
metadata.url = url
metadata.title = title
if let image {
metadata.imageProvider = NSItemProvider(object: image)
metadata.iconProvider = NSItemProvider(object: image)
}
return metadata
}
}
final class MediaLinkShare: Module {
public func definition() -> ExpoModulesCore.ModuleDefinition {
Name("MediaLinkShare")
AsyncFunction("share") { (link: String, artwork: String, title: String) in
guard let url = URL(string: link), let artworkURL = URL(string: artwork) else { return }
var image: UIImage?
var request = URLRequest(url: artworkURL)
request.timeoutInterval = 8
if let (data, response) = try? await URLSession.shared.data(for: request),
(response as? HTTPURLResponse)?.statusCode == 200 {
image = UIImage(data: data)
}
let artworkImage = image
await MainActor.run {
guard let presenter = self.appContext?.utilities?.currentViewController() else { return }
let controller = UIActivityViewController(
activityItems: [MediaLinkItem(url: url, image: artworkImage, title: title)], applicationActivities: nil)
if let popover = controller.popoverPresentationController {
popover.sourceView = presenter.view
popover.sourceRect = CGRect(x: presenter.view.bounds.midX, y: presenter.view.bounds.midY, width: 0, height: 0)
popover.permittedArrowDirections = []
}
presenter.present(controller, animated: true)
}
}
}
}
+7 -1
View File
@@ -5,6 +5,8 @@ import { PlayerBar } from "@/components/player-bar"
import { LazyQueuePanel } from "@/components/lazy-queue-panel"
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
import { AppSidebar } from "@/components/app-sidebar"
import { ScrollRestoration } from "@/components/scroll-restoration"
import { Suspense } from "react"
export default function AppLayout({
children,
@@ -18,7 +20,11 @@ export default function AppLayout({
<FavoritesProvider>
<AppSidebar />
<div className="flex min-h-svh min-w-0 flex-1">
<SidebarInset className="min-w-0 flex-1">{children}</SidebarInset>
<SidebarInset className="min-w-0 flex-1">
<Suspense>
<ScrollRestoration>{children}</ScrollRestoration>
</Suspense>
</SidebarInset>
<LazyQueuePanel />
</div>
<PlayerBar />
+3 -2
View File
@@ -389,7 +389,7 @@ export function AlbumView({
return (
<div className="flex h-svh flex-col">
<PageHeader />
<PageHeader openApp />
<ScrollArea className="min-h-0 flex-1 [&_[data-slot=scroll-area-viewport]>div]:block!">
<div className="pb-28">
<div className="mx-auto w-full min-w-0 max-w-9/10">
@@ -547,7 +547,8 @@ export function AlbumView({
onPlay={() =>
void playFromSong(
track.id as Id<"songs">,
albumSongIds
albumSongIds,
`album:${album.id}`
)
}
/>
+1 -1
View File
@@ -65,7 +65,7 @@ export function ArtistView({
return (
<div className="flex h-svh flex-col">
<PageHeader />
<PageHeader openApp />
<ScrollArea className="min-h-0 flex-1">
<div className="pb-28">
<div className="flex min-w-0 items-center gap-4 px-6 pt-6 pb-8 sm:gap-6">
+14 -2
View File
@@ -1,3 +1,4 @@
import { OpenAppButton } from "@/components/open-app-button"
import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger"
import { Skeleton } from "@/components/ui/skeleton"
import { albumGridClassName } from "@/lib/album-grid-classes"
@@ -19,7 +20,13 @@ function LoadingRegion({
)
}
export function PageHeader({ title }: { title?: string }) {
export function PageHeader({
title,
openApp = false,
}: {
title?: string
openApp?: boolean
}) {
return (
<header
className={cn(
@@ -28,7 +35,12 @@ export function PageHeader({ title }: { title?: string }) {
)}
>
<MobileSidebarTrigger />
{title ? <h1 className="text-lg font-semibold">{title}</h1> : null}
{title ? (
<h1 className="text-lg font-semibold">{title}</h1>
) : openApp ? (
<span className="font-semibold">oTunes</span>
) : null}
{openApp ? <OpenAppButton /> : null}
</header>
)
}
+22
View File
@@ -0,0 +1,22 @@
"use client"
import { ArrowUpRight } from "lucide-react"
export function OpenAppButton() {
function openApp() {
const link = new URL("otunes://open")
link.searchParams.set("url", window.location.href)
window.location.assign(link.href)
}
return (
<button
type="button"
onClick={openApp}
className="ml-auto inline-flex shrink-0 items-center gap-1 text-sm font-medium hover:underline focus-visible:outline-2 focus-visible:outline-offset-4 md:hidden"
>
Open App
<ArrowUpRight aria-hidden className="size-4" />
</button>
)
}
+28 -9
View File
@@ -63,7 +63,11 @@ type PlaybackContextValue = {
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">[]) => Promise<void>
playFromSong: (
songId: Id<"songs">,
songIds: Id<"songs">[],
origin?: string
) => Promise<void>
playFromLibrarySong: (
songId: Id<"songs">,
sort: {
@@ -1050,6 +1054,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
}
}, [currentSongId, currentSong])
const queueOriginRef = useRef<string | undefined>(undefined)
const playRequestRef = useRef(0)
const startPlayback = useCallback(
@@ -1057,9 +1062,12 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
recipe: (
state: playbackQueue.PlaybackQueueState
) => playbackQueue.PlaybackQueueState,
recorded: { playlistId?: Id<"playlists"> } = {}
recorded: { playlistId?: Id<"playlists">; origin?: string } = {}
) => {
playRequestRef.current += 1
queueOriginRef.current =
recorded.origin ??
(recorded.playlistId ? `playlist:${recorded.playlistId}` : undefined)
const previousSongId = store.getState().queue[0]
store.update(recipe)
const firstSongId = store.getState().queue[0]
@@ -1084,7 +1092,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
async (
songIds: Id<"songs">[] | Promise<Id<"songs">[]>,
shuffled: boolean,
recorded: { playlistId?: Id<"playlists"> } = {}
recorded: { playlistId?: Id<"playlists">; origin?: string } = {}
) => {
const request = ++playRequestRef.current
let resolvedSongIds: Id<"songs">[]
@@ -1149,12 +1157,19 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
)
const playFromSong = useCallback(
async (songId: Id<"songs">, songIds: Id<"songs">[]) => {
startPlayback((state) =>
playbackQueue.startQueueFromSong(state, songId, songIds)
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 }
)
},
[startPlayback]
[startPlayback, store]
)
const playFromLibrarySong = useCallback(
@@ -1222,13 +1237,17 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
const playAlbum = useCallback(
(albumId: Id<"albums">, songIds?: Id<"songs">[]) =>
playCollection(loadAlbumSongIds(albumId, songIds), false),
playCollection(loadAlbumSongIds(albumId, songIds), false, {
origin: `album:${albumId}`,
}),
[playCollection, loadAlbumSongIds]
)
const playAlbumShuffled = useCallback(
(albumId: Id<"albums">, songIds?: Id<"songs">[]) =>
playCollection(loadAlbumSongIds(albumId, songIds), true),
playCollection(loadAlbumSongIds(albumId, songIds), true, {
origin: `album:${albumId}`,
}),
[playCollection, loadAlbumSongIds]
)
+29 -25
View File
@@ -76,8 +76,8 @@ export function PlayerBar() {
queueOpen && !isMobile && "right-72"
)}
>
<div className="pointer-events-auto flex w-full max-w-6xl items-center gap-2 rounded-full border border-white/20 bg-[#303033] px-3 py-2 text-white shadow-lg @min-[640px]:gap-5 @min-[640px]:px-5 @min-[640px]:py-3">
<div className="flex shrink-0 items-center gap-0 @min-[640px]:gap-1 [&_button]:size-7 @min-[640px]:[&_button]:size-10 [&_svg]:size-4 @min-[640px]:[&_svg]:size-6">
<div className="pointer-events-auto flex w-full max-w-[40rem] items-center gap-2 rounded-full border border-foreground/20 bg-(--player-background) px-3 py-2 text-card-foreground shadow-lg [--player-background:var(--card)] md:gap-3 md:py-1.5 dark:border-white/20 dark:text-white dark:[--player-background:#303033]">
<div className="flex shrink-0 items-center gap-0 md:gap-0.5 [&_button]:size-7 [&_svg]:size-4">
<Button
variant="ghost"
size="icon"
@@ -85,11 +85,13 @@ export function PlayerBar() {
aria-pressed={shuffleEnabled}
className={cn(
"hidden @min-[640px]:inline-flex",
shuffleEnabled ? "text-white" : "text-white/40"
shuffleEnabled
? "text-card-foreground dark:text-white"
: "text-muted-foreground dark:text-white/40"
)}
onClick={() => void toggleShuffle()}
>
<Shuffle className="size-4 @min-[640px]:size-6" />
<Shuffle className="size-4" />
</Button>
<Button
variant="ghost"
@@ -98,7 +100,7 @@ export function PlayerBar() {
disabled={!hasQueue}
onClick={() => void skipPrevious()}
>
<SkipBack className="size-4 fill-current @min-[640px]:size-6" />
<SkipBack className="size-4 fill-current" />
</Button>
<Button
variant="ghost"
@@ -108,9 +110,9 @@ export function PlayerBar() {
onClick={() => setIsPlaying(!isPlaying)}
>
{isPlaying ? (
<Pause className="size-5! fill-current @min-[640px]:size-8!" />
<Pause className="size-5! fill-current" />
) : (
<Play className="size-5! fill-current @min-[640px]:size-8!" />
<Play className="size-5! fill-current" />
)}
</Button>
<Button
@@ -120,7 +122,7 @@ export function PlayerBar() {
disabled={!hasQueue}
onClick={() => void skipNext()}
>
<SkipForward className="size-4 fill-current @min-[640px]:size-6" />
<SkipForward className="size-4 fill-current" />
</Button>
<Button
variant="ghost"
@@ -129,38 +131,40 @@ export function PlayerBar() {
aria-pressed={repeatEnabled !== "none"}
className={cn(
"hidden @min-[640px]:inline-flex",
repeatEnabled !== "none" ? "text-white" : "text-white/40"
repeatEnabled !== "none"
? "text-card-foreground dark:text-white"
: "text-muted-foreground dark:text-white/40"
)}
onClick={() => void cycleRepeat()}
>
{repeatEnabled === "once" ? (
<Repeat1 className="size-4 @min-[640px]:size-6" />
<Repeat1 className="size-4" />
) : (
<Repeat className="size-4 @min-[640px]:size-6" />
<Repeat className="size-4" />
)}
</Button>
</div>
<div className="relative flex min-w-0 flex-1 items-center gap-2 pb-2 @min-[640px]:gap-3">
<div className="relative flex h-11 min-w-0 flex-1 items-center gap-2 pb-2 md:h-9 md:pb-1">
{currentSong ? (
<>
<div className="relative size-9 shrink-0 overflow-hidden rounded @min-[640px]:size-14">
<div className="relative size-9 shrink-0 overflow-hidden rounded md:size-8">
<Image
src={albumCoverUrl(currentSong.album.id)}
alt={currentSong.album.title}
fill
sizes="56px"
sizes="36px"
className="object-cover"
/>
</div>
<div className="min-w-0 flex-1">
<Link
href={`/album/${currentSong.album.id}`}
className="block truncate text-sm font-semibold hover:underline @min-[640px]:text-xl"
className="block truncate text-sm font-semibold hover:underline md:text-[13px] md:leading-4"
>
{currentSong.title}
</Link>
<p className="truncate text-xs @min-[640px]:text-lg">
<p className="truncate text-xs">
<Link
href={`/artist/${currentSong.artist.id}`}
className="hover:underline"
@@ -180,23 +184,23 @@ export function PlayerBar() {
<AudioFormatBadge
format={currentFormat}
iconOnly
backgroundColor="#303033"
backgroundColor="var(--player-background)"
/>
) : null}
</>
) : (
<Image
src="/logo-monochrome.svg"
src="/logo.png"
alt="oTunes"
width={14}
width={24}
height={24}
className="mx-auto my-2 h-6 w-auto opacity-85"
className="mx-auto size-6 opacity-85"
/>
)}
<div className="absolute inset-x-0 -bottom-1">
<Slider
className={cn(
"h-3 flex-1 [&_[data-slot=slider-range]]:bg-white/80 [&_[data-slot=slider-thumb]]:size-2 [&_[data-slot=slider-thumb]]:opacity-0 focus-within:[&_[data-slot=slider-thumb]]:opacity-100 hover:[&_[data-slot=slider-thumb]]:opacity-100 [&_[data-slot=slider-track]]:h-[3px] [&_[data-slot=slider-track]]:bg-white/30",
"h-3 flex-1 [&_[data-slot=slider-range]]:bg-current/80 [&_[data-slot=slider-thumb]]:size-2 [&_[data-slot=slider-thumb]]:border-current [&_[data-slot=slider-thumb]]:bg-current [&_[data-slot=slider-thumb]]:opacity-0 focus-within:[&_[data-slot=slider-thumb]]:opacity-100 hover:[&_[data-slot=slider-thumb]]:opacity-100 [&_[data-slot=slider-track]]:h-[3px] [&_[data-slot=slider-track]]:bg-current/30 md:[&_[data-slot=slider-track]]:h-0.5",
!hasActiveSong && "[&_[data-slot=slider-thumb]]:hidden"
)}
min={0}
@@ -218,7 +222,7 @@ export function PlayerBar() {
</div>
</div>
<div className="flex shrink-0 items-center gap-0 @min-[640px]:gap-2 [&_button]:size-7 @min-[640px]:[&_button]:size-10 [&_svg]:size-4 @min-[640px]:[&_svg]:size-6">
<div className="flex shrink-0 items-center gap-0 md:gap-1 [&_button]:size-7 [&_svg]:size-4">
<Button
variant="ghost"
size="icon"
@@ -226,7 +230,7 @@ export function PlayerBar() {
aria-label="Lyrics"
disabled
>
<MessageSquareQuote className="size-4 @min-[640px]:size-6" />
<MessageSquareQuote className="size-4" />
</Button>
<Button
variant="ghost"
@@ -236,12 +240,12 @@ export function PlayerBar() {
className={cn(queueOpen && "text-primary")}
onClick={toggleQueueOpen}
>
<ListMusic className="size-4 @min-[640px]:size-6" />
<ListMusic className="size-4" />
</Button>
<Popover>
<PopoverTrigger asChild>
<Button variant="ghost" size="icon" aria-label="Volume">
<Volume2 className="size-4 @min-[640px]:size-6" />
<Volume2 className="size-4" />
</Button>
</PopoverTrigger>
<PopoverContent side="top" align="end" className="w-40">
+61 -13
View File
@@ -6,7 +6,7 @@ import * as React from "react"
import Image from "next/image"
import { useRouter } from "next/navigation"
import { useMutation } from "convex/react"
import { Play, Share2, Shuffle, Star, Trash2 } from "lucide-react"
import { Play, SearchIcon, Share2, Shuffle, Star, Trash2 } from "lucide-react"
import { toast } from "sonner"
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
@@ -305,6 +305,19 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
const songs = isFavorites
? playlist.songs.filter((song) => !hiddenFavoriteIds.has(song.id))
: playlistSongs
const [searchQuery, setSearchQuery] = React.useState("")
const normalizedQuery = searchQuery.trim().toLowerCase()
const filteredSongs = React.useMemo(
() =>
normalizedQuery
? songs.filter((song) =>
[song.title, song.artist.name, song.album.title].some((value) =>
value.toLowerCase().includes(normalizedQuery)
)
)
: songs,
[songs, normalizedQuery]
)
const playlistSongIds = React.useMemo(
() => songs.map((song) => song.id as Id<"songs">),
[songs]
@@ -327,7 +340,8 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
handleSelect,
handlePointerDown,
prepareContextMenu,
} = useTrackSelection(songs)
clearSelection,
} = useTrackSelection(filteredSongs)
const selectedStationArtistId = React.useMemo(
() => stationArtistId(songs, selectedIds),
@@ -335,8 +349,12 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
)
const selectionPositions = React.useMemo(
() => getSelectionRangePositions(songs.map((song) => song.id), selectedIds),
[songs, selectedIds]
() =>
getSelectionRangePositions(
filteredSongs.map((song) => song.id),
selectedIds
),
[filteredSongs, selectedIds]
)
const totalDurationSeconds = React.useMemo(
() => sumDurationSeconds(songs),
@@ -461,7 +479,13 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
}
function handleDrop(targetIndex: number) {
if (isFavorites || !isOwner || dragIndex === null || dragIndex === targetIndex) {
if (
normalizedQuery ||
isFavorites ||
!isOwner ||
dragIndex === null ||
dragIndex === targetIndex
) {
setDragIndex(null)
return
}
@@ -519,7 +543,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
return (
<div className="flex h-svh flex-col">
<PageHeader />
<PageHeader openApp />
<ScrollArea className="min-h-0 flex-1">
<div className="pb-28">
<div className="mx-auto w-full min-w-0 max-w-9/10">
@@ -633,13 +657,31 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
</div>
</div>
{songs.length > 0 ? (
songs.map((song, index) => (
<div className="px-6 pb-4">
<div className="relative max-w-sm">
<SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
<input
type="search"
aria-label="Search playlist"
placeholder="Search playlist"
value={searchQuery}
onChange={(event) => {
setSearchQuery(event.target.value)
clearSelection()
setActiveTrackId("")
setDragIndex(null)
}}
className="h-10 w-full min-w-0 rounded-full border border-input bg-input/30 pr-3 pl-9 text-sm text-foreground transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50"
/>
</div>
</div>
{filteredSongs.length > 0 ? (
filteredSongs.map((song, index) => (
<PlaylistSongRow
key={song.id}
song={song}
index={index}
isOwner={isOwner && !isFavorites}
isOwner={isOwner && !isFavorites && !normalizedQuery}
canRemove={isFavorites || isOwner}
showFavoriteInMenu={!isFavorites}
removeLabel={
@@ -679,14 +721,14 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
onMediaAction={handleMediaAction}
onRemove={() => handleRemoveSong(song.id)}
onDragStart={(event) => {
if (isFavorites || !isOwner) {
if (normalizedQuery || isFavorites || !isOwner) {
return
}
setDragIndex(index)
event.dataTransfer.effectAllowed = "move"
}}
onDragOver={(event) => {
if (isFavorites || !isOwner) {
if (normalizedQuery || isFavorites || !isOwner) {
return
}
event.preventDefault()
@@ -697,13 +739,19 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
}}
isNowPlaying={currentSong?.id === song.id}
onPlay={() =>
void playFromSong(song.id as Id<"songs">, playlistSongIds)
void playFromSong(
song.id as Id<"songs">,
playlistSongIds,
`playlist:${playlist.id}`
)
}
/>
))
) : (
<p className="px-6 py-8 text-sm text-muted-foreground">
This playlist has no songs yet.
{normalizedQuery
? "No songs found."
: "This playlist has no songs yet."}
</p>
)}
<MediaCollectionFooter
+107
View File
@@ -0,0 +1,107 @@
"use client"
import { useLayoutEffect, useRef } from "react"
import { usePathname, useSearchParams } from "next/navigation"
const historyKey = "otunesScrollKey"
const scrollSelector = '[data-slot="scroll-area-viewport"], .overflow-y-auto'
type Position = { top: number; left: number }
// Track page containers independently of the window, including split library views.
export function ScrollRestoration({ children }: { children: React.ReactNode }) {
const pathname = usePathname()
const searchParams = useSearchParams()
const route = `${pathname}?${searchParams.toString()}`
const rootRef = useRef<HTMLDivElement>(null)
const positions = useRef(new Map<string, Map<number, Position>>())
useLayoutEffect(() => {
const root = rootRef.current
if (!root) return
const key =
typeof history.state?.[historyKey] === "string"
? (history.state[historyKey] as string)
: crypto.randomUUID()
history.replaceState({ ...history.state, [historyKey]: key }, "")
const saved = positions.current.get(key)
const pending = new Map(saved)
if (!positions.current.has(key)) positions.current.set(key, new Map())
// Bound memory during long listening sessions.
if (positions.current.size > 100) {
const oldest = positions.current.keys().next().value
if (oldest !== undefined) positions.current.delete(oldest)
}
const containers = () =>
Array.from(root.querySelectorAll<HTMLElement>(scrollSelector)).filter(
(element) => element.getClientRects().length > 0
)
const restore = () => {
for (const [index, element] of containers().entries()) {
const position = pending.get(index)
if (!position) continue
element.scrollTo({
top: position.top,
left: position.left,
behavior: "instant",
})
// Keep waiting if asynchronous content is still too short.
if (
Math.abs(element.scrollTop - position.top) < 1 &&
Math.abs(element.scrollLeft - position.left) < 1
) {
pending.delete(index)
}
}
}
const record = (event: Event) => {
if (!(event.target instanceof HTMLElement)) return
const index = containers().indexOf(event.target)
if (index < 0 || pending.has(index)) return
positions.current.get(key)?.set(index, {
top: event.target.scrollTop,
left: event.target.scrollLeft,
})
}
const stopRestoring = () => {
pending.clear()
observer.disconnect()
resizeObserver.disconnect()
}
const observer = new MutationObserver(() => {
restore()
for (const element of containers()) {
resizeObserver.observe(element)
for (const child of element.children) resizeObserver.observe(child)
}
})
const resizeObserver = new ResizeObserver(restore)
if (pending.size) {
observer.observe(root, { childList: true, subtree: true })
for (const element of containers()) {
resizeObserver.observe(element)
for (const child of element.children) resizeObserver.observe(child)
}
restore()
}
const timeout = window.setTimeout(stopRestoring, 10_000)
root.addEventListener("scroll", record, true)
root.addEventListener("wheel", stopRestoring, { passive: true })
root.addEventListener("touchstart", stopRestoring, { passive: true })
root.addEventListener("keydown", stopRestoring)
return () => {
window.clearTimeout(timeout)
stopRestoring()
root.removeEventListener("scroll", record, true)
root.removeEventListener("wheel", stopRestoring)
root.removeEventListener("touchstart", stopRestoring)
root.removeEventListener("keydown", stopRestoring)
}
}, [route])
return (
<div ref={rootRef} className="contents">
{children}
</div>
)
}
+5 -1
View File
@@ -64,7 +64,11 @@ export function startQueueFromSong(
songIds: Id<"songs">[]
): PlaybackQueueState {
const index = songIds.indexOf(songId)
const rest = index === -1 ? [] : songIds.slice(index + 1)
const rest = state.shuffleEnabled
? uniqueSongIds(songIds).filter((id) => id !== songId)
: index === -1
? []
: songIds.slice(index + 1)
return {
...state,
queue: [songId, ...(state.shuffleEnabled ? shuffleArray(rest) : rest)],
+10 -2
View File
@@ -433,7 +433,11 @@ export const playFromSong = mutation({
}
const index = songIds.indexOf(songId)
const rest = index === -1 ? [] : songIds.slice(index + 1)
const rest = user.shuffleEnabled
? uniqueSongIds(songIds).filter((id) => id !== songId)
: index === -1
? []
: songIds.slice(index + 1)
const queueRest = user.shuffleEnabled ? shuffleArray(rest) : rest
await setQueueState(ctx, userId, {
@@ -588,7 +592,11 @@ export const playFromLibrarySong = mutation({
const songIds = await getSortedLibrarySongIds(ctx, sortKey, sortDirection)
const index = songIds.indexOf(songId)
const rest = index === -1 ? [] : songIds.slice(index + 1)
const rest = user.shuffleEnabled
? uniqueSongIds(songIds).filter((id) => id !== songId)
: index === -1
? []
: songIds.slice(index + 1)
const queueRest = user.shuffleEnabled ? shuffleArray(rest) : rest
await setQueueState(ctx, userId, {