Compare commits

..
48 changed files with 277 additions and 1191 deletions

No files matched your search

-19
View File
@@ -23,22 +23,3 @@ 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.
+3 -4
View File
@@ -1,7 +1,7 @@
import type { ConfigContext, ExpoConfig } from "expo/config"
export default ({ config }: ConfigContext): ExpoConfig => {
const variant: string =
const variant =
process.env.APP_VARIANT ?? process.env.EAS_BUILD_PROFILE ?? "production"
if (
variant !== "development" &&
@@ -19,10 +19,9 @@ export default ({ config }: ConfigContext): ExpoConfig => {
: variant === "preview"
? " (Preview)"
: ""
// Expo writes this filename into Xcode build settings without quoting it.
const composer = {
development: "oTunesDev",
preview: "oTunesPreview",
development: "oTunes Dev",
preview: "oTunes Preview",
production: "oTunes",
}[variant]
+11 -33
View File
@@ -1,14 +1,12 @@
import Animated from "react-native-reanimated"
import { NavigationBar } from "expo-navigation-bar"
import {
AndroidTabThemeProvider,
useAndroidTabPalette,
useAndroidTabBackgroundStyle,
useAndroidNativeTabColors,
useAndroidTabSelectedColor,
} from "@/contexts/android-tab-theme"
import { DarkTheme, DefaultTheme, ThemeProvider } from "expo-router"
import { NativeTabs } from "expo-router/native-tabs"
import { DynamicColorIOS, Platform } from "react-native"
import { DynamicColorIOS, Platform, View } from "react-native"
import { useMemo } from "react"
import { AndroidMiniPlayer, TabBottomAccessory } from "@/components/mini-player"
@@ -43,12 +41,10 @@ function useRouterTheme() {
}
function useNativeTabColors() {
// These props initialize native tabs; the worklet owns subsequent colors.
const selectedColor = colors.dark.primary
const selectedColor = useAndroidTabSelectedColor()
const themeIsDark = useIsDark()
const androidPalette = colors.dark
const artworkPalette = useAndroidTabPalette()
const isDark = Platform.OS === "android" ? artworkPalette.isDark : themeIsDark
const androidPalette = useAndroidTabPalette()
const isDark = Platform.OS === "android" ? androidPalette.isDark : themeIsDark
const inactive = appleMusic.tabInactive
const iconColor =
@@ -58,14 +54,14 @@ function useNativeTabColors() {
selected: appleMusic.pink,
}
: {
default: androidPalette.mutedForeground,
default: androidPalette.secondaryForeground,
selected: selectedColor,
}
const labelColor =
Platform.OS === "ios"
? DynamicColorIOS({ dark: inactive, light: "#636366" })
: androidPalette.mutedForeground
: androidPalette.secondaryForeground
return {
isDark,
@@ -82,19 +78,15 @@ function useNativeTabColors() {
blurEffect: isDark
? "systemChromeMaterialDark"
: "systemChromeMaterialLight",
// Reveal the shared UI-thread background beneath the native tab bar.
backgroundColor: Platform.OS === "ios" ? undefined : "transparent",
backgroundColor:
Platform.OS === "ios" ? undefined : androidPalette.background,
}
}
function TabsContent() {
const homeColors = useAndroidNativeTabColors()
const libraryColors = useAndroidNativeTabColors()
const searchColors = useAndroidNativeTabColors()
const keyboardVisible = useAndroidKeyboardVisible()
const routerTheme = useRouterTheme()
const tabColors = useNativeTabColors()
const backgroundStyle = useAndroidTabBackgroundStyle()
const { currentSong, queueSongIds } = usePlaybackQueue()
const showBottomAccessory = Boolean(currentSong && queueSongIds.length > 0)
@@ -109,12 +101,7 @@ function TabsContent() {
return (
<ThemeProvider value={routerTheme}>
<Animated.View
style={[
{ flex: 1 },
Platform.OS === "android" ? backgroundStyle : undefined,
]}
>
<View style={{ flex: 1 }}>
{Platform.OS === "android" ? (
<NavigationBar style={tabColors.isDark ? "light" : "dark"} />
) : null}
@@ -140,9 +127,6 @@ function TabsContent() {
<NativeTabs.Trigger
name="home"
unstable_nativeProps={
Platform.OS === "android" ? homeColors : undefined
}
disableTransparentOnScrollEdge
contentStyle={androidContentStyle}
>
@@ -152,9 +136,6 @@ function TabsContent() {
<NativeTabs.Trigger
name="library"
unstable_nativeProps={
Platform.OS === "android" ? libraryColors : undefined
}
disableTransparentOnScrollEdge
contentStyle={androidContentStyle}
>
@@ -167,9 +148,6 @@ function TabsContent() {
<NativeTabs.Trigger
name="search"
unstable_nativeProps={
Platform.OS === "android" ? searchColors : undefined
}
disableTransparentOnScrollEdge
contentStyle={androidContentStyle}
>
@@ -178,7 +156,7 @@ function TabsContent() {
</NativeTabs.Trigger>
</NativeTabs>
{!keyboardVisible ? <AndroidMiniPlayer /> : null}
</Animated.View>
</View>
</ThemeProvider>
)
}
@@ -1,4 +1,5 @@
import { Stack } from "expo-router"
import { Platform } from "react-native"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
@@ -14,6 +15,10 @@ export default function HomeLayout() {
<Stack
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,
@@ -1,18 +1,17 @@
import {
PaletteText,
PaletteIcon,
renderArtworkBackButton,
} from "@/components/palette-text"
import Animated from "react-native-reanimated"
import {
renderAndroidArtworkBackground,
useAndroidScreenPalette,
} from "@/contexts/android-tab-theme"
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 { Platform, Pressable, StyleSheet, View } from "react-native"
import {
FlatList,
Platform,
Pressable,
StyleSheet,
Text,
View,
} from "react-native"
import { Ionicons } from "@expo/vector-icons"
import {
CollectionDivider,
@@ -71,8 +70,7 @@ export default function AlbumScreen() {
coverUri,
album ? album.cover != null : album === null ? false : undefined
)
const { palette, onLayout, backgroundStyle } =
useAndroidScreenPalette(artworkPalette)
const { palette, onLayout } = useAndroidScreenPalette(artworkPalette)
const songIds = useMemo(
() => album?.tracks.map((track) => track.id as Id<"songs">) ?? [],
[album]
@@ -113,9 +111,7 @@ export default function AlbumScreen() {
songIds={songIds}
palette={palette}
favorited={isSongFavorite(item.track.id)}
onPlay={(songId, ids) =>
playFromSong(songId, ids, `album:${album.id}`)
}
onPlay={playFromSong}
onAction={handleAlbumTrackAction}
/>
) : null
@@ -137,24 +133,9 @@ export default function AlbumScreen() {
options={{
title: "",
headerLargeTitle: false,
...(Platform.OS === "android"
? {
headerStyle: { backgroundColor: "transparent" },
headerBackground: renderAndroidArtworkBackground,
headerBackVisible: false,
headerLeft: renderArtworkBackButton,
headerTintColor: palette.foreground,
}
: {}),
}}
/>
<CollectionDetailSkeleton
onLayout={onLayout}
style={backgroundStyle}
backgroundColor={
Platform.OS === "android" ? palette.background : undefined
}
/>
<CollectionDetailSkeleton />
</>
)
}
@@ -169,9 +150,9 @@ export default function AlbumScreen() {
}}
/>
<View style={[styles.empty, { backgroundColor: colors.background }]}>
<PaletteText style={{ color: colors.mutedForeground }}>
<Text style={{ color: colors.mutedForeground }}>
Album not found.
</PaletteText>
</Text>
</View>
</>
)
@@ -192,10 +173,7 @@ export default function AlbumScreen() {
headerTintColor: palette.foreground,
...(Platform.OS === "android"
? {
headerStyle: { backgroundColor: "transparent" },
headerBackground: renderAndroidArtworkBackground,
headerBackVisible: false,
headerLeft: renderArtworkBackButton,
headerStyle: { backgroundColor: palette.background },
statusBarStyle: palette.isDark
? ("light" as const)
: ("dark" as const),
@@ -206,7 +184,7 @@ export default function AlbumScreen() {
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">,
@@ -217,8 +195,7 @@ export default function AlbumScreen() {
}
>
<Pressable hitSlop={8}>
<PaletteIcon
tone="foreground"
<Ionicons
name="ellipsis-horizontal"
size={22}
color={palette.isDark ? "#fff" : "#000"}
@@ -228,15 +205,12 @@ export default function AlbumScreen() {
),
}}
/>
<Animated.FlatList
<FlatList
onLayout={onLayout}
{...longListProps}
data={listItems}
keyExtractor={albumListItemKey}
style={[
{ flex: 1, backgroundColor: palette.background },
backgroundStyle,
]}
style={{ flex: 1, backgroundColor: palette.background }}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
indicatorStyle={palette.isDark ? "white" : "black"}
@@ -248,22 +222,16 @@ export default function AlbumScreen() {
hasCover={album.cover != null}
style={styles.cover}
/>
<PaletteText
tone="foreground"
style={[styles.title, { color: palette.foreground }]}
>
<Text style={[styles.title, { color: palette.foreground }]}>
{album.title}
</PaletteText>
</Text>
<Pressable
onPress={() => push(`/artist/${album.artist.id}`)}
style={styles.artistPressable}
>
<PaletteText
tone="accentText"
style={[styles.artist, { color: palette.accentText }]}
>
<Text style={[styles.artist, { color: palette.accentText }]}>
{album.artist.name}
</PaletteText>
</Text>
</Pressable>
<View
style={{
@@ -275,25 +243,18 @@ export default function AlbumScreen() {
}}
>
{metadata ? (
<PaletteText
tone="secondaryForeground"
style={{ color: palette.secondaryForeground }}
>
<Text style={{ color: palette.secondaryForeground }}>
{metadata}
</PaletteText>
</Text>
) : null}
{hasLossless ? (
<>
{metadata ? (
<PaletteText
tone="secondaryForeground"
style={{ color: palette.secondaryForeground }}
>
<Text style={{ color: palette.secondaryForeground }}>
·
</PaletteText>
</Text>
) : null}
<AudioFormatBadge
artwork
format="lossless"
color={palette.secondaryForeground}
backgroundColor={palette.background}
@@ -303,15 +264,11 @@ export default function AlbumScreen() {
{hasAtmos ? (
<>
{metadata || hasLossless ? (
<PaletteText
tone="secondaryForeground"
style={{ color: palette.secondaryForeground }}
>
<Text style={{ color: palette.secondaryForeground }}>
·
</PaletteText>
</Text>
) : null}
<AudioFormatBadge
artwork
format="atmos"
color={palette.secondaryForeground}
backgroundColor={palette.background}
@@ -328,8 +285,7 @@ export default function AlbumScreen() {
{ backgroundColor: palette.surface },
]}
>
<PaletteIcon
tone={favorited ? "accent" : "foreground"}
<Ionicons
name={favorited ? "star" : "star-outline"}
size={24}
color={favorited ? palette.accent : palette.foreground}
@@ -355,8 +311,7 @@ export default function AlbumScreen() {
{ backgroundColor: palette.surface },
]}
>
<PaletteIcon
tone="foreground"
<Ionicons
name="shuffle"
size={24}
color={palette.foreground}
@@ -449,7 +404,6 @@ 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)}
>
@@ -458,12 +412,11 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
style={styles.trackRow}
onPress={() => void onPlay(track.id as Id<"songs">, songIds)}
>
<PaletteText
tone="secondaryForeground"
<Text
style={[styles.trackNumber, { color: palette.secondaryForeground }]}
>
{number}
</PaletteText>
</Text>
<View
style={[
styles.trackContent,
@@ -471,29 +424,24 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
]}
>
<View style={styles.trackMeta}>
<PaletteText
tone="foreground"
<Text
style={[styles.trackTitle, { color: palette.foreground }]}
numberOfLines={1}
>
{track.title}
</PaletteText>
</Text>
{track.artists ? (
<PaletteText
tone="secondaryForeground"
<Text
style={{ color: palette.secondaryForeground }}
numberOfLines={1}
>
{track.artists.join(", ")}
</PaletteText>
</Text>
) : null}
</View>
<PaletteText
tone="secondaryForeground"
style={{ color: palette.secondaryForeground }}
>
<Text style={{ color: palette.secondaryForeground }}>
{formatDuration(track.durationSeconds)}
</PaletteText>
</Text>
</View>
</Pressable>
</MusicEntityView>
@@ -75,11 +75,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)
}
@@ -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,17 +1,4 @@
import {
PaletteText,
PaletteIcon,
renderArtworkBackButton,
} from "@/components/palette-text"
import Animated from "react-native-reanimated"
import {
PlaylistSearchBar,
usePlaylistSearch,
} from "@/components/playlist-search-bar"
import {
renderAndroidArtworkBackground,
useAndroidScreenPalette,
} from "@/contexts/android-tab-theme"
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"
@@ -23,13 +10,16 @@ import {
} from "expo-router"
import { StatusBar } from "expo-status-bar"
import {
FlatList,
Platform,
Pressable,
StyleSheet,
Text,
View,
type ListRenderItemInfo,
} from "react-native"
import ReanimatedSwipeable from "react-native-gesture-handler/ReanimatedSwipeable"
import { Ionicons } from "@expo/vector-icons"
import { CollectionDivider } from "@/components/collection-list"
import { CoverImage } from "@/components/cover-image"
@@ -91,8 +81,7 @@ export default function PlaylistScreen() {
coverUri,
playlist ? playlist.cover != null : playlist === null ? false : undefined
)
const { palette, onLayout, backgroundStyle } =
useAndroidScreenPalette(artworkPalette)
const { palette, onLayout } = useAndroidScreenPalette(artworkPalette)
useEffect(() => {
if (songs) rememberSongs(songs)
@@ -105,24 +94,9 @@ export default function PlaylistScreen() {
options={{
title: "",
headerLargeTitle: false,
...(Platform.OS === "android"
? {
headerStyle: { backgroundColor: "transparent" },
headerBackground: renderAndroidArtworkBackground,
headerBackVisible: false,
headerLeft: renderArtworkBackButton,
headerTintColor: palette.foreground,
}
: {}),
}}
/>
<CollectionDetailSkeleton
onLayout={onLayout}
style={backgroundStyle}
backgroundColor={
Platform.OS === "android" ? palette.background : undefined
}
/>
<CollectionDetailSkeleton />
</>
)
}
@@ -137,9 +111,9 @@ export default function PlaylistScreen() {
}}
/>
<View style={[styles.empty, { backgroundColor: colors.background }]}>
<PaletteText style={{ color: colors.mutedForeground }}>
<Text style={{ color: colors.mutedForeground }}>
Playlist not found.
</PaletteText>
</Text>
</View>
</>
)
@@ -147,7 +121,6 @@ export default function PlaylistScreen() {
return (
<PlaylistContent
backgroundStyle={backgroundStyle}
onLayout={onLayout}
playlist={playlist}
songs={playlist.songs}
@@ -158,7 +131,6 @@ export default function PlaylistScreen() {
}
function PlaylistContent({
backgroundStyle,
onLayout,
playlist,
songs,
@@ -166,7 +138,6 @@ function PlaylistContent({
palette,
}: {
onLayout?: () => void
backgroundStyle: ReturnType<typeof useAndroidScreenPalette>["backgroundStyle"]
playlist: BrowsePlaylistDetail
songs: BrowseSong[]
coverUri: string
@@ -187,14 +158,11 @@ 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, `playlist:${playlistId}`),
[playFromSong, songIds, playlistId]
(song: BrowseSong) => void playFromSong(song.id, songIds),
[playFromSong, songIds]
)
const handleSongMenuAction = useCallback(
@@ -272,10 +240,7 @@ function PlaylistContent({
headerTintColor: palette.foreground,
...(Platform.OS === "android"
? {
headerStyle: { backgroundColor: "transparent" },
headerBackground: renderAndroidArtworkBackground,
headerBackVisible: false,
headerLeft: renderArtworkBackButton,
headerStyle: { backgroundColor: palette.background },
statusBarStyle: palette.isDark
? ("light" as const)
: ("dark" as const),
@@ -288,14 +253,12 @@ function PlaylistContent({
share={{
type: "playlist",
playlistId: playlistId ?? "favorites",
title: playlist?.title ?? "oTunes",
}}
includeActions={canEdit ? OWNER_MENU_ACTIONS : undefined}
onAction={handlePlaylistMenuAction}
>
<Pressable hitSlop={8}>
<PaletteIcon
tone="foreground"
<Ionicons
name="ellipsis-horizontal"
size={22}
color={palette.isDark ? "#fff" : "#000"}
@@ -312,7 +275,6 @@ function PlaylistContent({
palette.background,
palette.isDark,
playlistId,
playlist?.title,
router,
songIds,
])
@@ -347,35 +309,17 @@ function PlaylistContent({
<StatusBar style={palette.isDark ? "light" : "dark"} />
) : null}
<Stack.Screen options={screenOptions} />
<PlaylistSearchBar
onQueryChange={onQueryChange}
onSearchSubmit={onSearchSubmit}
/>
<Animated.FlatList
<FlatList
onLayout={onLayout}
{...longListProps}
data={filteredSongs}
data={songs}
keyExtractor={songKey}
renderItem={renderItem}
style={[
{ flex: 1, backgroundColor: palette.background },
backgroundStyle,
]}
style={{ flex: 1, backgroundColor: palette.background }}
indicatorStyle={palette.isDark ? "white" : "black"}
contentContainerStyle={styles.listContent}
contentInsetAdjustmentBehavior="automatic"
onScrollBeginDrag={swipeGroup.closeOpenRow}
ListEmptyComponent={
<PaletteText
tone="secondaryForeground"
style={[
styles.emptyResults,
{ color: palette.secondaryForeground },
]}
>
{songs.length ? "No songs found." : "No songs in this playlist."}
</PaletteText>
}
ListHeaderComponent={
<PlaylistHero
entityId={playlistId ?? "otunes:favorites"}
@@ -468,19 +412,15 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
}}
style={[styles.removeAction, { backgroundColor: colors.destructive }]}
>
<PaletteIcon
name="trash"
size={22}
color={colors.primaryForeground}
/>
<PaletteText
<Ionicons name="trash" size={22} color={colors.primaryForeground} />
<Text
style={[
styles.removeActionText,
{ color: colors.primaryForeground },
]}
>
Remove
</PaletteText>
</Text>
</Pressable>
)}
>
@@ -518,18 +458,10 @@ const PlaylistHero = memo(function PlaylistHero({
<MusicEntityView kind="playlist" id={entityId}>
<View style={styles.hero}>
<CoverImage uri={coverUri} hasCover={hasCover} style={styles.cover} />
<PaletteText
tone="foreground"
style={[styles.title, { color: palette.foreground }]}
>
<Text style={[styles.title, { color: palette.foreground }]}>
{title}
</PaletteText>
<PaletteText
tone="secondaryForeground"
style={{ color: palette.secondaryForeground }}
>
{ownerName}
</PaletteText>
</Text>
<Text style={{ color: palette.secondaryForeground }}>{ownerName}</Text>
<View style={styles.actions}>
{showSubscribe ? (
<Pressable
@@ -547,8 +479,7 @@ const PlaylistHero = memo(function PlaylistHero({
},
]}
>
<PaletteIcon
tone={isSubscribed ? "foreground" : "accentForeground"}
<Ionicons
name={isSubscribed ? "checkmark" : "add"}
size={24}
color={
@@ -574,12 +505,7 @@ const PlaylistHero = memo(function PlaylistHero({
onPress={onShuffle}
style={[styles.iconAction, { backgroundColor: palette.surface }]}
>
<PaletteIcon
tone="foreground"
name="shuffle"
size={24}
color={palette.foreground}
/>
<Ionicons name="shuffle" size={24} color={palette.foreground} />
</Pressable>
</View>
</View>
@@ -589,7 +515,6 @@ 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,7 +1,3 @@
import {
PlaylistSearchBar,
usePlaylistSearch,
} from "@/components/playlist-search-bar"
import { memo, useCallback, useEffect, useMemo } from "react"
import {
FlatList,
@@ -41,8 +37,6 @@ 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)
@@ -105,25 +99,14 @@ 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>
}
ListHeaderComponent={
<FavoritesHero
title={favorites.title}
@@ -190,7 +173,6 @@ 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 },
@@ -1,4 +1,5 @@
import { Stack } from "expo-router"
import { Platform } from "react-native"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
@@ -14,6 +15,10 @@ export default function LibraryLayout() {
<Stack
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,
@@ -1,4 +1,5 @@
import { Stack } from "expo-router"
import { Platform } from "react-native"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
@@ -14,6 +15,10 @@ export default function SearchLayout() {
<Stack
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,
+1 -20
View File
@@ -1,10 +1,3 @@
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,
@@ -12,7 +5,7 @@ import {
} from "convex/react"
import { 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"
@@ -31,18 +24,6 @@ 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 (
-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 "/"
}
}
+2 -10
View File
@@ -1,6 +1,5 @@
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 { useServerConfig } from "@/contexts/server-config"
@@ -12,16 +11,9 @@ export default function Index() {
return <Redirect href="/server" />
}
const destination = auth?.isAuthenticated
? incomingMediaLink(config.serverUrl)
: null
return (
<Redirect
href={
(destination as Href) ??
(auth?.isAuthenticated ? "/(app)/(tabs)/library" : "/signin")
}
href={auth?.isAuthenticated ? "/(app)/(tabs)/library" : "/signin"}
/>
)
}
+2 -10
View File
@@ -1,5 +1,4 @@
import { useLocalSearchParams } from "expo-router"
import { useEffect, useState } from "react"
import { useState } from "react"
import { StyleSheet, Text, View } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
@@ -12,14 +11,7 @@ import { spacing, useThemeColors } from "@/lib/theme"
export default function ServerScreen() {
const colors = useThemeColors()
const { setServerHostname } = useServerConfig()
const { hostname: linkedHostname } = useLocalSearchParams<{
hostname?: string
}>()
const [hostname, setHostname] = useState(linkedHostname ?? "")
useEffect(() => {
if (linkedHostname) setHostname(linkedHostname)
}, [linkedHostname])
const [hostname, setHostname] = useState("")
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

+2 -10
View File
@@ -1,5 +1,4 @@
import { PaletteText } from "@/components/palette-text"
import { StyleSheet, View } from "react-native"
import { StyleSheet, Text, View } from "react-native"
import Svg, { G, Path } from "react-native-svg"
import type { PlaybackFormat } from "@otunes/convex/playback-stream"
@@ -75,12 +74,10 @@ function LosslessMark({
/** The Dolby Atmos or Lossless label shown under the progress bar. */
export function AudioFormatBadge({
artwork = false,
format,
color,
backgroundColor,
}: {
artwork?: boolean
format: PlaybackFormat
color: string
backgroundColor: string
@@ -93,12 +90,7 @@ export function AudioFormatBadge({
) : (
<LosslessMark color={color} backgroundColor={backgroundColor} />
)}
<PaletteText
tone={artwork ? "secondaryForeground" : undefined}
style={[styles.label, { color }]}
>
{label}
</PaletteText>
<Text style={[styles.label, { color }]}>{label}</Text>
</View>
)
}
+3 -7
View File
@@ -1,6 +1,5 @@
import { PaletteText } from "@/components/palette-text"
import { memo } from "react"
import { StyleSheet, View } from "react-native"
import { StyleSheet, Text, View } from "react-native"
import { useThemeColors } from "@/lib/theme"
@@ -26,12 +25,9 @@ export const DiscHeader = memo(function DiscHeader({
}) {
const colors = useThemeColors()
return (
<PaletteText
tone={color ? "foreground" : undefined}
style={[styles.discHeader, { color: color ?? colors.foreground }]}
>
<Text style={[styles.discHeader, { color: color ?? colors.foreground }]}>
{label}
</PaletteText>
</Text>
)
})
-6
View File
@@ -2,7 +2,6 @@ import { Ionicons } from "@expo/vector-icons"
import { Image, type ImageContentFit, type ImageStyle } from "expo-image"
import { memo, useMemo } from "react"
import {
Platform,
PixelRatio,
StyleProp,
StyleSheet,
@@ -10,8 +9,6 @@ import {
type ViewStyle,
} from "react-native"
import { prefetchCoverPalette } from "@/hooks/use-cover-palette"
import { useThemeColors } from "@/lib/theme"
import {
coverImageSizes,
@@ -109,9 +106,6 @@ export const CoverImage = memo(function CoverImage({
contentFit={contentFit}
transition={150}
blurRadius={blurRadius}
onLoad={
Platform.OS === "android" ? () => prefetchCoverPalette(uri) : undefined
}
cachePolicy="memory-disk"
recyclingKey={sourceUri}
enforceEarlyResizing
+3 -7
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, title: album.title }}
share={{ type: "album", albumId: album.id }}
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, title: artist.name }}
share={{ type: "artist", artistId: artist.id }}
onAction={(action) => void handleArtistAction(artist, action)}
>
<MusicEntityView kind="artist" id={artist.id}>
@@ -176,11 +176,7 @@ 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}>
@@ -59,8 +59,7 @@ export function MenuView({
outlineVariant: "#545458",
error: "#FF453A",
}}
// Rows fill their parent width; compact action buttons keep intrinsic sizing.
matchContents={shouldOpenOnLongPress ? { vertical: true } : true}
matchContents
>
<DropdownMenu
expanded={expanded}
@@ -71,9 +70,7 @@ export function MenuView({
properties={{ clippingEnabled: false }}
>
<DropdownMenu.Trigger>
<RNHostView
matchContents={shouldOpenOnLongPress ? { vertical: true } : true}
>
<RNHostView matchContents>
{shouldOpenOnLongPress ? (
<GestureDetector gesture={longPress}>
<View collapsable={false}>{children}</View>
+14 -32
View File
@@ -1,13 +1,11 @@
import { PaletteText, PaletteIcon } from "@/components/palette-text"
import Animated from "react-native-reanimated"
import {
useAndroidTabPalette,
useAndroidTabBackgroundStyle,
useAndroidTabHasArtworkPalette,
} from "@/contexts/android-tab-theme"
import { Ionicons } from "@expo/vector-icons"
import { NativeTabs } from "expo-router/native-tabs"
import { useRouter } from "expo-router"
import { Platform, Pressable, StyleSheet, View } from "react-native"
import { Platform, Pressable, StyleSheet, Text, View } from "react-native"
import { useSafeAreaInsets } from "react-native-safe-area-context"
@@ -67,8 +65,7 @@ function MiniPlayerContent({
<View
style={isAccessory ? styles.accessoryInlineMeta : styles.inlineMeta}
>
<PaletteText
tone="foreground"
<Text
style={[
isAccessory ? styles.accessoryTitle : styles.title,
{ color: colors.foreground },
@@ -76,7 +73,7 @@ function MiniPlayerContent({
numberOfLines={1}
>
{currentSong.title}
</PaletteText>
</Text>
</View>
<Pressable
style={styles.controlButton}
@@ -86,8 +83,7 @@ function MiniPlayerContent({
}}
hitSlop={6}
>
<PaletteIcon
tone="foreground"
<Ionicons
name={isPlaying ? "pause" : "play"}
size={20}
color={colors.foreground}
@@ -105,8 +101,7 @@ function MiniPlayerContent({
style={artworkStyle}
/>
<View style={isAccessory ? styles.accessoryMeta : styles.meta}>
<PaletteText
tone="foreground"
<Text
style={[
isAccessory ? styles.accessoryTitle : styles.title,
{ color: colors.foreground },
@@ -114,9 +109,8 @@ function MiniPlayerContent({
numberOfLines={1}
>
{currentSong.title}
</PaletteText>
<PaletteText
tone="secondaryForeground"
</Text>
<Text
style={[
isAccessory ? styles.accessoryArtist : styles.artist,
{ color: colors.mutedForeground },
@@ -124,7 +118,7 @@ function MiniPlayerContent({
numberOfLines={1}
>
{currentSong.artist.name}
</PaletteText>
</Text>
</View>
<View style={styles.controls}>
{Platform.OS === "android" && !isAccessory ? (
@@ -138,12 +132,7 @@ function MiniPlayerContent({
}}
hitSlop={6}
>
<PaletteIcon
tone="foreground"
name="play-back"
size={24}
color={colors.foreground}
/>
<Ionicons name="play-back" size={24} color={colors.foreground} />
</Pressable>
) : null}
<Pressable
@@ -154,8 +143,7 @@ function MiniPlayerContent({
}}
hitSlop={6}
>
<PaletteIcon
tone="foreground"
<Ionicons
name={isPlaying ? "pause" : "play"}
size={24}
color={colors.foreground}
@@ -169,12 +157,7 @@ function MiniPlayerContent({
}}
hitSlop={6}
>
<PaletteIcon
tone="foreground"
name="play-forward"
size={24}
color={colors.foreground}
/>
<Ionicons name="play-forward" size={24} color={colors.foreground} />
</Pressable>
</View>
</Pressable>
@@ -184,10 +167,9 @@ function MiniPlayerContent({
function MiniPlayerChrome({ children }: { children: React.ReactNode }) {
const palette = useAndroidTabPalette()
const hasArtworkPalette = useAndroidTabHasArtworkPalette()
const backgroundStyle = useAndroidTabBackgroundStyle()
return (
<Animated.View style={[styles.androidBar, backgroundStyle]}>
<View style={[styles.androidBar, { backgroundColor: palette.background }]}>
{children}
{hasArtworkPalette ? (
<View
@@ -205,7 +187,7 @@ function MiniPlayerChrome({ children }: { children: React.ReactNode }) {
{ backgroundColor: palette.secondaryForeground },
]}
/>
</Animated.View>
</View>
)
}
-49
View File
@@ -1,49 +0,0 @@
import { Ionicons } from "@expo/vector-icons"
import type { ComponentProps } from "react"
import { Pressable, type TextProps } from "react-native"
import { useRouter } from "expo-router"
import Animated from "react-native-reanimated"
import {
useAnimatedPaletteColor,
type PaletteColor,
} from "@/contexts/android-tab-theme"
const AnimatedIcon = Animated.createAnimatedComponent(Ionicons)
/** Keep artwork text colors on the same UI-thread animation as the background. */
export function PaletteText({
tone,
style,
...props
}: TextProps & { tone?: PaletteColor }) {
const colorStyle = useAnimatedPaletteColor(tone)
return <Animated.Text {...props} style={[style, colorStyle]} />
}
export function PaletteIcon({
tone,
style,
...props
}: ComponentProps<typeof Ionicons> & { tone?: PaletteColor }) {
const colorStyle = useAnimatedPaletteColor(tone)
return <AnimatedIcon {...props} style={[style, colorStyle]} />
}
function ArtworkBackButton() {
const router = useRouter()
return (
<Pressable
accessibilityRole="button"
accessibilityLabel="Navigate up"
hitSlop={8}
onPress={() => router.back()}
>
<PaletteIcon tone="foreground" name="arrow-back" size={24} />
</Pressable>
)
}
export function renderArtworkBackButton() {
return <ArtworkBackButton />
}
+7 -14
View File
@@ -1,4 +1,3 @@
import { PaletteText } from "@/components/palette-text"
import { MusicEntityView } from "@/components/music-entity-view"
import { collectionInset } from "@/components/collection-list"
import { CoverImage } from "@/components/cover-image"
@@ -9,7 +8,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, View } from "react-native"
import { Platform, Pressable, StyleSheet, Text, View } from "react-native"
import {
MediaContextMenu,
@@ -47,27 +46,22 @@ export const SongRow = memo(function SongRow({
const content = (
<>
<View style={styles.rowMeta}>
<PaletteText
tone={palette ? "foreground" : undefined}
<Text
style={[styles.rowTitle, { color: foreground }]}
numberOfLines={1}
>
{song.title}
</PaletteText>
<PaletteText
tone={palette ? "secondaryForeground" : undefined}
</Text>
<Text
style={[styles.rowSubtitle, { color: secondaryForeground }]}
numberOfLines={1}
>
{song.artist.name} · {song.album.title}
</PaletteText>
</Text>
</View>
<PaletteText
tone={palette ? "secondaryForeground" : undefined}
style={[styles.duration, { color: secondaryForeground }]}
>
<Text style={[styles.duration, { color: secondaryForeground }]}>
{formatDuration(song.durationSeconds)}
</PaletteText>
</Text>
{trailing}
</>
)
@@ -153,7 +147,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),
}}
@@ -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,
}
: {})}
/>
)
}
+36 -85
View File
@@ -1,5 +1,4 @@
import Reanimated from "react-native-reanimated"
import { useEffect, useRef, type ReactNode, type ComponentProps } from "react"
import { useEffect, useRef } from "react"
import {
Animated,
ScrollView,
@@ -19,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
@@ -99,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>
)
}
@@ -142,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>
)
}
@@ -198,25 +161,15 @@ export function HomeSkeleton() {
/** Album and playlist pages: cover, title, play buttons, then tracks. */
export function CollectionDetailSkeleton({
style,
round = false,
backgroundColor,
onLayout,
}: {
style?: ComponentProps<typeof Reanimated.ScrollView>["style"]
round?: boolean
backgroundColor?: string
onLayout?: () => void
}) {
const colors = useThemeColors()
const coverSize = round ? 180 : 210
return (
<Reanimated.ScrollView
onLayout={onLayout}
style={[
{ flex: 1, backgroundColor: backgroundColor ?? colors.background },
style,
]}
<ScrollView
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
scrollEnabled={false}
@@ -239,30 +192,28 @@ export function CollectionDetailSkeleton({
</View>
</View>
{round ? (
<MediaGridSkeleton items={4} contentInset={false} embedded />
<MediaGridSkeleton items={4} contentInset={false} />
) : (
<SongListSkeleton rows={8} embedded />
<SongListSkeleton rows={8} />
)}
</Reanimated.ScrollView>
</ScrollView>
)
}
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>
)
}
@@ -282,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 },
+2 -15
View File
@@ -1,4 +1,3 @@
import { PaletteText, PaletteIcon } from "@/components/palette-text"
import {
ActivityIndicator,
Platform,
@@ -74,20 +73,8 @@ export function Button({
<ActivityIndicator color={textColor} />
) : (
<View style={styles.buttonContent}>
{icon ? (
<PaletteIcon
tone={tint ? "accentForeground" : undefined}
name={icon}
size={18}
color={textColor}
/>
) : null}
<PaletteText
tone={tint ? "accentForeground" : undefined}
style={[styles.buttonText, { color: textColor }]}
>
{title}
</PaletteText>
{icon ? <Ionicons name={icon} size={18} color={textColor} /> : null}
<Text style={[styles.buttonText, { color: textColor }]}>{title}</Text>
</View>
)}
</Pressable>
+40 -135
View File
@@ -1,7 +1,8 @@
import {
useIsFocused,
useRoute,
useNavigation,
usePreventRemove,
useRoute,
type NativeStackNavigationProp,
} from "expo-router"
import {
@@ -13,29 +14,14 @@ import {
useState,
type PropsWithChildren,
} from "react"
import { Platform, StyleSheet, type HostInstance } from "react-native"
import Reanimated, {
useSharedValue,
useAnimatedStyle,
useAnimatedReaction,
useAnimatedRef,
setNativeProps,
processColor,
withTiming,
type SharedValue,
} from "react-native-reanimated"
import { Platform } from "react-native"
import { themeCoverPalette, type CoverPalette } from "@/lib/cover-palette"
import { useIsDark, useThemeColors } from "@/lib/theme"
export type PaletteColor = Exclude<keyof CoverPalette, "isDark">
type PaletteColors = Pick<CoverPalette, PaletteColor> & {
selectedColor: string
}
type TabTheme = {
palette: CoverPalette
colors: SharedValue<PaletteColors>
selectedColor: string
hasArtworkPalette: boolean
setPalette: (palette: CoverPalette | null, owner: string) => void
}
@@ -53,30 +39,7 @@ export function AndroidTabThemeProvider({ children }: PropsWithChildren) {
palette: CoverPalette
owner: string
} | null>(null)
const palette = screen?.palette ?? defaultPalette
const hasArtwork =
palette.background !== defaultPalette.background ||
palette.foreground !== defaultPalette.foreground ||
palette.secondaryForeground !== defaultPalette.secondaryForeground ||
palette.accent !== defaultPalette.accent
const { isDark: _defaultIsDark, ...defaultColors } = defaultPalette
const animatedColors = useSharedValue<PaletteColors>({
...defaultColors,
selectedColor: defaultPalette.accentText,
})
useLayoutEffect(() => {
if (Platform.OS !== "android") return
const { isDark: _isDark, ...colors } = palette
animatedColors.value = withTiming(
{
...colors,
selectedColor: hasArtwork
? palette.foreground
: defaultPalette.accentText,
},
{ duration: PALETTE_FADE_MS }
)
}, [animatedColors, palette, defaultPalette, hasArtwork])
const palette = screen?.palette ?? null
const setPalette = useCallback(
(palette: CoverPalette | null, owner: string) => {
setScreen((current) =>
@@ -85,15 +48,22 @@ export function AndroidTabThemeProvider({ children }: PropsWithChildren) {
},
[]
)
const artworkPalette = hasArtwork ? palette : null
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,
colors: animatedColors,
selectedColor: artworkPalette?.foreground ?? defaultPalette.accentText,
hasArtworkPalette: artworkPalette !== null,
setPalette,
}),
[defaultPalette, artworkPalette, setPalette, animatedColors]
[defaultPalette, artworkPalette, setPalette]
)
return (
<AndroidTabTheme.Provider value={value}>
@@ -102,50 +72,6 @@ export function AndroidTabThemeProvider({ children }: PropsWithChildren) {
)
}
/**
* NativeTabs forwards raw screen props to its Fabric screen. Bind that host
* directly so appearance updates stay on the UI thread with the page colors.
*/
export function useAndroidNativeTabColors() {
const colors = useContext(AndroidTabTheme)?.colors
const ref = useAnimatedRef<HostInstance>()
const mounted = useSharedValue(false)
const attach = useCallback(
(host: HostInstance | null) => {
if (host) ref(host)
mounted.value = host !== null
},
[ref, mounted]
)
useAnimatedReaction(
() => ({ colors: colors?.value, mounted: mounted.value }),
({ colors: palette, mounted: ready }) => {
if (Platform.OS !== "android" || !ready || !palette) return
const normal = processColor(palette.secondaryForeground)
const selected = processColor(palette.selectedColor)
setNativeProps(ref, {
standardAppearance: {
tabBarBackgroundColor: processColor("transparent"),
tabBarItemRippleColor: selected,
tabBarItemActiveIndicatorEnabled: false,
tabBarItemTitleSmallLabelFontSize: 10,
tabBarItemTitleLargeLabelFontSize: 10,
normal: {
tabBarItemTitleFontColor: normal,
tabBarItemIconColor: normal,
},
selected: {
tabBarItemTitleFontColor: selected,
tabBarItemIconColor: selected,
},
},
})
}
)
return { ref: attach, style: { backgroundColor: "transparent" } }
}
export function useAndroidTabPalette() {
const theme = useContext(AndroidTabTheme)
const defaultPalette = useDefaultPalette()
@@ -156,60 +82,39 @@ export function useAndroidTabHasArtworkPalette() {
return useContext(AndroidTabTheme)?.hasArtworkPalette ?? false
}
export function useAndroidTabBackgroundStyle() {
export function useAndroidTabSelectedColor() {
const theme = useContext(AndroidTabTheme)
const fallback = useDefaultPalette().background
const colors = theme?.colors
return useAnimatedStyle(() =>
Platform.OS === "android"
? { backgroundColor: colors?.value.background ?? fallback }
: {}
)
const defaultPalette = useDefaultPalette()
return theme?.selectedColor ?? defaultPalette.accentText
}
/** Color tokens share the background's UI-thread timing. */
export function useAnimatedPaletteColor(tone: PaletteColor | undefined) {
const colors = useContext(AndroidTabTheme)?.colors
return useAnimatedStyle(() =>
Platform.OS === "android" && tone && colors
? { color: colors.value[tone] }
: {}
)
}
/** Native headers draw this same UI-thread background as the page and bars. */
function AndroidArtworkBackground() {
const style = useAndroidTabBackgroundStyle()
return <Reanimated.View style={[StyleSheet.absoluteFill, style]} />
}
export function renderAndroidArtworkBackground() {
return <AndroidArtworkBackground />
}
const PALETTE_FADE_MS = 400
/** The focused artwork screen selects the shared background for page and bars. */
/** 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 [closing, setClosing] = useState(false)
const onLayout = useCallback(() => setLaidOut(true), [])
useLayoutEffect(() => {
if (Platform.OS !== "android") return
const start = navigation.addListener("transitionStart", ({ data }) => {
setClosing(data.closing)
})
return start
}, [navigation])
const defaultPalette = useDefaultPalette()
const theme = useContext(AndroidTabTheme)
const setPalette = theme?.setPalette
const target = isFocused && laidOut && !closing ? palette : defaultPalette
const backgroundStyle = useAndroidTabBackgroundStyle()
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 (
@@ -217,16 +122,16 @@ export function useAndroidScreenPalette(palette: CoverPalette) {
!setPalette ||
!isFocused ||
!laidOut ||
closing
!appeared ||
leaving
)
return
setPalette(palette, owner)
return () => setPalette(null, owner)
}, [closing, laidOut, isFocused, owner, palette, setPalette])
}, [appeared, isFocused, laidOut, leaving, owner, palette, setPalette])
return {
palette: Platform.OS === "android" ? target : palette,
backgroundStyle,
palette: Platform.OS === "android" && theme ? theme.palette : palette,
onLayout: Platform.OS === "android" ? onLayout : undefined,
}
}
+13 -53
View File
@@ -87,11 +87,7 @@ 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">[],
origin?: string
) => Promise<void>
playFromSong: (songId: Id<"songs">, songIds: Id<"songs">[]) => Promise<void>
playFromLibrarySong: (
songId: Id<"songs">,
sort: {
@@ -268,13 +264,11 @@ 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)
@@ -354,21 +348,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
@@ -586,12 +565,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
@@ -829,7 +807,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
handlePlaybackLoadFailure,
historySyncKey,
queueSyncKey,
queueStartVersion,
repeatEnabled,
scheduleTrackChangeHandling,
userPlaybackKey,
@@ -850,20 +827,18 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
) => playbackQueue.PlaybackQueueState,
recorded: {
playlistId?: Id<"playlists">
origin?: string
entity?: { kind: MusicEntityKind; id: string }
} = {}
) => {
playRequestRef.current += 1
queueOriginRef.current =
recorded.origin ??
(recorded.playlistId ? `playlist:${recorded.playlistId}` : undefined)
resetQueuePlayback()
store.update(playbackQueue.clearQueue)
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
@@ -894,7 +869,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
: { songId: firstSongId }
)
},
[store, resetQueuePlayback, setIsPlaying, recordPlay]
[store, seekTo, setIsPlaying, recordPlay]
)
const playCollection = useCallback(
@@ -903,7 +878,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
shuffled: boolean,
recorded: {
playlistId?: Id<"playlists">
origin?: string
entity?: { kind: MusicEntityKind; id: string }
} = {}
) => {
@@ -968,19 +942,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(
@@ -1050,7 +1017,6 @@ 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]
)
@@ -1059,7 +1025,6 @@ 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]
)
@@ -1122,14 +1087,12 @@ 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, resetQueuePlayback, setIsPlaying]
[store, setIsPlaying]
)
const startFromSong = useCallback(
@@ -1140,20 +1103,17 @@ 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, resetQueuePlayback, setIsPlaying]
[store, setIsPlaying]
)
const clearQueue = useCallback(async () => {
playRequestRef.current += 1
queueOriginRef.current = undefined
store.update(playbackQueue.clearQueue)
setIsPlaying(false)
}, [store, setIsPlaying])
+2 -14
View File
@@ -95,13 +95,6 @@ function extractSwatches(key: string) {
return request
}
/** Warm visible artwork colors before a detail page is pushed. */
export function prefetchCoverPalette(uri: string) {
const key = withCoverImageSize(uri, 64)
if (cachedSwatches(key) !== undefined) return
void extractSwatches(key)
}
/**
* Colors for a screen tinted by `uri`'s cover art. Extraction runs once per
* cover and is cached on device. Pass `hasCover` as `undefined` while it isn't
@@ -145,10 +138,7 @@ export function useCoverPalette(
// case the cover changed.
const timer =
known === undefined
? setTimeout(
() => !cancelled && setWaitedKey(key),
COVER_PALETTE_WAIT_MS
)
? setTimeout(() => !cancelled && setWaitedKey(key), COVER_PALETTE_WAIT_MS)
: null
void extractSwatches(key).then((next) => {
if (!cancelled) show(next ?? known ?? null)
@@ -161,9 +151,7 @@ export function useCoverPalette(
const palette = useMemo(() => {
const fromArt =
hasCover !== false && swatches
? deriveCoverPalette(swatches, isDark)
: null
hasCover !== false && swatches ? deriveCoverPalette(swatches, isDark) : null
return fromArt ?? themeCoverPalette(theme, isDark)
}, [hasCover, isDark, swatches, theme])
-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()
}
+1 -2
View File
@@ -1,9 +1,8 @@
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,
-1
View File
@@ -28,7 +28,6 @@ export function useStackScreenOptions(
headerBackButtonDisplayMode: "minimal",
...(Platform.OS === "android"
? {
animation: "slide_from_right",
headerLargeTitle: false,
headerTransparent: false,
headerStyle: { backgroundColor: theme.background },
+2 -27
View File
@@ -1,4 +1,3 @@
import { requireOptionalNativeModule } from "expo"
import * as Sharing from "expo-sharing"
import { Platform, Share } from "react-native"
@@ -6,10 +5,6 @@ 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
@@ -22,32 +17,12 @@ export async function shareMediaLink(
showError("Sharing is not available on this device")
return
}
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
)
await Sharing.shareAsync(url, { dialogTitle: "Share" })
return
}
await Share.share(
Platform.OS === "ios"
? { url, title: share.title }
: { message: url, title: share.title }
Platform.OS === "ios" ? { url } : { message: url }
)
} catch (error) {
if (error instanceof Error && /cancel/i.test(error.message)) {
-53
View File
@@ -1,53 +0,0 @@
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
@@ -1,55 +0,0 @@
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)
}
}
}
}
+2 -3
View File
@@ -389,7 +389,7 @@ export function AlbumView({
return (
<div className="flex h-svh flex-col">
<PageHeader openApp />
<PageHeader />
<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,8 +547,7 @@ export function AlbumView({
onPlay={() =>
void playFromSong(
track.id as Id<"songs">,
albumSongIds,
`album:${album.id}`
albumSongIds
)
}
/>
+1 -1
View File
@@ -65,7 +65,7 @@ export function ArtistView({
return (
<div className="flex h-svh flex-col">
<PageHeader openApp />
<PageHeader />
<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">
+2 -14
View File
@@ -1,4 +1,3 @@
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"
@@ -20,13 +19,7 @@ function LoadingRegion({
)
}
export function PageHeader({
title,
openApp = false,
}: {
title?: string
openApp?: boolean
}) {
export function PageHeader({ title }: { title?: string }) {
return (
<header
className={cn(
@@ -35,12 +28,7 @@ export function PageHeader({
)}
>
<MobileSidebarTrigger />
{title ? (
<h1 className="text-lg font-semibold">{title}</h1>
) : openApp ? (
<span className="font-semibold">oTunes</span>
) : null}
{openApp ? <OpenAppButton /> : null}
{title ? <h1 className="text-lg font-semibold">{title}</h1> : null}
</header>
)
}
-22
View File
@@ -1,22 +0,0 @@
"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>
)
}
+10 -35
View File
@@ -63,11 +63,7 @@ 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">[],
origin?: string
) => Promise<void>
playFromSong: (songId: Id<"songs">, songIds: Id<"songs">[]) => Promise<void>
playFromLibrarySong: (
songId: Id<"songs">,
sort: {
@@ -388,7 +384,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
const [queueOpen, setQueueOpen] = useState(false)
const [isPlaying, setIsPlaying] = useState(false)
const [playbackStartVersion, setPlaybackStartVersion] = useState(0)
const [currentTime, setCurrentTime] = useState(0)
const [measuredDuration, setMeasuredDuration] = useState<{
songId: string
@@ -891,7 +886,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
return () => {
audio.removeEventListener("canplay", onCanPlay)
}
}, [isPlaying, currentSongId, playbackStartVersion, attemptPlayback])
}, [isPlaying, currentSongId, attemptPlayback])
useEffect(() => {
const audio = audioRef.current
@@ -1055,7 +1050,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
}
}, [currentSongId, currentSong])
const queueOriginRef = useRef<string | undefined>(undefined)
const playRequestRef = useRef(0)
const startPlayback = useCallback(
@@ -1063,14 +1057,10 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
recipe: (
state: playbackQueue.PlaybackQueueState
) => playbackQueue.PlaybackQueueState,
recorded: { playlistId?: Id<"playlists">; origin?: string } = {}
recorded: { playlistId?: Id<"playlists"> } = {}
) => {
playRequestRef.current += 1
queueOriginRef.current =
recorded.origin ??
(recorded.playlistId ? `playlist:${recorded.playlistId}` : undefined)
const previousSongId = store.getState().queue[0]
store.update(playbackQueue.clearQueue)
store.update(recipe)
const firstSongId = store.getState().queue[0]
if (!firstSongId) {
@@ -1080,11 +1070,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
if (firstSongId === previousSongId) {
seekTo(0)
}
// Repeated Play/Shuffle presses must request playback even when the
// first song and playing state have not changed.
isPlayingRef.current = true
setIsPlaying(true)
setPlaybackStartVersion((version) => version + 1)
recordPlay(
recorded.playlistId
? { playlistId: recorded.playlistId }
@@ -1098,7 +1084,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
async (
songIds: Id<"songs">[] | Promise<Id<"songs">[]>,
shuffled: boolean,
recorded: { playlistId?: Id<"playlists">; origin?: string } = {}
recorded: { playlistId?: Id<"playlists"> } = {}
) => {
const request = ++playRequestRef.current
let resolvedSongIds: Id<"songs">[]
@@ -1163,19 +1149,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(
@@ -1243,17 +1222,13 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
const playAlbum = useCallback(
(albumId: Id<"albums">, songIds?: Id<"songs">[]) =>
playCollection(loadAlbumSongIds(albumId, songIds), false, {
origin: `album:${albumId}`,
}),
playCollection(loadAlbumSongIds(albumId, songIds), false),
[playCollection, loadAlbumSongIds]
)
const playAlbumShuffled = useCallback(
(albumId: Id<"albums">, songIds?: Id<"songs">[]) =>
playCollection(loadAlbumSongIds(albumId, songIds), true, {
origin: `album:${albumId}`,
}),
playCollection(loadAlbumSongIds(albumId, songIds), true),
[playCollection, loadAlbumSongIds]
)
+19 -19
View File
@@ -76,8 +76,8 @@ export function PlayerBar() {
queueOpen && !isMobile && "right-72"
)}
>
<div className="pointer-events-auto flex w-full max-w-[40rem] items-center gap-2 rounded-full border border-foreground/20 bg-(--player-background) px-3 py-2 text-card-foreground shadow-lg [--player-background:var(--card)] md:gap-3 md:py-1.5 dark:border-white/20 dark:text-white dark:[--player-background:#303033]">
<div className="flex shrink-0 items-center gap-0 md:gap-0.5 [&_button]:size-7 [&_svg]:size-4">
<div className="pointer-events-auto flex w-full max-w-6xl 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)] @min-[640px]:gap-5 @min-[640px]:px-5 @min-[640px]:py-3 dark:border-white/20 dark:text-white dark:[--player-background:#303033]">
<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">
<Button
variant="ghost"
size="icon"
@@ -91,7 +91,7 @@ export function PlayerBar() {
)}
onClick={() => void toggleShuffle()}
>
<Shuffle className="size-4" />
<Shuffle className="size-4 @min-[640px]:size-6" />
</Button>
<Button
variant="ghost"
@@ -100,7 +100,7 @@ export function PlayerBar() {
disabled={!hasQueue}
onClick={() => void skipPrevious()}
>
<SkipBack className="size-4 fill-current" />
<SkipBack className="size-4 fill-current @min-[640px]:size-6" />
</Button>
<Button
variant="ghost"
@@ -110,9 +110,9 @@ export function PlayerBar() {
onClick={() => setIsPlaying(!isPlaying)}
>
{isPlaying ? (
<Pause className="size-5! fill-current" />
<Pause className="size-5! fill-current @min-[640px]:size-8!" />
) : (
<Play className="size-5! fill-current" />
<Play className="size-5! fill-current @min-[640px]:size-8!" />
)}
</Button>
<Button
@@ -122,7 +122,7 @@ export function PlayerBar() {
disabled={!hasQueue}
onClick={() => void skipNext()}
>
<SkipForward className="size-4 fill-current" />
<SkipForward className="size-4 fill-current @min-[640px]:size-6" />
</Button>
<Button
variant="ghost"
@@ -138,33 +138,33 @@ export function PlayerBar() {
onClick={() => void cycleRepeat()}
>
{repeatEnabled === "once" ? (
<Repeat1 className="size-4" />
<Repeat1 className="size-4 @min-[640px]:size-6" />
) : (
<Repeat className="size-4" />
<Repeat className="size-4 @min-[640px]:size-6" />
)}
</Button>
</div>
<div className="relative flex h-11 min-w-0 flex-1 items-center gap-2 pb-2 md:h-9 md:pb-1">
<div className="relative flex h-11 min-w-0 flex-1 items-center gap-2 pb-2 @min-[640px]:h-16 @min-[640px]:gap-3">
{currentSong ? (
<>
<div className="relative size-9 shrink-0 overflow-hidden rounded md:size-8">
<div className="relative size-9 shrink-0 overflow-hidden rounded @min-[640px]:size-14">
<Image
src={albumCoverUrl(currentSong.album.id)}
alt={currentSong.album.title}
fill
sizes="36px"
sizes="56px"
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 md:text-[13px] md:leading-4"
className="block truncate text-sm font-semibold hover:underline @min-[640px]:text-xl"
>
{currentSong.title}
</Link>
<p className="truncate text-xs">
<p className="truncate text-xs @min-[640px]:text-lg">
<Link
href={`/artist/${currentSong.artist.id}`}
className="hover:underline"
@@ -200,7 +200,7 @@ export function PlayerBar() {
<div className="absolute inset-x-0 -bottom-1">
<Slider
className={cn(
"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",
"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",
!hasActiveSong && "[&_[data-slot=slider-thumb]]:hidden"
)}
min={0}
@@ -222,7 +222,7 @@ export function PlayerBar() {
</div>
</div>
<div className="flex shrink-0 items-center gap-0 md:gap-1 [&_button]:size-7 [&_svg]:size-4">
<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">
<Button
variant="ghost"
size="icon"
@@ -230,7 +230,7 @@ export function PlayerBar() {
aria-label="Lyrics"
disabled
>
<MessageSquareQuote className="size-4" />
<MessageSquareQuote className="size-4 @min-[640px]:size-6" />
</Button>
<Button
variant="ghost"
@@ -240,12 +240,12 @@ export function PlayerBar() {
className={cn(queueOpen && "text-primary")}
onClick={toggleQueueOpen}
>
<ListMusic className="size-4" />
<ListMusic className="size-4 @min-[640px]:size-6" />
</Button>
<Popover>
<PopoverTrigger asChild>
<Button variant="ghost" size="icon" aria-label="Volume">
<Volume2 className="size-4" />
<Volume2 className="size-4 @min-[640px]:size-6" />
</Button>
</PopoverTrigger>
<PopoverContent side="top" align="end" className="w-40">
+13 -61
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, SearchIcon, Share2, Shuffle, Star, Trash2 } from "lucide-react"
import { Play, Share2, Shuffle, Star, Trash2 } from "lucide-react"
import { toast } from "sonner"
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
@@ -305,19 +305,6 @@ 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]
@@ -340,8 +327,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
handleSelect,
handlePointerDown,
prepareContextMenu,
clearSelection,
} = useTrackSelection(filteredSongs)
} = useTrackSelection(songs)
const selectedStationArtistId = React.useMemo(
() => stationArtistId(songs, selectedIds),
@@ -349,12 +335,8 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
)
const selectionPositions = React.useMemo(
() =>
getSelectionRangePositions(
filteredSongs.map((song) => song.id),
selectedIds
),
[filteredSongs, selectedIds]
() => getSelectionRangePositions(songs.map((song) => song.id), selectedIds),
[songs, selectedIds]
)
const totalDurationSeconds = React.useMemo(
() => sumDurationSeconds(songs),
@@ -479,13 +461,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
}
function handleDrop(targetIndex: number) {
if (
normalizedQuery ||
isFavorites ||
!isOwner ||
dragIndex === null ||
dragIndex === targetIndex
) {
if (isFavorites || !isOwner || dragIndex === null || dragIndex === targetIndex) {
setDragIndex(null)
return
}
@@ -543,7 +519,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
return (
<div className="flex h-svh flex-col">
<PageHeader openApp />
<PageHeader />
<ScrollArea className="min-h-0 flex-1">
<div className="pb-28">
<div className="mx-auto w-full min-w-0 max-w-9/10">
@@ -657,31 +633,13 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
</div>
</div>
<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) => (
{songs.length > 0 ? (
songs.map((song, index) => (
<PlaylistSongRow
key={song.id}
song={song}
index={index}
isOwner={isOwner && !isFavorites && !normalizedQuery}
isOwner={isOwner && !isFavorites}
canRemove={isFavorites || isOwner}
showFavoriteInMenu={!isFavorites}
removeLabel={
@@ -721,14 +679,14 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
onMediaAction={handleMediaAction}
onRemove={() => handleRemoveSong(song.id)}
onDragStart={(event) => {
if (normalizedQuery || isFavorites || !isOwner) {
if (isFavorites || !isOwner) {
return
}
setDragIndex(index)
event.dataTransfer.effectAllowed = "move"
}}
onDragOver={(event) => {
if (normalizedQuery || isFavorites || !isOwner) {
if (isFavorites || !isOwner) {
return
}
event.preventDefault()
@@ -739,19 +697,13 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
}}
isNowPlaying={currentSong?.id === song.id}
onPlay={() =>
void playFromSong(
song.id as Id<"songs">,
playlistSongIds,
`playlist:${playlist.id}`
)
void playFromSong(song.id as Id<"songs">, playlistSongIds)
}
/>
))
) : (
<p className="px-6 py-8 text-sm text-muted-foreground">
{normalizedQuery
? "No songs found."
: "This playlist has no songs yet."}
This playlist has no songs yet.
</p>
)}
<MediaCollectionFooter
+1 -5
View File
@@ -64,11 +64,7 @@ export function startQueueFromSong(
songIds: Id<"songs">[]
): PlaybackQueueState {
const index = songIds.indexOf(songId)
const rest = state.shuffleEnabled
? uniqueSongIds(songIds).filter((id) => id !== songId)
: index === -1
? []
: songIds.slice(index + 1)
const rest = index === -1 ? [] : songIds.slice(index + 1)
return {
...state,
queue: [songId, ...(state.shuffleEnabled ? shuffleArray(rest) : rest)],
+2 -10
View File
@@ -433,11 +433,7 @@ export const playFromSong = mutation({
}
const index = songIds.indexOf(songId)
const rest = user.shuffleEnabled
? uniqueSongIds(songIds).filter((id) => id !== songId)
: index === -1
? []
: songIds.slice(index + 1)
const rest = index === -1 ? [] : songIds.slice(index + 1)
const queueRest = user.shuffleEnabled ? shuffleArray(rest) : rest
await setQueueState(ctx, userId, {
@@ -592,11 +588,7 @@ export const playFromLibrarySong = mutation({
const songIds = await getSortedLibrarySongIds(ctx, sortKey, sortDirection)
const index = songIds.indexOf(songId)
const rest = user.shuffleEnabled
? uniqueSongIds(songIds).filter((id) => id !== songId)
: index === -1
? []
: songIds.slice(index + 1)
const rest = index === -1 ? [] : songIds.slice(index + 1)
const queueRest = user.shuffleEnabled ? shuffleArray(rest) : rest
await setQueueState(ctx, userId, {