Compare commits

...
63 changed files with 1220 additions and 715 deletions

No files matched your search

+2 -2
View File
@@ -121,7 +121,7 @@ RUN curl -fsSL -o ffmpeg.tar.xz "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VER
# Decoders cover the library formats (FLAC, ALAC/AAC in m4a, MP3, Opus,
# Vorbis, WavPack, WMA, E-AC-3/TrueHD for Atmos). Encoders are only the two
# the app writes: AAC (HLS and ADTS) and FLAC.
# the app writes: AAC (HLS, ADTS and .m4a downloads) and FLAC.
RUN ./configure \
--prefix=/opt/ffmpeg \
--disable-shared \
@@ -138,7 +138,7 @@ RUN ./configure \
--enable-demuxer=aac,ac3,aiff,ape,asf,au,caf,dsf,flac,matroska,mov,mp3,ogg,wav,wv \
--enable-decoder=aac,aac_latm,ac3,alac,ape,dsd_lsbf,dsd_msbf,eac3,flac,mlp,mp3,opus,pcm_f32le,pcm_s16be,pcm_s16le,pcm_s24be,pcm_s24le,pcm_s32be,pcm_s32le,pcm_u8,truehd,vorbis,wavpack,wmav1,wmav2 \
--enable-encoder=aac,flac \
--enable-muxer=adts,flac,hls,mpegts \
--enable-muxer=adts,flac,hls,ipod,mpegts \
--enable-parser=aac,aac_latm,ac3,flac,mpegaudio,opus,vorbis \
--enable-bsf=aac_adtstoasc \
--enable-filter=aresample,aformat \
+7
View File
@@ -32,6 +32,13 @@ export default ({ config }: ConfigContext): ExpoConfig => {
...config,
plugins: [
...(config.plugins ?? []),
[
"react-native-continued-task",
{
// Matches TASK_PREFIX in hooks/use-background-downloads.ts.
identifierPrefixes: [`${bundleIdentifier}.downloads`],
},
],
...(process.env.MAC_CATALYST === "1"
? ["./plugins/with-mac-catalyst"]
: []),
@@ -1,11 +1,8 @@
import { Stack } from "expo-router"
import { TabStackContext } from "@/lib/app-navigation"
import { renderTabScreenContent } from "@/components/tab-screen-content"
import {
inlineTitleOptions,
tabStackScreenTitles,
useStackScreenOptions,
} from "@/lib/navigation"
import { useStackScreenOptions, tabStackScreenTitles } from "@/lib/navigation"
import { tabletSections, TabletSectionContext } from "@/lib/tablet-navigation"
export default function TabletSectionLayout({ segment }: { segment: string }) {
@@ -14,17 +11,18 @@ export default function TabletSectionLayout({ segment }: { segment: string }) {
return (
<TabletSectionContext value={section}>
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...options,
...inlineTitleOptions,
title:
route.name === "index"
? section?.title
: tabStackScreenTitles[route.name],
})}
/>
<TabStackContext value={section?.group}>
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...options,
title:
route.name === "index"
? section?.title
: tabStackScreenTitles[route.name],
})}
/>
</TabStackContext>
</TabletSectionContext>
)
}
+23 -25
View File
@@ -1,12 +1,9 @@
import { renderTabScreenContent } from "@/components/tab-screen-content"
import { Stack } from "expo-router"
import { TabStackContext } from "@/lib/app-navigation"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import {
inlineTitleOptions,
tabStackScreenTitles,
useStackScreenOptions,
} from "@/lib/navigation"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
export const unstable_settings = {
anchor: "index",
@@ -16,25 +13,26 @@ export default function HomeLayout() {
const baseOptions = useStackScreenOptions({ title: "Home" })
return (
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...baseOptions,
...inlineTitleOptions,
title: tabStackScreenTitles[route.name] ?? "Home",
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
})}
/>
<TabStackContext value="home">
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Home",
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
})}
/>
</TabStackContext>
)
}
@@ -53,7 +53,7 @@ export default function AlbumsScreen() {
return (
<>
{searchBar}
<MediaGridSkeleton title="Albums" />
<MediaGridSkeleton />
</>
)
}
@@ -63,7 +63,6 @@ export default function AlbumsScreen() {
{searchBar}
<MediaGridList
title="Albums"
content={albums}
paddingBottom={contentBottomInset}
onEndReached={() => {
@@ -2,13 +2,12 @@ import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router"
import { memo, useCallback } from "react"
import {
type FlatList,
FlatList,
Pressable,
StyleSheet,
Text,
type ListRenderItemInfo,
} from "react-native"
import Animated from "react-native-reanimated"
import {
MediaContextMenu,
@@ -16,7 +15,6 @@ import {
} from "@/components/media-context-menu"
import { CoverImage } from "@/components/cover-image"
import { ArtistListSkeleton } from "@/components/skeletons"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { contentBottomInset } from "@/components/player"
import { useServerConfig } from "@/contexts/server-config"
import {
@@ -35,7 +33,6 @@ import { spacing, useThemeColors } from "@/lib/theme"
const PAGE_SIZE = 50
export default function ArtistsScreen() {
const { ref, scrollY } = useScreenTitleScroll<FlatList<BrowseArtist>>()
const { push } = useAppNavigation()
const colors = useThemeColors()
const { config } = useServerConfig()
@@ -97,7 +94,7 @@ export default function ArtistsScreen() {
return (
<>
{searchBar}
<ArtistListSkeleton title="Artists" />
<ArtistListSkeleton />
</>
)
}
@@ -106,11 +103,8 @@ export default function ArtistsScreen() {
<>
{searchBar}
<Animated.FlatList
<FlatList
{...longListProps}
ref={ref}
scrollEventThrottle={16}
ListHeaderComponent={<ScreenTitle title="Artists" scrollY={scrollY} />}
data={artists}
keyExtractor={artistKey}
renderItem={renderItem}
@@ -1,4 +1,3 @@
import { useContext } from "react"
import { Pressable } from "react-native"
import { MediaGridList } from "@/components/media-cards"
@@ -11,20 +10,19 @@ import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router"
import { SymbolView } from "expo-symbols"
import { useAddToPlaylist } from "@/contexts/add-to-playlist"
import { TabletSectionContext } from "@/lib/tablet-navigation"
export default function PlaylistsTabScreen() {
const colors = useThemeColors()
const playlists = useCachedQuery(api.playlists.listAllPlaylists)
const { openCreatePlaylist } = useAddToPlaylist()
const title = useContext(TabletSectionContext)?.title ?? "Playlists"
if (playlists === undefined) {
return (
<>
<Stack.Screen
options={{
title,
title: "Playlists",
headerLargeTitle: true,
headerRight: () => (
<Pressable
onPress={openCreatePlaylist}
@@ -40,7 +38,7 @@ export default function PlaylistsTabScreen() {
),
}}
/>
<MediaGridSkeleton title={title} />
<MediaGridSkeleton />
</>
)
}
@@ -49,7 +47,8 @@ export default function PlaylistsTabScreen() {
<>
<Stack.Screen
options={{
title,
title: "Playlists",
headerLargeTitle: true,
headerRight: () => (
<Pressable
onPress={openCreatePlaylist}
@@ -62,7 +61,6 @@ export default function PlaylistsTabScreen() {
}}
/>
<MediaGridList
title={title}
content={playlists}
paddingBottom={tabContentBottomInset}
/>
@@ -1,16 +1,10 @@
import { Stack } from "expo-router"
import { useCallback, useState } from "react"
import {
type FlatList,
StyleSheet,
type ListRenderItemInfo,
} from "react-native"
import Animated from "react-native-reanimated"
import { FlatList, StyleSheet, type ListRenderItemInfo } from "react-native"
import type { MediaAction } from "@/components/media-context-menu"
import { contentBottomInset, SongListRow } from "@/components/player"
import { SongListSkeleton } from "@/components/skeletons"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback"
import {
@@ -26,7 +20,6 @@ import { longListProps } from "@/lib/list"
const PAGE_SIZE = 50
export default function SongsScreen() {
const { ref, scrollY } = useScreenTitleScroll<FlatList<BrowseSong>>()
const { playFromLibrarySong } = usePlaybackActions()
const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions()
@@ -94,7 +87,7 @@ export default function SongsScreen() {
return (
<>
{searchBar}
<SongListSkeleton title="Songs" />
<SongListSkeleton />
</>
)
}
@@ -103,11 +96,8 @@ export default function SongsScreen() {
<>
{searchBar}
<Animated.FlatList
<FlatList
{...longListProps}
ref={ref}
scrollEventThrottle={16}
ListHeaderComponent={<ScreenTitle title="Songs" scrollY={scrollY} />}
data={songs}
keyExtractor={songKey}
renderItem={renderItem}
@@ -1,6 +1,6 @@
import { useMemo } from "react"
import {
type FlatList,
FlatList,
Pressable,
StyleSheet,
Text,
@@ -8,10 +8,8 @@ import {
type ListRenderItemInfo,
} from "react-native"
import { Stack } from "expo-router"
import Animated from "react-native-reanimated"
import { CoverImage } from "@/components/cover-image"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { tabContentBottomInset } from "@/components/player"
import {
FAVORITES_DOWNLOAD_ID,
@@ -55,7 +53,6 @@ export default function DownloadsScreen() {
const { push } = useAppNavigation()
const { columns, cardWidth, onLayout, horizontalPadding, gap } =
useMediaGridLayout()
const { ref, scrollY } = useScreenTitleScroll<FlatList<Card>>()
const cards = useMemo<Card[]>(() => {
if (!queue) return []
@@ -138,10 +135,8 @@ export default function DownloadsScreen() {
return (
<>
<Stack.Screen options={{ title: "Downloads" }} />
<Animated.FlatList
ref={ref}
scrollEventThrottle={16}
<Stack.Screen options={{ title: "Downloads", headerLargeTitle: true }} />
<FlatList
key={columns}
onLayout={onLayout}
data={cards}
@@ -154,20 +149,13 @@ export default function DownloadsScreen() {
numColumns={columns}
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{
paddingTop: spacing.lg,
paddingHorizontal: horizontalPadding,
paddingBottom: tabContentBottomInset,
gap,
}}
columnWrapperStyle={columns > 1 ? { gap } : undefined}
contentInsetAdjustmentBehavior="automatic"
ListHeaderComponent={
<ScreenTitle
title="Downloads"
scrollY={scrollY}
// The list padding already insets the title.
style={{ paddingHorizontal: 0 }}
/>
}
ListEmptyComponent={
<View style={styles.empty}>
<Text style={{ color: colors.mutedForeground }}>
@@ -1,17 +1,15 @@
import { useCallback, useMemo } from "react"
import {
type FlatList,
FlatList,
Pressable,
StyleSheet,
Text,
View,
type ListRenderItemInfo,
} from "react-native"
import Animated from "react-native-reanimated"
import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { useSwipeRowGroup } from "@/components/ios-swipe-to-remove-row"
import type { MediaAction } from "@/components/media-context-menu"
import { contentBottomInset, SongListRow } from "@/components/player"
@@ -54,7 +52,6 @@ export default function OtherDownloadsScreen() {
const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions()
const swipeGroup = useSwipeRowGroup()
const { ref, scrollY } = useScreenTitleScroll<FlatList<BrowseSong>>()
const handlePlaySong = useCallback(
(song: BrowseSong) => void playFromSong(song.id, playableIds, PLAY_ORIGIN),
@@ -93,11 +90,11 @@ export default function OtherDownloadsScreen() {
return (
<>
<Stack.Screen options={{ title: OTHER_DOWNLOADS_TITLE }} />
<Animated.FlatList
<Stack.Screen
options={{ title: OTHER_DOWNLOADS_TITLE, headerLargeTitle: false }}
/>
<FlatList
{...longListProps}
ref={ref}
scrollEventThrottle={16}
data={songs}
keyExtractor={(song) => song.id}
renderItem={renderItem}
@@ -106,32 +103,25 @@ export default function OtherDownloadsScreen() {
contentInsetAdjustmentBehavior="automatic"
onScrollBeginDrag={swipeGroup.closeOpenRow}
ListHeaderComponent={
<>
<ScreenTitle title={OTHER_DOWNLOADS_TITLE} scrollY={scrollY} />
{songs.length > 0 ? (
<View style={styles.actions}>
<Button
title="Play"
icon="play"
onPress={() => void playInOrder(playableIds, PLAY_ORIGIN)}
style={styles.play}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() => void playShuffled(playableIds, PLAY_ORIGIN)}
style={[styles.shuffle, { backgroundColor: colors.card }]}
>
<Ionicons
name="shuffle"
size={24}
color={colors.foreground}
/>
</Pressable>
</View>
) : null}
</>
songs.length > 0 ? (
<View style={styles.actions}>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() => void playShuffled(playableIds, PLAY_ORIGIN)}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
<Button
title="Play"
icon="play"
onPress={() => void playInOrder(playableIds, PLAY_ORIGIN)}
style={styles.playButton}
/>
</View>
) : undefined
}
ListEmptyComponent={
<Text style={[styles.empty, { color: colors.mutedForeground }]}>
@@ -147,14 +137,15 @@ const styles = StyleSheet.create({
actions: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: spacing.sm,
padding: spacing.lg,
},
play: { flex: 1 },
shuffle: {
width: 48,
height: 48,
borderRadius: 24,
playButton: { borderRadius: 999, minWidth: 160 },
iconAction: {
width: 44,
height: 44,
borderRadius: 22,
alignItems: "center",
justifyContent: "center",
},
+4 -16
View File
@@ -1,10 +1,8 @@
import { memo } from "react"
import { type ScrollViewInstance, StyleSheet } from "react-native"
import Animated from "react-native-reanimated"
import { ScrollView, StyleSheet } from "react-native"
import { ContentCarousel } from "@/components/media-cards"
import { HomeSkeleton } from "@/components/skeletons"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { tabContentBottomInset } from "@/components/player"
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api"
@@ -40,7 +38,6 @@ const HomeCarousels = memo(function HomeCarousels({
export default function HomeScreen() {
const colors = useThemeColors()
const { ref, scrollY } = useScreenTitleScroll<ScrollViewInstance>()
const recentlyAdded = useCachedPaginatedQuery(
api.library.browseRecentlyAddedPaginated,
{},
@@ -56,16 +53,14 @@ export default function HomeScreen() {
(result) => result.status === "LoadingFirstPage" && !result.isCached
)
if (isLoading) {
return <HomeSkeleton title="Home" />
return <HomeSkeleton />
}
const added = recentlyAdded.results.slice(0, CAROUSEL_ITEM_LIMIT)
const played = recentlyPlayed.results.slice(0, CAROUSEL_ITEM_LIMIT)
return (
<Animated.ScrollView
ref={ref}
scrollEventThrottle={16}
<ScrollView
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={[
styles.content,
@@ -73,9 +68,8 @@ export default function HomeScreen() {
]}
contentInsetAdjustmentBehavior="automatic"
>
<ScreenTitle title="Home" scrollY={scrollY} style={styles.title} />
<HomeCarousels recentlyAdded={added} recentlyPlayed={played} />
</Animated.ScrollView>
</ScrollView>
)
}
@@ -84,10 +78,4 @@ const styles = StyleSheet.create({
padding: spacing.lg,
gap: spacing.xl,
},
// The content padding already insets the title.
title: {
paddingHorizontal: 0,
marginTop: -spacing.lg,
marginBottom: -spacing.md,
},
})
@@ -14,12 +14,11 @@ export default function RecentlyAddedScreen() {
)
if (status === "LoadingFirstPage" && !isCached) {
return <MediaGridSkeleton title="Recently Added" />
return <MediaGridSkeleton />
}
return (
<MediaGridList
title="Recently Added"
content={results}
paddingBottom={contentBottomInset}
onEndReached={() => {
@@ -14,12 +14,11 @@ export default function RecentlyPlayedScreen() {
)
if (status === "LoadingFirstPage" && !isCached) {
return <MediaGridSkeleton title="Recently Played" />
return <MediaGridSkeleton />
}
return (
<MediaGridList
title="Recently Played"
content={results}
paddingBottom={contentBottomInset}
onEndReached={() => {
+10 -6
View File
@@ -1,4 +1,8 @@
import { atmosEnabled, dolbyAtmosSupported } from "@/lib/playback-capabilities"
import {
atmosEnabled,
deviceDownloadQualities,
dolbyAtmosSupported,
} from "@/lib/playback-capabilities"
import { Ionicons } from "@expo/vector-icons"
import { useAction, useMutation, useQuery } from "convex/react"
import { Image } from "expo-image"
@@ -25,7 +29,6 @@ import {
writeRememberedDownloadQuality,
} from "@/lib/downloads"
import {
DOWNLOAD_QUALITIES,
DOWNLOAD_QUALITY_DETAILS,
DOWNLOAD_QUALITY_LABELS,
formatBytes,
@@ -450,9 +453,10 @@ function QualitySection({ user }: { user: CurrentUser }) {
/** Shades of the text color, faintest for the smallest files. */
const QUALITY_OPACITY: Record<DownloadQuality, number> = {
medium: 0.25,
high: 0.45,
lossless: 0.7,
low: 0.2,
medium: 0.35,
high: 0.5,
lossless: 0.75,
atmos: 1,
}
@@ -507,7 +511,7 @@ function RememberedQualityCard() {
detail: string
}[] = [
{ value: null, label: "Ask every time", detail: "Choose when downloading" },
...DOWNLOAD_QUALITIES.map((quality) => ({
...deviceDownloadQualities.map((quality) => ({
value: quality,
label: DOWNLOAD_QUALITY_LABELS[quality],
detail: DOWNLOAD_QUALITY_DETAILS[quality],
@@ -2,12 +2,9 @@ import { useTabletLayout } from "@/hooks/use-tablet-layout"
import { renderTabScreenContent } from "@/components/tab-screen-content"
import { Stack } from "expo-router"
import { TabStackContext } from "@/lib/app-navigation"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import {
inlineTitleOptions,
tabStackScreenTitles,
useStackScreenOptions,
} from "@/lib/navigation"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
export const unstable_settings = {
anchor: "index",
@@ -18,27 +15,28 @@ export default function LibraryLayout() {
const baseOptions = useStackScreenOptions({ title: "Library" })
return (
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...baseOptions,
...inlineTitleOptions,
title:
tabStackScreenTitles[route.name] ??
(tabletLayout ? "Recently Added" : "Library"),
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
})}
/>
<TabStackContext value="library">
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...baseOptions,
title:
tabStackScreenTitles[route.name] ??
(tabletLayout ? "Recently Added" : "Library"),
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
})}
/>
</TabStackContext>
)
}
@@ -72,7 +72,6 @@ export default function LibraryScreen() {
const { push } = useAppNavigation()
const isTablet = tabletLayout
const colors = useThemeColors()
const title = isTablet ? "Recently Added" : "Library"
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
api.library.browseRecentlyAddedPaginated,
{},
@@ -125,18 +124,11 @@ export default function LibraryScreen() {
)
if (status === "LoadingFirstPage" && !isCached) {
return (
<MediaGridSkeleton
title={title}
contentInset={false}
header={listHeader}
/>
)
return <MediaGridSkeleton contentInset={false} header={listHeader} />
}
return (
<MediaGridList
title={title}
content={results}
paddingBottom={tabContentBottomInset}
contentInset={false}
+23 -25
View File
@@ -1,12 +1,9 @@
import { renderTabScreenContent } from "@/components/tab-screen-content"
import { Stack } from "expo-router"
import { TabStackContext } from "@/lib/app-navigation"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import {
inlineTitleOptions,
tabStackScreenTitles,
useStackScreenOptions,
} from "@/lib/navigation"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
export const unstable_settings = {
anchor: "index",
@@ -16,25 +13,26 @@ export default function SearchLayout() {
const baseOptions = useStackScreenOptions({ title: "Search" })
return (
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...baseOptions,
...inlineTitleOptions,
title: tabStackScreenTitles[route.name] ?? "Search",
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
})}
/>
<TabStackContext value="search">
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Search",
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
})}
/>
</TabStackContext>
)
}
@@ -35,7 +35,7 @@ export default function SearchScreen() {
: {})}
/>
<SearchResults searchQuery={searchQuery} title="Search" />
<SearchResults searchQuery={searchQuery} />
</>
)
}
+94 -113
View File
@@ -1,4 +1,13 @@
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"
import {
memo,
type ComponentType,
type ReactElement,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react"
import {
Pressable,
ScrollView,
@@ -6,13 +15,11 @@ import {
Text,
View,
type ScrollViewInstance,
type ViewProps,
} from "react-native"
import MaskedViewClass from "@react-native-masked-view/masked-view"
import Animated, {
cancelAnimation,
Easing,
useAnimatedStyle,
useSharedValue,
withTiming,
type SharedValue,
} from "react-native-reanimated"
@@ -21,7 +28,7 @@ import {
usePlaybackProgress,
usePlaybackQueue,
} from "@/contexts/playback"
import { useLyricsTime } from "@/hooks/use-lyrics"
import { useLyricsTime, usePlaybackClock } from "@/hooks/use-lyrics"
import type { NowPlayingColors } from "@/lib/now-playing-colors"
import {
activeLineIndex,
@@ -30,12 +37,21 @@ import {
type Lyrics,
} from "@otunes/convex/client/lyrics"
// The package's class typings predate React 19's; this is its documented API.
const MaskedView = MaskedViewClass as unknown as ComponentType<
ViewProps & { maskElement: ReactElement }
>
/** How long a manual scroll keeps the view from following the song. */
const MANUAL_SCROLL_HOLD_MS = 3000
/** Where the playing line sits, as a share of the view's height from the top. */
const ACTIVE_LINE_POSITION = 0.12
/** Blur radius by distance from the playing line; farther lines share the last. */
const LINE_BLUR = [0, 1, 2, 3]
/** Opacity of lines other than the one playing. */
const INACTIVE_LINE_OPACITY = 0.35
/** How long a line takes to brighten, dim, or change blur. */
const LINE_FADE_MS = 300
/**
* Lyrics in the player's own colors. Synced lines follow playback and seek
@@ -76,6 +92,7 @@ function LyricsLines({
const { isPlaying } = usePlaybackQueue()
const { seekTo, setIsPlaying } = usePlaybackActions()
const time = useLyricsTime(lyrics, currentTime, isPlaying)
const clock = usePlaybackClock(currentTime, isPlaying)
const active = activeLineIndex(lyrics, time)
const synced = lyrics.synced !== "none"
const scrollRef = useRef<ScrollViewInstance>(null)
@@ -169,8 +186,7 @@ function LyricsLines({
: Math.min(Math.abs(index - active), LINE_BLUR.length - 1)
}
active={index === active}
time={index === active ? time : null}
isPlaying={isPlaying}
clock={clock}
colors={colors}
textStyle={lineStyle}
onSelect={playFrom}
@@ -198,17 +214,16 @@ function LyricsLines({
}
/**
* One timed line, blurred by its `distance` from the playing line. Only the
* playing line gets the time, so the others skip re-rendering as the song
* plays.
* One timed line, laid out word by word whether or not it is playing, so it
* never re-wraps. It fades and blurs by its `distance` from the playing line,
* and only the playing line's words fill.
*/
const SyncedLine = memo(function SyncedLine({
index,
line,
distance,
active,
time,
isPlaying,
clock,
colors,
textStyle,
onSelect,
@@ -218,136 +233,100 @@ const SyncedLine = memo(function SyncedLine({
line: LyricLine
distance: number
active: boolean
time: number | null
isPlaying: boolean
clock: SharedValue<number>
colors: NowPlayingColors
textStyle: { fontSize: number; lineHeight: number }
onSelect: (seconds: number) => void
onLayoutY: (index: number, y: number) => void
}) {
const blur = LINE_BLUR[distance]
const wordStyle = [styles.lineText, textStyle, { color: colors.foreground }]
return (
<Pressable
onPress={() => onSelect(line.start ?? 0)}
onLayout={(event) => onLayoutY(index, event.nativeEvent.layout.y)}
accessibilityRole="button"
accessibilityHint="Plays from this line"
style={[styles.line, blur > 0 && { filter: [{ blur }] }]}
style={styles.line}
>
{active && line.words && time !== null ? (
<FilledWords
words={line.words}
time={time}
isPlaying={isPlaying}
colors={colors}
textStyle={textStyle}
/>
) : (
<Text
style={[
styles.lineText,
textStyle,
{
color:
active && !line.words
? colors.foreground
: colors.lyricsInactive,
},
]}
>
{line.text}
</Text>
)}
<Animated.View
style={{
opacity: active ? 1 : INACTIVE_LINE_OPACITY,
filter: [{ blur: LINE_BLUR[distance] }],
transitionProperty: ["opacity", "filter"],
transitionDuration: LINE_FADE_MS,
}}
>
{line.words ? (
<View
style={[styles.words, { columnGap: textStyle.fontSize * 0.25 }]}
>
{line.words.map((word, wordIndex) =>
active ? (
<FilledWord
key={wordIndex}
word={word}
clock={clock}
colors={colors}
textStyle={textStyle}
/>
) : (
<Text key={wordIndex} style={wordStyle}>
{word.text.trim()}
</Text>
)
)}
</View>
) : (
<Text style={wordStyle}>{line.text}</Text>
)}
</Animated.View>
</Pressable>
)
})
/**
* The playing line's words, each wiping from dim to bright as it is sung.
* Reanimated runs the wipe; playback updates only re-anchor it.
* A word of the playing line, filled from dim to bright with a soft edge as
* it is sung: a gradient 2.5 times its width slides under the word's
* shape, like the web panel's.
*/
function FilledWords({
words,
time,
isPlaying,
colors,
textStyle,
}: {
words: LyricWord[]
time: number
isPlaying: boolean
colors: NowPlayingColors
textStyle: { fontSize: number; lineHeight: number }
}) {
const sung = useSharedValue(time)
const end = words.at(-1)?.end ?? time
useEffect(() => {
cancelAnimation(sung)
sung.value = time
if (isPlaying && end > time) {
sung.value = withTiming(end, {
duration: (end - time) * 1000,
easing: Easing.linear,
})
}
}, [sung, time, isPlaying, end])
return (
<View style={[styles.words, { columnGap: textStyle.fontSize * 0.25 }]}>
{words.map((word, index) => (
<FilledWord
key={index}
word={word}
sung={sung}
colors={colors}
textStyle={textStyle}
/>
))}
</View>
)
}
function FilledWord({
word,
sung,
clock,
colors,
textStyle,
}: {
word: LyricWord
sung: SharedValue<number>
clock: SharedValue<number>
colors: NowPlayingColors
textStyle: { fontSize: number; lineHeight: number }
}) {
const [width, setWidth] = useState(0)
const text = word.text.trim()
const wipe = useAnimatedStyle(() => {
const slide = useAnimatedStyle(() => {
const progress =
(sung.value - word.start) / Math.max(word.end - word.start, 0.05)
return { width: width * Math.min(Math.max(progress, 0), 1) }
(clock.value - word.start) / Math.max(word.end - word.start, 0.05)
const sung = Math.min(Math.max(progress, 0), 1)
// -60% of the gradient's width shows its dim end; 0% its bright one.
return { transform: [{ translateX: `${-60 * (1 - sung)}%` }] }
})
return (
<View>
<Text
style={[styles.lineText, textStyle, { color: colors.lyricsUnsung }]}
onLayout={(event) => setWidth(event.nativeEvent.layout.width)}
>
{text}
</Text>
<Animated.View style={[styles.wipe, wipe]}>
<Text
numberOfLines={1}
style={[
styles.lineText,
textStyle,
{ color: colors.foreground, width },
]}
>
{text}
</Text>
</Animated.View>
</View>
<MaskedView
maskElement={
<Text style={[styles.lineText, textStyle, styles.mask]}>{text}</Text>
}
>
{/* Sizes the word; the mask draws it. */}
<Text style={[styles.lineText, textStyle, styles.hidden]}>{text}</Text>
<Animated.View
style={[
styles.fillGradient,
{
backgroundImage: `linear-gradient(90deg, ${colors.foreground} 40%, ${colors.lyricsUnsung} 60%)`,
},
slide,
]}
/>
</MaskedView>
)
}
@@ -358,12 +337,14 @@ const styles = StyleSheet.create({
line: { paddingVertical: 9 },
lineText: { fontWeight: "800" },
words: { flexDirection: "row", flexWrap: "wrap" },
wipe: {
mask: { color: "black" },
hidden: { opacity: 0 },
fillGradient: {
position: "absolute",
top: 0,
bottom: 0,
left: 0,
overflow: "hidden",
width: "250%",
},
plainLine: { fontWeight: "700", paddingVertical: 2 },
stanzaGap: { height: 18 },
+2 -25
View File
@@ -4,7 +4,6 @@ import { tabletLayoutTransition } from "@/lib/tablet-motion"
import { TabletMediaGrid } from "@/components/tablet-media-grid"
import { useMediaGridLayout } from "@/hooks/use-media-grid-layout"
import { MusicEntityView } from "@/components/music-entity-view"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { Link } from "expo-router"
import { Ionicons } from "@expo/vector-icons"
import { memo, useCallback, type ReactElement } from "react"
@@ -301,21 +300,17 @@ export function MediaGridList({
onEndReached,
ListHeaderComponent,
contentInset = true,
title,
}: {
content: MediaItem[]
paddingBottom: number
onEndReached?: () => void
ListHeaderComponent?: ReactElement
contentInset?: boolean
/** iOS `ScreenTitle` shown above the grid; it replaces the top inset. */
title?: string
}) {
const tabletLayout = useTabletLayout()
const { columns, cardWidth, onLayout, horizontalPadding, gap } =
useMediaGridLayout()
const colors = useThemeColors()
const { ref, scrollY } = useScreenTitleScroll<FlatList<MediaItem>>()
const renderItem = useCallback(
({ item }: ListRenderItemInfo<MediaItem>) => (
<View style={{ width: cardWidth }}>
@@ -333,30 +328,13 @@ export function MediaGridList({
onEndReached={onEndReached}
ListHeaderComponent={ListHeaderComponent}
contentInset={contentInset}
title={title}
renderCard={renderTabletCard}
/>
)
}
const header = title ? (
<View>
<ScreenTitle
title={title}
scrollY={scrollY}
// Inset grids already pad the whole list horizontally.
style={{ paddingHorizontal: contentInset ? 0 : horizontalPadding }}
/>
{ListHeaderComponent}
</View>
) : (
ListHeaderComponent
)
return (
<Animated.FlatList
ref={ref}
scrollEventThrottle={16}
<FlatList
key={columns}
onLayout={onLayout}
data={content}
@@ -373,7 +351,6 @@ export function MediaGridList({
paddingBottom,
gap,
...(contentInset ? { paddingHorizontal: horizontalPadding } : {}),
...(title ? { paddingTop: 0 } : {}),
},
]}
columnWrapperStyle={[
@@ -382,7 +359,7 @@ export function MediaGridList({
{ gap },
]}
contentInsetAdjustmentBehavior="automatic"
ListHeaderComponent={header}
ListHeaderComponent={ListHeaderComponent}
onEndReached={onEndReached}
onEndReachedThreshold={0.5}
/>
+1 -15
View File
@@ -1,7 +1,4 @@
import {
useAndroidTabPalette,
useAndroidTabHasArtworkPalette,
} from "@/contexts/android-tab-theme"
import { useAndroidTabPalette } from "@/contexts/android-tab-theme"
import { Ionicons } from "@expo/vector-icons"
import { NativeTabs } from "expo-router/native-tabs"
import { useRouter } from "expo-router"
@@ -166,20 +163,10 @@ function MiniPlayerContent({
function MiniPlayerChrome({ children }: { children: React.ReactNode }) {
const palette = useAndroidTabPalette()
const hasArtworkPalette = useAndroidTabHasArtworkPalette()
return (
<View style={[styles.androidBar, { backgroundColor: palette.background }]}>
{children}
{hasArtworkPalette ? (
<View
style={[
styles.separator,
styles.topBorder,
{ backgroundColor: palette.secondaryForeground },
]}
/>
) : null}
<View
style={[
styles.separator,
@@ -267,7 +254,6 @@ const styles = StyleSheet.create({
height: 1,
zIndex: 1,
},
topBorder: { top: 0 },
bottomBorder: { bottom: 0 },
content: {
flexDirection: "row",
-84
View File
@@ -1,84 +0,0 @@
import { useHeaderHeight } from "expo-router/react-navigation"
import type { Component } from "react"
import {
Platform,
StyleSheet,
type ScrollViewInstance,
type StyleProp,
type TextStyle,
} from "react-native"
import Animated, {
useAnimatedRef,
useAnimatedStyle,
useScrollOffset,
type SharedValue,
} from "react-native-reanimated"
import { spacing, useThemeColors } from "@/lib/theme"
/**
* Tracks the scroll view that renders a `ScreenTitle`. Attach `ref` to that
* Reanimated `Animated.ScrollView` / `Animated.FlatList` and pass `scrollY`
* to the title.
*/
export function useScreenTitleScroll<
TScrollView extends Component | ScrollViewInstance,
>() {
const ref = useAnimatedRef<TScrollView>()
const scrollY = useScrollOffset(ref)
return { ref, scrollY }
}
/**
* iOS screen title rendered as the first item of a screen's scroll content,
* in place of the native large title (Apple Music style): it scrolls away
* with the content, never collapses into the bar, and stays put on
* pull-down. Android keeps its native header title, so this renders nothing.
*/
export function ScreenTitle({
title,
scrollY,
style,
}: {
title: string
/** From `useScreenTitleScroll`; omit for screens that never scroll. */
scrollY?: SharedValue<number>
style?: StyleProp<TextStyle>
}) {
const colors = useThemeColors()
// At rest the scroll offset is minus the automatic header inset, so any
// offset below that is overscroll the title should cancel out.
const headerHeight = useHeaderHeight()
const pinStyle = useAnimatedStyle(() => ({
transform: [
{
translateY: scrollY ? Math.min(0, scrollY.value + headerHeight) : 0,
},
],
}))
if (Platform.OS !== "ios") return null
return (
<Animated.Text
accessibilityRole="header"
numberOfLines={2}
style={[styles.title, { color: colors.foreground }, style, pinStyle]}
>
{title}
</Animated.Text>
)
}
// Matches UIKit's large title metrics: 34pt bold in a 52pt tall area.
const styles = StyleSheet.create({
title: {
fontSize: 34,
lineHeight: 41,
fontWeight: "700",
letterSpacing: 0.37,
paddingHorizontal: spacing.lg,
paddingTop: 3,
paddingBottom: 8,
},
})
+13 -22
View File
@@ -1,15 +1,13 @@
import { memo, useCallback, useMemo } from "react"
import {
type FlatList,
FlatList,
StyleSheet,
Text,
View,
type ListRenderItemInfo,
} from "react-native"
import Animated from "react-native-reanimated"
import { ContentCarousel } from "@/components/media-cards"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import type { MediaAction } from "@/components/media-context-menu"
import { tabContentBottomInset, SongListRow } from "@/components/player"
import { SongListSkeleton } from "@/components/skeletons"
@@ -21,16 +19,8 @@ import { api } from "@otunes/convex/_generated/api"
import type { BrowseSong, SearchSong } from "@otunes/convex/types"
import { spacing, useThemeColors } from "@/lib/theme"
function SearchResultsBody({
searchQuery,
title,
}: {
searchQuery: string
/** iOS `ScreenTitle`, shown above the results and while idle. */
title: string
}) {
function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
const colors = useThemeColors()
const { ref, scrollY } = useScreenTitleScroll<FlatList<BrowseSong>>()
const { playFromSong } = usePlaybackActions()
const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions()
@@ -86,14 +76,16 @@ function SearchResultsBody({
)
if (isSearching) {
return <SongListSkeleton title={title} />
return <SongListSkeleton />
}
if (!hasQuery) {
return <></>
}
return (
<Animated.FlatList
ref={ref}
scrollEventThrottle={16}
data={hasQuery ? (results?.songs ?? []) : []}
<FlatList
data={results?.songs ?? []}
keyExtractor={(song) => song.id}
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{ paddingBottom: tabContentBottomInset }}
@@ -101,8 +93,7 @@ function SearchResultsBody({
keyboardShouldPersistTaps="handled"
ListHeaderComponent={
<>
<ScreenTitle title={title} scrollY={scrollY} />
{hasQuery && !hasResults ? (
{!hasResults ? (
<View style={styles.empty}>
<Text
style={[styles.emptyText, { color: colors.mutedForeground }]}
@@ -112,13 +103,13 @@ function SearchResultsBody({
</View>
) : null}
{hasQuery && results?.artists.length ? (
{results?.artists.length ? (
<View style={styles.section}>
<ContentCarousel title="Artists" content={results.artists} />
</View>
) : null}
{hasQuery && results?.albums.length ? (
{results?.albums.length ? (
<View style={styles.section}>
<ContentCarousel title="Albums" content={results.albums} />
</View>
@@ -127,7 +118,7 @@ function SearchResultsBody({
}
renderItem={renderItem}
ListFooterComponent={
hasQuery && playlistResults && playlistResults.length > 0 ? (
playlistResults && playlistResults.length > 0 ? (
<View style={styles.section}>
<ContentCarousel title="Playlists" content={playlistResults} />
</View>
+5 -49
View File
@@ -9,7 +9,6 @@ import {
collectionInset,
} from "@/components/collection-list"
import { tabletCardTextHeight } from "@/components/tablet-media-grid"
import { ScreenTitle } from "@/components/screen-title"
import { Link } from "expo-router"
import { useHeaderHeight } from "expo-router/react-navigation"
import Reanimated from "react-native-reanimated"
@@ -152,16 +151,9 @@ function SongRows({ rows, inset }: { rows: number; inset?: boolean }) {
))
}
export function SongListSkeleton({
rows = 10,
title,
}: {
rows?: number
title?: string
}) {
export function SongListSkeleton({ rows = 10 }: { rows?: number }) {
return (
<SkeletonScreen>
{title ? <ScreenTitle title={title} /> : null}
<SongRows rows={rows} />
</SkeletonScreen>
)
@@ -242,45 +234,23 @@ export function MediaGridSkeleton({
items = 6,
contentInset = true,
header,
title,
}: {
items?: number
contentInset?: boolean
/** The loaded list's `ListHeaderComponent`, so it keeps its position. */
header?: ReactNode
/** The loaded list's `ScreenTitle`, which replaces its top inset. */
title?: string
}) {
return (
<SkeletonScreen>
<MediaGridContent
items={items}
contentInset={contentInset && !title}
header={
title ? (
<>
<MediaGridTitle title={title} />
{header}
</>
) : (
header
)
}
contentInset={contentInset}
header={header}
/>
</SkeletonScreen>
)
}
function MediaGridTitle({ title }: { title: string }) {
const { horizontalPadding } = useMediaGridLayout()
return (
<ScreenTitle
title={title}
style={{ paddingHorizontal: horizontalPadding }}
/>
)
}
export function CarouselSkeleton() {
return (
<View style={styles.carousel}>
@@ -294,11 +264,10 @@ export function CarouselSkeleton() {
)
}
export function HomeSkeleton({ title }: { title: string }) {
export function HomeSkeleton() {
return (
<SkeletonScreen>
<View style={styles.home}>
<ScreenTitle title={title} style={styles.homeTitle} />
<CarouselSkeleton />
<CarouselSkeleton />
</View>
@@ -419,17 +388,10 @@ export function CollectionDetailSkeleton({
)
}
export function ArtistListSkeleton({
rows = 12,
title,
}: {
rows?: number
title?: string
}) {
export function ArtistListSkeleton({ rows = 12 }: { rows?: number }) {
const colors = useThemeColors()
return (
<SkeletonScreen>
{title ? <ScreenTitle title={title} /> : null}
{Array.from({ length: rows }, (_, index) => (
<View
key={index}
@@ -494,12 +456,6 @@ const styles = StyleSheet.create({
carousel: { gap: spacing.md, overflow: "hidden" },
carouselRow: { flexDirection: "row", gap: spacing.md },
home: { padding: spacing.lg, gap: spacing.xl },
// Mirrors the home screen's title spacing.
homeTitle: {
paddingHorizontal: 0,
marginTop: -spacing.lg,
marginBottom: -spacing.md,
},
centeredHero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm },
actions: {
flexDirection: "row",
+5 -20
View File
@@ -6,7 +6,7 @@ import {
type ReactElement,
} from "react"
import {
type ScrollViewInstance,
ScrollView,
View,
type NativeSyntheticEvent,
type NativeScrollEvent,
@@ -15,7 +15,6 @@ import Animated from "react-native-reanimated"
import { useSafeAreaInsets } from "react-native-safe-area-context"
import type { MediaItem } from "@/components/media-cards"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { useMediaGridLayout } from "@/hooks/use-media-grid-layout"
import { tabletLayoutTransition } from "@/lib/tablet-motion"
import { useThemeColors } from "@/lib/theme"
@@ -29,8 +28,6 @@ type GridProps = {
onEndReached?: () => void
ListHeaderComponent?: ReactElement
contentInset?: boolean
/** iOS `ScreenTitle` shown above the grid; it replaces the top inset. */
title?: string
renderCard: (item: MediaItem, width: number) => ReactElement
}
@@ -44,12 +41,9 @@ export function TabletMediaGrid({
onEndReached,
ListHeaderComponent,
contentInset = true,
title,
renderCard,
}: GridProps) {
const colors = useThemeColors()
const { ref, scrollY: titleScrollY } =
useScreenTitleScroll<ScrollViewInstance>()
const insets = useSafeAreaInsets()
const { columns, cardWidth, onLayout, horizontalPadding, gap, ready } =
useMediaGridLayout()
@@ -108,27 +102,18 @@ export function TabletMediaGrid({
setViewportHeight(event.nativeEvent.layout.height)
}}
>
<Animated.ScrollView
ref={ref}
<ScrollView
onScroll={onScroll}
// Every frame, so the title pins smoothly on pull-down.
scrollEventThrottle={16}
scrollEventThrottle={32}
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={{
paddingTop: contentInset && !title ? horizontalPadding : 0,
paddingTop: contentInset ? horizontalPadding : 0,
paddingBottom: paddingBottom + insets.bottom,
}}
>
<View
onLayout={(event) => setHeaderHeight(event.nativeEvent.layout.height)}
>
{title ? (
<ScreenTitle
title={title}
scrollY={titleScrollY}
style={{ paddingHorizontal: horizontalPadding }}
/>
) : null}
{ListHeaderComponent}
</View>
<View style={{ height: gridHeight }}>
@@ -151,7 +136,7 @@ export function TabletMediaGrid({
)
})}
</View>
</Animated.ScrollView>
</ScrollView>
</Animated.View>
)
}
+48 -31
View File
@@ -25,6 +25,7 @@ import { AndroidSheet } from "@/components/android-sheet"
import { AudioFormatBadge } from "@/components/audio-format-badge"
import { useCacheScope } from "@/contexts/persistent-cache"
import { useServerConfig } from "@/contexts/server-config"
import { useBackgroundDownloads } from "@/hooks/use-background-downloads"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { getAuthCookieHeader } from "@/lib/auth-cookies"
import {
@@ -33,6 +34,7 @@ import {
writeRememberedDownloadQuality,
} from "@/lib/downloads"
import { loadPlaybackSongs } from "@/lib/playback-files"
import { downloadQualitySupported } from "@/lib/playback-capabilities"
import type { ServerConfig } from "@/lib/server-config"
import { showError } from "@/lib/toast"
import { useThemeColors } from "@/lib/theme"
@@ -237,36 +239,44 @@ function DownloadQualityPopup({
>
{pending?.target.title}
</Text>
{pending?.response.options.map((option) => (
<Pressable
key={option.quality}
accessibilityRole="button"
style={[styles.row, { borderBottomColor: colors.border }]}
onPress={() => onPick(option.quality, remember)}
>
<View style={styles.rowText}>
{option.quality === "lossless" ||
option.quality === "atmos" ? (
<AudioFormatBadge
format={option.quality}
color={colors.foreground}
backgroundColor={colors.card}
/>
) : (
<Text style={[styles.label, { color: colors.foreground }]}>
{DOWNLOAD_QUALITY_LABELS[option.quality]}
{pending?.response.options
.filter((option) => downloadQualitySupported(option.quality))
.map((option) => (
<Pressable
key={option.quality}
accessibilityRole="button"
style={[styles.row, { borderBottomColor: colors.border }]}
onPress={() => onPick(option.quality, remember)}
>
<View style={styles.rowText}>
{option.quality === "lossless" ||
option.quality === "atmos" ? (
<AudioFormatBadge
format={option.quality}
color={colors.foreground}
backgroundColor={colors.card}
/>
) : (
<Text
style={[styles.label, { color: colors.foreground }]}
>
{DOWNLOAD_QUALITY_LABELS[option.quality]}
</Text>
)}
<Text
style={{ color: colors.mutedForeground, fontSize: 12 }}
>
{optionDetail(option, songCount)}
</Text>
)}
<Text style={{ color: colors.mutedForeground, fontSize: 12 }}>
{optionDetail(option, songCount)}
</View>
<Text
style={[styles.size, { color: colors.mutedForeground }]}
>
{option.estimated ? "~" : ""}
{formatBytes(option.bytes)}
</Text>
</View>
<Text style={[styles.size, { color: colors.mutedForeground }]}>
{option.estimated ? "~" : ""}
{formatBytes(option.bytes)}
</Text>
</Pressable>
))}
</Pressable>
))}
<View style={styles.rememberRow}>
<Text style={{ color: colors.foreground, fontSize: 15 }}>
Remember my choice
@@ -344,6 +354,7 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
target: DownloadTarget
response: DownloadOptionsResponse
} | null>(null)
const keepDownloading = useBackgroundDownloads(queue)
useEffect(() => {
if (!queue) return
@@ -391,6 +402,7 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
const remembered = await readRememberedDownloadQuality()
if (remembered) {
await startDownload(queue, target, response.songs, remembered)
keepDownloading()
toast(`Downloading ${target.title}`)
} else {
setPending({ target, response })
@@ -399,7 +411,7 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
showError(error instanceof Error ? error.message : "Download failed")
}
},
[cacheScope, config, convex, queue]
[cacheScope, config, convex, keepDownloading, queue]
)
const removeDownload = useCallback(
@@ -417,9 +429,14 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
if (!pending || !queue) return
setPending(null)
if (remember) void writeRememberedDownloadQuality(quality)
void startDownload(queue, pending.target, pending.response.songs, quality)
void startDownload(
queue,
pending.target,
pending.response.songs,
quality
).then(keepDownloading)
},
[pending, queue]
[keepDownloading, pending, queue]
)
const value = useMemo(
@@ -0,0 +1,164 @@
import { requireOptionalNativeModule } from "expo"
import Constants from "expo-constants"
import { useCallback, useEffect, useRef } from "react"
import { AppState, Platform } from "react-native"
import {
ContinuedTasks,
type ContinuedTask,
} from "react-native-continued-task"
import { setKeptRunning } from "@/lib/downloads"
import type { DownloadQueue } from "@otunes/convex/client/download-queue"
const downloadService = requireOptionalNativeModule<{
update: (remaining: number) => void
}>("DownloadService")
/** Songs downloading at once while the app runs, as the queue defaults to. */
const RUNNING_CONCURRENCY = 2
// Stopping right after starting can beat the service to `startForeground`,
// which Android treats as a crash.
const STOP_DELAY_MS = 2000
// Must match `identifierPrefixes` in app.config.ts.
const TASK_PREFIX = `${Constants.expoConfig?.ios?.bundleIdentifier}.downloads`
function songsLeft(count: number) {
return count === 1 ? "1 song left" : `${count} songs left`
}
/**
* Keeps downloads going while the app is in the background. Call the returned
* function right after the person starts a download.
*
* iOS 26+: a continued processing task keeps the app running, with progress
* in a Live Activity, so songs keep downloading a few at a time with fresh
* sign-in tokens. It must start from the person's action, so it covers
* downloads they start, not playlist syncs.
*
* iOS otherwise (and once that task ends): songs download in a background URL
* session. Songs started while suspended may wait for Wi-Fi and power, so
* every waiting song is handed over as the app leaves the screen.
*
* Android: a foreground service keeps the app running while songs are queued.
*/
export function useBackgroundDownloads(queue: DownloadQueue | null) {
const startTask = useRef<() => void>(() => {})
useEffect(() => {
if (!queue) return
if (Platform.OS === "ios") {
let active = AppState.currentState === "active"
let task: ContinuedTask | null = null
let submitting = false
let total = 0
let lastPending = 0
const updateConcurrency = () =>
queue.setConcurrency(
active || task?.state === "running" ? RUNNING_CONCURRENCY : Infinity
)
const end = () => {
task = null
setKeptRunning(false)
updateConcurrency()
}
const report = () => {
const pending = queue.pendingCount()
if (pending > lastPending) total += pending - lastPending
lastPending = pending
if (task?.state !== "running") return
if (pending === 0) {
task.complete(true)
end()
return
}
task.setProgress(total - pending, total)
task.updateTitle("Downloading", songsLeft(pending))
}
startTask.current = () => {
if (!ContinuedTasks.isSupported || task || submitting) return
const pending = queue.pendingCount()
if (pending === 0) return
submitting = true
total = pending
lastPending = pending
ContinuedTasks.submit({
identifierPrefix: TASK_PREFIX,
title: "Downloading",
subtitle: songsLeft(pending),
totalUnitCount: total,
// A task that cannot start now is no use once the app is closed.
ios: { submissionStrategy: "fail" },
})
.then((submitted) => {
task = submitted
submitted.addOnStartListener(() => {
setKeptRunning(true)
updateConcurrency()
report()
})
// iOS reports a cancel from the Live Activity as expiry too, so
// either way the songs carry on in the background session.
submitted.addOnStopListener(() => {
if (task === submitted) end()
})
})
.catch(() => {
// Not permitted or unavailable: the background session covers it.
})
.finally(() => {
submitting = false
})
}
updateConcurrency()
const unsubscribe = queue.subscribe(report)
const subscription = AppState.addEventListener("change", (state) => {
active = state === "active"
updateConcurrency()
})
return () => {
startTask.current = () => {}
unsubscribe()
subscription.remove()
task?.cancel()
end()
}
}
if (!downloadService) return
const service = downloadService
let shown = 0
let stopTimer: ReturnType<typeof setTimeout> | null = null
const update = () => {
const remaining = queue.pendingCount()
if (remaining === shown) return
if (stopTimer) clearTimeout(stopTimer)
stopTimer = null
if (remaining > 0) {
shown = remaining
service.update(remaining)
} else {
stopTimer = setTimeout(() => {
shown = 0
service.update(0)
}, STOP_DELAY_MS)
}
}
update()
const unsubscribe = queue.subscribe(update)
return () => {
unsubscribe()
if (stopTimer) clearTimeout(stopTimer)
service.update(0)
}
}, [queue])
return useCallback(() => startTask.current(), [])
}
+50 -1
View File
@@ -1,5 +1,18 @@
import { File } from "expo-file-system"
import { useEffect, useMemo, useState, useSyncExternalStore } from "react"
import {
useEffect,
useMemo,
useRef,
useState,
useSyncExternalStore,
} from "react"
import {
cancelAnimation,
Easing,
useSharedValue,
withSequence,
withTiming,
} from "react-native-reanimated"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
@@ -107,3 +120,39 @@ export function useLyricsTime(
? advanced.time
: currentTime
}
/** How far the clock may drift from the player before it is reset. */
const CLOCK_DRIFT_SECONDS = 0.15
/** How far ahead the clock runs on its own; progress updates come long before. */
const CLOCK_RUN_SECONDS = 3600
/**
* Playback time in seconds on the UI thread, running smoothly between the
* player's progress updates. It is reset only when it drifts, so animations
* driven by it never restart mid-word.
*/
export function usePlaybackClock(currentTime: number, isPlaying: boolean) {
const clock = useSharedValue(currentTime)
const running = useRef(false)
useEffect(() => {
if (!isPlaying) {
running.current = false
cancelAnimation(clock)
clock.value = currentTime
return
}
const drift = Math.abs(clock.value - currentTime)
if (running.current && drift < CLOCK_DRIFT_SECONDS) return
running.current = true
clock.value = withSequence(
withTiming(currentTime, { duration: 0 }),
withTiming(currentTime + CLOCK_RUN_SECONDS, {
duration: CLOCK_RUN_SECONDS * 1000,
easing: Easing.linear,
})
)
}, [clock, currentTime, isPlaying])
return clock
}
+22 -8
View File
@@ -1,5 +1,5 @@
import { useRouter, useSegments, type Href } from "expo-router"
import { useCallback } from "react"
import { createContext, use, useCallback } from "react"
import { tabletSections } from "@/lib/tablet-navigation"
@@ -30,6 +30,13 @@ export function tabPath(tab: AppTab, path: string): Href {
return `/(app)/(tabs)/${tab}${normalized}` as Href
}
/**
* The tab whose stack a screen lives in. Each tab stack layout provides it so
* links resolve against the screen's own tab, even when the global segments
* ref has not caught up with a tab switch yet.
*/
export const TabStackContext = createContext<AppTab | undefined>(undefined)
function getActiveTabFromRef(): AppTab {
return getActiveTab(activeSegmentsRef.current)
}
@@ -41,8 +48,15 @@ export function AppNavigationSync() {
return null
}
/** Tab-aware navigation: paths resolve inside the caller's tab stack, falling back to the active tab outside one. */
export function useAppNavigation() {
const router = useRouter()
const stackTab = use(TabStackContext)
const currentTab = useCallback(
() => stackTab ?? getActiveTabFromRef(),
[stackTab]
)
const push = useCallback(
(path: string) => {
@@ -53,26 +67,26 @@ export function useAppNavigation() {
return
}
router.push(tabPath(getActiveTabFromRef(), path))
router.push(tabPath(currentTab(), path))
},
[router]
[router, currentTab]
)
const replace = useCallback(
(path: string) => {
router.replace(tabPath(getActiveTabFromRef(), path))
router.replace(tabPath(currentTab(), path))
},
[router]
[router, currentTab]
)
const href = useCallback(
(path: string) => tabPath(getActiveTabFromRef(), path),
[]
(path: string) => tabPath(currentTab(), path),
[currentTab]
)
return {
get tab() {
return getActiveTabFromRef()
return currentTab()
},
href,
push,
+9 -2
View File
@@ -16,9 +16,16 @@ function authCookieNames(serverUrl: string) {
}
}
/**
* Cookies that sign a request to the server in. Pass `refresh: false` for
* requests that may run after the JWT expires (iOS background downloads): the
* server would spend the refresh token, and the app's next refresh of the same
* token would then end the session.
*/
export async function getAuthCookieHeader(
serverUrl: string,
convexUrl: string
convexUrl: string,
{ refresh = true }: { refresh?: boolean } = {}
): Promise<string | null> {
const [jwt, refreshToken] = await Promise.all([
secureGetItem(authStorageKey(JWT_STORAGE_KEY, convexUrl)),
@@ -31,7 +38,7 @@ export async function getAuthCookieHeader(
const names = authCookieNames(serverUrl)
const parts = [`${names.jwt}=${jwt}`]
if (refreshToken) {
if (refresh && refreshToken) {
parts.push(`${names.refresh}=${refreshToken}`)
}
+11 -2
View File
@@ -12,19 +12,28 @@ const secureStoreOptions: SecureStore.SecureStoreOptions = {
keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK,
}
// The last value read or written per key, for when the keychain refuses a
// read (say, while the phone is locked and downloads continue).
const remembered = new Map<string, string>()
export async function secureGetItem(key: string): Promise<string | null> {
try {
return await SecureStore.getItemAsync(key, secureStoreOptions)
const value = await SecureStore.getItemAsync(key, secureStoreOptions)
if (value === null) remembered.delete(key)
else remembered.set(key, value)
return value
} catch {
return null
return remembered.get(key) ?? null
}
}
export async function secureSetItem(key: string, value: string): Promise<void> {
remembered.set(key, value)
await SecureStore.setItemAsync(key, value, secureStoreOptions)
}
export async function secureRemoveItem(key: string): Promise<void> {
remembered.delete(key)
try {
await SecureStore.deleteItemAsync(key, secureStoreOptions)
} catch {
+100 -12
View File
@@ -1,5 +1,5 @@
import AsyncStorage from "@react-native-async-storage/async-storage"
import { Directory, File, Paths } from "expo-file-system"
import { Directory, DownloadTask, File, Paths } from "expo-file-system"
import { Platform } from "react-native"
import {
@@ -16,6 +16,7 @@ import {
type DownloadQuality,
} from "@otunes/convex/download-quality"
import { getAuthCookieHeader } from "@/lib/auth-cookies"
import { downloadQualitySupported } from "@/lib/playback-capabilities"
import type { ServerConfig } from "@/lib/server-config"
const REMEMBERED_QUALITY_KEY = "otunes.download-quality"
@@ -73,6 +74,82 @@ function audioFile(folder: Directory) {
return folder.list().find((entry): entry is File => entry instanceof File)
}
type SongDownload = {
url: string
destination: Directory
headers: Record<string, string>
signal: AbortSignal
/** Checks and keeps the downloaded file, returning its size. */
finish: (file: File) => number
}
// Whether a continued processing task keeps the app running in the
// background (iOS 26+, see `useBackgroundDownloads`).
let keptRunning = false
const regularSessionDownloads = new Set<() => void>()
/**
* While a continued task keeps the app running, songs download through the
* regular session: iOS treats background session downloads started from the
* background as deferrable until Wi-Fi and power. When the task ends, running
* songs restart in the background session before iOS suspends the app.
*/
export function setKeptRunning(running: boolean) {
keptRunning = running
if (!running) for (const handOff of regularSessionDownloads) handOff()
}
/**
* Downloads through an iOS URL session. The background one keeps going while
* the app is suspended and wakes it when done; iOS keeps the app awake until
* `finish` returns (up to 25 seconds). Downloads still running when iOS
* terminates the app are lost.
*/
async function runDownloadTask(
{ url, destination, headers, signal, finish }: SongDownload,
sessionType: "foreground" | "background"
) {
const task = new DownloadTask(url, destination, {
headers,
signal,
sessionType,
deferBackgroundSessionCompletion: sessionType === "background",
})
const handOff = () => task.cancel()
if (sessionType === "foreground") regularSessionDownloads.add(handOff)
try {
const file = await task.downloadAsync()
if (!file) throw new Error("Download paused")
return finish(file)
} finally {
regularSessionDownloads.delete(handOff)
if (task.state === "completed") {
await task.acknowledgeBackgroundCompletionAsync().catch(() => {})
}
task.release()
}
}
async function downloadOnIOS(download: SongDownload) {
if (keptRunning) {
try {
return await runDownloadTask(download, "foreground")
} catch (error) {
// Still running means a real failure; otherwise it was handed off.
if (keptRunning || download.signal.aborted) throw error
}
}
return runDownloadTask(download, "background")
}
/** Android keeps the app running with a foreground service instead. */
async function downloadInForeground(download: SongDownload) {
const { url, destination, headers, signal, finish } = download
return finish(
await File.downloadFileAsync(url, destination, { headers, signal })
)
}
function createStorage(config: ServerConfig): DownloadStorage {
const root = serverDirectory(config)
const indexFile = new File(root, "index.json")
@@ -116,7 +193,8 @@ function createStorage(config: ServerConfig): DownloadStorage {
async save({ songId, requested, quality, albumId }, signal) {
const cookieHeader = await getAuthCookieHeader(
config.serverUrl,
config.convexUrl
config.convexUrl,
{ refresh: Platform.OS !== "ios" }
)
if (!cookieHeader) throw new Error("Sign in to download")
@@ -126,17 +204,26 @@ function createStorage(config: ServerConfig): DownloadStorage {
if (partial.exists) partial.delete()
partial.create()
try {
const path = songDownloadPath(songId, requested, {
const url = `${config.serverUrl}${songDownloadPath(songId, requested, {
losslessFormat: Platform.OS === "ios" ? "alac" : undefined,
})}`
const download =
Platform.OS === "ios" ? downloadOnIOS : downloadInForeground
return await download({
url,
destination: partial,
headers: { Cookie: cookieHeader },
signal,
finish(file) {
signal.throwIfAborted()
// A lapsed sign-in redirects to the sign-in page instead of failing.
if (file.extension === ".html") {
throw new Error("Sign in to download")
}
partial.rename(name)
return file.size ?? 0
},
})
const file = await File.downloadFileAsync(
`${config.serverUrl}${path}`,
partial,
{ headers: { Cookie: cookieHeader }, signal }
)
signal.throwIfAborted()
partial.rename(name)
return file.size ?? 0
} catch (error) {
if (partial.exists) partial.delete()
throw error
@@ -212,9 +299,10 @@ export function downloadedCoverUri(url: string) {
export async function readRememberedDownloadQuality() {
try {
return parseDownloadQuality(
const quality = parseDownloadQuality(
await AsyncStorage.getItem(REMEMBERED_QUALITY_KEY)
)
return quality && downloadQualitySupported(quality) ? quality : undefined
} catch {
return undefined
}
+1 -8
View File
@@ -17,20 +17,13 @@ export const tabStackScreenTitles: Record<string, string> = {
"downloads/other": "Other Downloaded Songs",
}
/**
* iOS tab stacks render their titles in the scroll content with
* `ScreenTitle`, so the bar keeps the title (for back menus) but hides it.
*/
export const inlineTitleOptions: StackScreenOptions =
Platform.OS === "ios" ? { headerTitleStyle: { color: "transparent" } } : {}
export function useStackScreenOptions(
overrides?: StackScreenOptions
): StackScreenOptions {
const theme = useThemeColors()
return {
headerLargeTitle: false,
headerLargeTitle: true,
headerTransparent: true,
headerTintColor: theme.foreground,
headerLargeTitleStyle: { color: theme.foreground },
-3
View File
@@ -12,8 +12,6 @@ export type NowPlayingColors = {
selected: string
selectedForeground: string
highlight: string
/** Lyrics lines other than the one playing. */
lyricsInactive: string
/** Words of the playing line not yet sung. */
lyricsUnsung: string
isDark: boolean
@@ -32,7 +30,6 @@ export function nowPlayingColors(palette: CoverPalette): NowPlayingColors {
selected: withAlpha(foreground, 0.8),
selectedForeground: palette.background,
highlight: withAlpha(foreground, 0.1),
lyricsInactive: withAlpha(foreground, 0.35),
lyricsUnsung: withAlpha(foreground, 0.55),
isDark: palette.isDark,
}
+15
View File
@@ -1,5 +1,10 @@
import { Platform } from "react-native"
import {
DOWNLOAD_QUALITIES,
type DownloadQuality,
} from "@otunes/convex/download-quality"
// Android Dolby decoder reports do not reliably indicate working Atmos playback.
export const dolbyAtmosSupported = Platform.OS === "ios"
@@ -7,3 +12,13 @@ export const dolbyAtmosSupported = Platform.OS === "ios"
export function atmosEnabled(user: { preferAtmos?: boolean }) {
return dolbyAtmosSupported && (user.preferAtmos ?? false)
}
/** Whether this device may download in a quality. Android cannot download Atmos. */
export function downloadQualitySupported(quality: DownloadQuality) {
return quality !== "atmos" || dolbyAtmosSupported
}
/** Download qualities this device offers, lowest first. */
export const deviceDownloadQualities = DOWNLOAD_QUALITIES.filter(
downloadQualitySupported
)
@@ -0,0 +1,11 @@
plugins {
id 'com.android.library'
id 'expo-module-gradle-plugin'
}
group = 'expo.modules.downloadservice'
version = '1.0.0'
android {
namespace 'expo.modules.downloadservice'
}
@@ -0,0 +1,11 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<application>
<service
android:name="expo.modules.downloadservice.DownloadService"
android:exported="false"
android:foregroundServiceType="dataSync" />
</application>
</manifest>
@@ -0,0 +1,88 @@
package expo.modules.downloadservice
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
/**
* Keeps the app running while songs download, so Android does not freeze the
* JS downloads when the app leaves the screen. Started with the number of
* songs left, and stopped by the module once none are.
*/
class DownloadService : Service() {
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val remaining = intent?.getIntExtra(EXTRA_REMAINING, 0) ?: 0
val notification = notification(remaining)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
} else {
startForeground(NOTIFICATION_ID, notification)
}
// A restarted service would have no downloads to keep alive.
return START_NOT_STICKY
}
// Android 15 limits data sync services to six hours a day.
override fun onTimeout(startId: Int, fgsType: Int) {
stopSelf()
}
private fun notification(remaining: Int): Notification {
val manager = getSystemService(NotificationManager::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
manager.createNotificationChannel(
NotificationChannel(CHANNEL_ID, "Downloads", NotificationManager.IMPORTANCE_LOW)
)
}
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(this, CHANNEL_ID)
} else {
@Suppress("DEPRECATION")
Notification.Builder(this)
}
val launch = packageManager.getLaunchIntentForPackage(packageName)?.let {
PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_IMMUTABLE)
}
return builder
.setSmallIcon(android.R.drawable.stat_sys_download)
.setContentTitle(if (remaining == 1) "Downloading 1 song" else "Downloading $remaining songs")
.setContentIntent(launch)
.setOngoing(true)
.setOnlyAlertOnce(true)
.build()
}
companion object {
private const val CHANNEL_ID = "downloads"
private const val NOTIFICATION_ID = 7301
private const val EXTRA_REMAINING = "remaining"
fun update(context: Context, remaining: Int) {
val intent = Intent(context, DownloadService::class.java)
if (remaining == 0) {
context.stopService(intent)
return
}
intent.putExtra(EXTRA_REMAINING, remaining)
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent)
} else {
context.startService(intent)
}
} catch (_: IllegalStateException) {
// Android 12+ refuses to start one from the background (say, a
// playlist syncing); downloads then run only while the app does.
}
}
}
}
@@ -0,0 +1,15 @@
package expo.modules.downloadservice
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
class DownloadServiceModule : Module() {
override fun definition() = ModuleDefinition {
Name("DownloadService")
/** Shows how many songs are left, or stops the service at zero. */
Function("update") { remaining: Int ->
DownloadService.update(requireNotNull(appContext.reactContext), remaining)
}
}
}
@@ -0,0 +1,6 @@
{
"platforms": ["android"],
"android": {
"modules": ["expo.modules.downloadservice.DownloadServiceModule"]
}
}
@@ -0,0 +1,5 @@
{
"name": "otunes-download-service",
"version": "1.0.0",
"private": true
}
@@ -0,0 +1,3 @@
{
"platforms": ["apple"]
}
@@ -0,0 +1,37 @@
// React Native draws `filter: [{ blur }]` on iOS only with its SwiftUI
// filters flag, which the stable release leaves off. This keeps the stable
// flags and turns that one on.
#import <UIKit/UIKit.h>
#import <react/featureflags/ReactNativeFeatureFlags.h>
#import <react/featureflags/ReactNativeFeatureFlagsOverridesOSSStable.h>
using namespace facebook::react;
class SwiftUIFilterFlags : public ReactNativeFeatureFlagsOverridesOSSStable {
public:
bool enableSwiftUIBasedFilters() override {
return true;
}
};
@interface SwiftUIFilters : NSObject
@end
@implementation SwiftUIFilters
+ (void)load
{
// React Native sets its flags once while launching and throws if they were
// set first, so this waits for launch to finish. No views exist yet then.
[NSNotificationCenter.defaultCenter
addObserverForName:UIApplicationDidFinishLaunchingNotification
object:nil
queue:nil
usingBlock:^(NSNotification *notification) {
ReactNativeFeatureFlags::dangerouslyForceOverride(
std::make_unique<SwiftUIFilterFlags>());
}];
}
@end
@@ -0,0 +1,14 @@
Pod::Spec.new do |s|
s.name = 'SwiftUIFilters'
s.version = '1.0.0'
s.summary = 'Turns on React Native view filters like blur on iOS'
s.description = s.summary
s.license = { :type => 'MIT' }
s.author = 'oTunes'
s.homepage = 'https://otunes.abunchofknowitalls.com'
s.platforms = { :ios => '16.4' }
s.source = { :git => '' }
s.static_framework = true
install_modules_dependencies(s)
s.source_files = '**/*.{h,mm}'
end
+3
View File
@@ -20,6 +20,7 @@
"@otunes/convex": "workspace:*",
"@react-native-async-storage/async-storage": "2.2.0",
"@react-native-community/slider": "5.2.1",
"@react-native-masked-view/masked-view": "0.3.2",
"@react-native/metro-config": "0.88.0",
"convex": "^1.40.0",
"expo": "~58.0.17",
@@ -48,8 +49,10 @@
"react": "19.3.0",
"react-dom": "19.3.0",
"react-native": "0.88.0",
"react-native-continued-task": "0.1.0",
"react-native-gesture-handler": "~3.3.0",
"react-native-image-colors": "^2.6.0",
"react-native-nitro-modules": "0.37.2",
"react-native-reanimated": "4.7.1",
"react-native-safe-area-context": "~5.10.1",
"react-native-screens": "4.30.0",
+3
View File
@@ -114,6 +114,7 @@ export function AlbumView({
}) {
const {
isSongFavorite,
areSongsFavorite,
isAlbumFavorite,
toggleSongFavorite,
toggleAlbumFavorite,
@@ -154,6 +155,7 @@ export function AlbumView({
handlePointerDown,
prepareContextMenu,
} = useTrackSelection(album.tracks, validHighlightedSongId)
const selectionFavorited = areSongsFavorite(selectedIds)
const selectionPositions = React.useMemo(
() =>
@@ -413,6 +415,7 @@ export function AlbumView({
isFavorite={isSongFavorite(track.id)}
selectedCount={selectedCount}
selectionStationArtistId={album.artist.id}
selectionFavorited={selectionFavorited}
isNowPlaying={currentSongId === track.id}
onPointerDown={handlePointerDown}
onSelect={handleRowSelect}
+4 -3
View File
@@ -39,9 +39,10 @@ const ASK_EVERY_TIME = "ask"
/** Shades of the text color, darkest for the smallest files. */
const QUALITY_OPACITY: Record<DownloadQuality, number> = {
medium: 0.25,
high: 0.45,
lossless: 0.7,
low: 0.2,
medium: 0.35,
high: 0.5,
lossless: 0.75,
atmos: 1,
}
+12 -21
View File
@@ -37,7 +37,8 @@ type FavoritesContextValue = {
) => Promise<boolean>
toggleAlbumFavorite: (albumId: Id<"albums">) => Promise<void>
toggleArtistFavorite: (artistId: Id<"artists">) => Promise<void>
favoriteSongs: (songIds: Id<"songs">[]) => Promise<void>
/** True when `songIds` is non-empty and every song is favorited. */
areSongsFavorite: (songIds: Iterable<string>) => boolean
}
const FavoritesContext = React.createContext<FavoritesContextValue | null>(null)
@@ -130,26 +131,16 @@ export function FavoritesProvider({ children }: { children: React.ReactNode }) {
[songIds, favoriteSong, unfavoriteSong]
)
const favoriteSongs = React.useCallback(
async (ids: Id<"songs">[]) => {
const unique = [...new Set(ids)]
if (unique.length === 0) {
return
}
try {
await favoriteSongsMutation({ songIds: unique })
toast.success(
unique.length > 1
? `Favorited ${unique.length} songs`
: "Added to favorites"
)
} catch (error) {
toast.error(
error instanceof Error ? error.message : "Failed to update favorites"
)
const areSongsFavorite = React.useCallback(
(ids: Iterable<string>) => {
let any = false
for (const id of ids) {
if (!songIds.has(id)) return false
any = true
}
return any
},
[favoriteSongsMutation]
[songIds]
)
const toggleSongsFavorite = React.useCallback(
@@ -232,7 +223,7 @@ export function FavoritesProvider({ children }: { children: React.ReactNode }) {
toggleSongsFavorite,
toggleAlbumFavorite,
toggleArtistFavorite,
favoriteSongs,
areSongsFavorite,
}),
[
isSongFavorite,
@@ -242,7 +233,7 @@ export function FavoritesProvider({ children }: { children: React.ReactNode }) {
toggleSongsFavorite,
toggleAlbumFavorite,
toggleArtistFavorite,
favoriteSongs,
areSongsFavorite,
]
)
+6 -5
View File
@@ -183,7 +183,8 @@ const SyncedLine = React.memo(function SyncedLine({
/**
* The playing line's words, each filled as far as it has been sung. The
* browser runs the fills; playback updates only correct their drift.
* browser runs the fills on the song's timeline (a word's start is its
* delay); playback updates only correct their drift.
*/
function FilledWords({
words,
@@ -200,6 +201,7 @@ function FilledWords({
React.useEffect(() => {
fills.current = words.map((word, index) =>
spans.current[index]?.animate(WORD_FILL_FRAMES, {
delay: word.start * 1000,
duration: Math.max(word.end - word.start, 0.05) * 1000,
easing: "linear",
fill: "both",
@@ -209,15 +211,14 @@ function FilledWords({
}, [words])
React.useEffect(() => {
const at = time * 1000
fills.current.forEach((fill, index) => {
if (!fill) return
const at = (time - words[index].start) * 1000
if (Math.abs(Number(fill.currentTime ?? 0) - at) > FILL_DRIFT_MS) {
fill.currentTime = at
}
// `play` on a finished fill would rewind it.
const duration = Number(fill.effect?.getTiming().duration ?? 0)
if (isPlaying && at < duration) fill.play()
// `play` on a finished fill would rewind it to the start.
if (isPlaying && time < words[index].end) fill.play()
else fill.pause()
})
}, [words, time, isPlaying])
+4 -1
View File
@@ -48,7 +48,8 @@ export function OtherDownloadsView() {
[songs]
)
const { isSongFavorite, toggleSongFavorite } = useFavorites()
const { isSongFavorite, areSongsFavorite, toggleSongFavorite } =
useFavorites()
const { playFromSong, playInOrder, playShuffled } = usePlaybackActions()
const {
selectedIds,
@@ -62,6 +63,7 @@ export function OtherDownloadsView() {
() => stationArtistId(songs, selectedIds),
[songs, selectedIds]
)
const selectionFavorited = areSongsFavorite(selectedIds)
const selectionPositions = useMemo(
() =>
getSelectionRangePositions(
@@ -140,6 +142,7 @@ export function OtherDownloadsView() {
isFavorite={isSongFavorite(songs[index].id)}
selectedCount={selectedCount}
selectionStationArtistId={selectedStationArtistId}
selectionFavorited={selectionFavorited}
onPointerDown={handlePointerDown}
onSelect={handleRowSelect}
onPlay={handleRowPlay}
+9 -2
View File
@@ -74,8 +74,12 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
currentUser === undefined
? playlist.isOwner
: currentUser?._id === playlist.owner.id
const { isSongFavorite, toggleSongFavorite, toggleSongsFavorite } =
useFavorites()
const {
isSongFavorite,
areSongsFavorite,
toggleSongFavorite,
toggleSongsFavorite,
} = useFavorites()
const currentSongId = useCurrentSongId()
const {
playInOrder,
@@ -143,6 +147,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
() => stationArtistId(songs, selectedIds),
[songs, selectedIds]
)
const selectionFavorited = areSongsFavorite(selectedIds)
const selectionPositions = React.useMemo(
() =>
@@ -465,6 +470,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
onAction={handlePlaylistMediaAction}
playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
showFavorite={!isFavorites}
favorited={areSongsFavorite(playlistSongIds)}
downloaded={playlistDownloaded}
trackRowTrigger={false}
triggerVariant="secondary"
@@ -522,6 +528,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
selectionPosition={selectionPositions[index]}
selectedCount={selectedCount}
selectionStationArtistId={selectedStationArtistId}
selectionFavorited={selectionFavorited}
playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
downloadCollection={downloadRef}
showFavoriteInMenu={!isFavorites}
+7 -1
View File
@@ -244,7 +244,7 @@ export function QueuePanel() {
prepareContextMenu,
clearSelection,
} = useTrackSelection(selectionItems)
const { isSongFavorite } = useFavorites()
const { isSongFavorite, areSongsFavorite } = useFavorites()
const { runSongsAction } = useMediaActions()
/** The rows a menu acts on: the selection, else just the clicked row. */
@@ -268,6 +268,11 @@ export function QueuePanel() {
),
[selectableQueue, selectedIds]
)
const selectionFavorited = areSongsFavorite(
selectableQueue.flatMap((item) =>
item.song && selectedIds.has(item.selectionId) ? [item.song.id] : []
)
)
const handleMediaAction = React.useCallback(
(action: MediaContextAction, selectionId: string) => {
@@ -453,6 +458,7 @@ export function QueuePanel() {
isFavorite={isSongFavorite(item.song.id)}
selectedCount={selectedCount}
selectionStationArtistId={selectedStationArtistId}
selectionFavorited={selectionFavorited}
removeLabel="Remove from Queue"
selectionPosition={selectionPositions[index]}
isDragging={draggingIndices.has(index)}
+4 -1
View File
@@ -47,7 +47,8 @@ const SONGS_PAGE_SIZE = 50
const estimateSongRowSize = () => 56
export function SongsView() {
const { isSongFavorite, toggleSongFavorite } = useFavorites()
const { isSongFavorite, areSongsFavorite, toggleSongFavorite } =
useFavorites()
const { playFromLibrarySong } = usePlaybackActions()
const [sortKey, setSortKey] = useState<SortKey>("title")
const [sortDirection, setSortDirection] = useState<SortDirection>("asc")
@@ -98,6 +99,7 @@ export function SongsView() {
() => stationArtistId(songs, selectedIds),
[songs, selectedIds]
)
const selectionFavorited = areSongsFavorite(selectedIds)
const selectionPositions = useMemo(
() =>
@@ -222,6 +224,7 @@ export function SongsView() {
isFavorite={isSongFavorite(songs[index].id)}
selectedCount={selectedCount}
selectionStationArtistId={selectedStationArtistId}
selectionFavorited={selectionFavorited}
onPointerDown={handlePointerDown}
onSelect={handleRowSelect}
onPlay={handleRowPlay}
+7 -1
View File
@@ -68,6 +68,8 @@ export type TrackRowProps = {
selectedCount?: number
/** Station artist for the selection when this row is selected. */
selectionStationArtistId?: string
/** Whether every selected song is favorited, when this row is selected. */
selectionFavorited?: boolean
playlistLabel?: string
showFavoriteInMenu?: boolean
/** Adds a destructive menu item calling `onRemove`. */
@@ -268,6 +270,7 @@ function TrackRowComponent({
isDragging = false,
selectedCount = 0,
selectionStationArtistId,
selectionFavorited,
playlistLabel,
showFavoriteInMenu = true,
removeLabel,
@@ -345,7 +348,10 @@ function TrackRowComponent({
onAction: (action) => onMediaAction(action, rowId),
playlistLabel,
showFavorite: showFavoriteInMenu,
favorited: isFavorite,
favorited:
inRange && selectedCount > 0
? (selectionFavorited ?? isFavorite)
: isFavorite,
navigation: {
artist: { id: song.artist.id },
album: { id: song.album.id },
+6 -3
View File
@@ -26,7 +26,8 @@ function songsTitle(songIds: readonly string[]) {
export function useMediaActions() {
const { openAddToPlaylist, openAddArtistToPlaylist } = useAddToPlaylist()
const { favoriteSongs, toggleArtistFavorite } = useFavorites()
const { areSongsFavorite, toggleSongsFavorite, toggleArtistFavorite } =
useFavorites()
const { runQueueAction, createStation } = useQueueMediaActions()
const convex = useConvex()
const cacheScope = useCacheScope()
@@ -44,7 +45,8 @@ export function useMediaActions() {
if (stationArtist) void createStation(stationArtist)
break
case "favorite":
void favoriteSongs(songIds)
// Unfavorite only when every song already is, matching the menu label.
void toggleSongsFavorite(songIds, areSongsFavorite(songIds))
break
case "playlist":
openAddToPlaylist(songIds)
@@ -73,7 +75,8 @@ export function useMediaActions() {
},
[
createStation,
favoriteSongs,
areSongsFavorite,
toggleSongsFavorite,
openAddToPlaylist,
runQueueAction,
requestDownload,
+13 -1
View File
@@ -125,8 +125,9 @@ function collectionKey({ kind, id }: CollectionRef) {
*/
export function createDownloadQueue(
storage: DownloadStorage,
{ concurrency = 2 }: { concurrency?: number } = {}
options: { concurrency?: number } = {}
) {
let concurrency = options.concurrency ?? 2
const downloaded = new Map<string, DownloadedSong>()
const collections = new Map<string, DownloadedCollection>()
const otherSongIds = new Set<string>()
@@ -372,6 +373,17 @@ export function createDownloadQueue(
collections: () => [...collections.values()],
isQueued,
status,
/** Songs downloading or waiting to. */
pendingCount: () => running.size + waiting.length,
/**
* How many songs download at once. Raising it starts waiting songs now;
* lowering it lets running songs finish.
*/
setConcurrency(limit: number) {
concurrency = limit
pump()
},
/** Songs downloaded on their own, in the order they were added. */
otherSongIds: () => [...otherSongIds],
+93
View File
@@ -0,0 +1,93 @@
/**
* Typo-tolerant word matching, shared by library search, lyrics search and
* in-list song filters.
*/
/**
* Lowercase words without accents or apostrophes, so "Don't Stop Beyoncé"
* gives ["dont", "stop", "beyonce"].
*/
export function searchWords(text: string): string[] {
return (
text
.normalize("NFKD")
.replace(/\p{M}/gu, "")
.toLowerCase()
.replace(/['’]/g, "")
.match(/[\p{L}\p{N}]+/gu) ?? []
)
}
/** Typos a query word may hold. Short words get none, or they match too much. */
function allowedTypos(term: string) {
if (term.length < 4) return 0
return term.length < 8 ? 1 : 2
}
/**
* Edits (insert, delete, substitute or swap neighbors) turning `a` into `b`,
* or `max + 1` once it is sure to exceed `max`.
*/
function editDistance(a: string, b: string, max: number): number {
if (Math.abs(a.length - b.length) > max) return max + 1
let before: number[] = []
let previous = Array.from({ length: b.length + 1 }, (_, j) => j)
for (let i = 1; i <= a.length; i++) {
const current = [i]
let rowMin = i
for (let j = 1; j <= b.length; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1
let distance = Math.min(
previous[j]! + 1,
current[j - 1]! + 1,
previous[j - 1]! + cost
)
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
distance = Math.min(distance, before[j - 2]! + 1)
}
current.push(distance)
rowMin = Math.min(rowMin, distance)
}
if (rowMin > max) return max + 1
before = previous
previous = current
}
return previous[b.length]!
}
/**
* Whether `word` is query `term` give or take a few typos. With `prefix` the
* word may also just start with the term, as when it is still being typed.
*/
function wordMatchesTerm(term: string, word: string, prefix: boolean) {
const typos = allowedTypos(term)
if (typos === 0) return false
if (editDistance(term, word, typos) <= typos) return true
return (
prefix &&
word.length > term.length &&
editDistance(term, word.slice(0, term.length), typos) <= typos
)
}
/**
* How every query term (from `searchWords`) appears among `words`: "exact"
* when each is a word, "fuzzy" when some only match give or take typos, or
* null when one is missing. The last term may be a word's prefix.
*/
export function matchWords(
words: readonly string[],
terms: readonly string[]
): "exact" | "fuzzy" | null {
let quality: "exact" | "fuzzy" = "exact"
for (const [index, term] of terms.entries()) {
const prefix = index === terms.length - 1
const exact = words.some((word) =>
prefix ? word.startsWith(term) : word === term
)
if (exact) continue
if (!words.some((word) => wordMatchesTerm(term, word, prefix))) return null
quality = "fuzzy"
}
return terms.length > 0 ? quality : null
}
+54 -27
View File
@@ -5,6 +5,8 @@
* the same.
*/
import { matchWords, searchWords } from "./fuzzy-search"
export type LyricWord = {
/** Includes its trailing space, so a line's words join back into its text. */
text: string
@@ -16,11 +18,15 @@ export type LyricLine = {
text: string
/** Seconds; `null` for plain lyrics. */
start: number | null
/** Set only on word-timed lines. */
/**
* The line's words as they are sung. Line-timed lyrics get estimated
* ones (see `estimateWords`); plain lyrics have none.
*/
words: LyricWord[] | null
}
export type Lyrics = {
/** How the source was timed, whatever `words` were estimated. */
synced: "none" | "line" | "word"
lines: LyricLine[]
}
@@ -29,6 +35,8 @@ const LINE_STAMP = /^\[(\d+):(\d+(?:[.:]\d+)?)\]/
const WORD_STAMP = /<(\d+):(\d+(?:[.:]\d+)?)>/g
const HAS_WORD_STAMP = /<\d+:\d+(?:[.:]\d+)?>/
const ID_TAG = /^\[[a-z]+:.*\]$/i
/** A rough singing pace, so a line-timed line's fill tracks its words. */
const ESTIMATED_SECONDS_PER_CHAR = 0.07
function seconds(minutes: string, rest: string) {
return Number(minutes) * 60 + Number(rest.replace(":", "."))
@@ -107,10 +115,31 @@ export function parseLyrics(raw: string): Lyrics | null {
}
lines.sort((a, b) => a.start! - b.start!)
if (lines.length === 0) return null
return {
synced: lines.every((line) => line.words) ? "word" : "line",
lines,
}
const synced = lines.every((line) => line.words) ? "word" : "line"
if (synced === "line") estimateWords(lines)
return { synced, lines }
}
/**
* Gives timed lines without word timing words spread over them by length,
* at a singing pace but never past the next line, so they fill as they play.
*/
function estimateWords(lines: LyricLine[]) {
lines.forEach((line, index) => {
if (line.words || line.start === null) return
const next = lines[index + 1]?.start ?? Infinity
const duration = Math.min(
next - line.start,
line.text.length * ESTIMATED_SECONDS_PER_CHAR
)
const perChar = duration / line.text.length
let at = line.start
line.words = (line.text.match(/\S+\s*/g) ?? []).map((text) => {
const start = at
at += text.length * perChar
return { text, start, end: at }
})
})
}
/** The text without timestamps, one line per row, for search and snippets. */
@@ -185,32 +214,32 @@ export function followLyrics(
return () => clearTimeout(timer)
}
/** Lowercase words of a search, for matching lyrics the way the search index does. */
function searchTerms(query: string): string[] {
return query.toLowerCase().match(/[\p{L}\p{N}']+/gu) ?? []
}
const SNIPPET_LEAD = 24
export type LyricsMatch = {
/** The matched line, trimmed to start near the match. */
snippet: string
/** Whether the line holds the query as typed, not just its words. */
exact: boolean
/**
* 2 when the line holds the query as typed, 1 when it holds every word of
* it, 0 when it does give or take typos.
*/
score: 0 | 1 | 2
}
/**
* Where a search matched the lyrics: a line holding the query as typed, or
* else a line holding every word of it (the last may be a prefix, as when
* typing). Null when no single line does.
* Where a search matched the lyrics: the best line holding the query as
* typed, or else every word of it (see `matchWords`). Null when no single
* line does.
*/
export function matchLyrics(plain: string, query: string): LyricsMatch | null {
const needle = query.trim().toLowerCase()
const terms = searchTerms(needle)
const last = terms.at(-1)
if (!needle || last === undefined) return null
const terms = searchWords(needle)
// Most songs miss a word entirely, so skip them before checking lines.
if (!needle || !matchWords([...new Set(searchWords(plain))], terms)) {
return null
}
let loose: string | null = null
let loose: LyricsMatch | null = null
for (const line of plain.split("\n")) {
const column = line.toLowerCase().indexOf(needle)
if (column !== -1) {
@@ -218,15 +247,13 @@ export function matchLyrics(plain: string, query: string): LyricsMatch | null {
column > SNIPPET_LEAD
? `…${line.slice(column - SNIPPET_LEAD).trimStart()}`
: line.trim()
return { snippet, exact: true }
return { snippet, score: 2 }
}
if (loose === null) {
const words = searchTerms(line)
const hasAll =
terms.slice(0, -1).every((term) => words.includes(term)) &&
words.some((word) => word.startsWith(last))
if (hasAll) loose = line.trim()
if (loose?.score === 1) continue
const quality = matchWords(searchWords(line), terms)
if (quality === "exact" || (quality && !loose)) {
loose = { snippet: line.trim(), score: quality === "exact" ? 1 : 0 }
}
}
return loose === null ? null : { snippet: loose, exact: false }
return loose
}
+14 -10
View File
@@ -1,3 +1,5 @@
import { matchWords, searchWords } from "./fuzzy-search"
type SearchableSong = {
id: string
title: string
@@ -6,9 +8,9 @@ type SearchableSong = {
}
/**
* Case-insensitive match on title, artist, or album, plus the songs in
* `lyricsMatches` (from `api.lyrics.matchingSongIds`). A blank query keeps
* every song.
* Case-insensitive match on title, artist, or album, give or take typos (see
* `matchWords`), plus the songs in `lyricsMatches` (from
* `api.lyrics.matchingSongIds`). A blank query keeps every song.
*/
export function filterSongs<T extends SearchableSong>(
songs: T[],
@@ -19,12 +21,14 @@ export function filterSongs<T extends SearchableSong>(
if (!normalized) {
return songs
}
const terms = searchWords(normalized)
const byLyrics = new Set(lyricsMatches)
return songs.filter(
(song) =>
byLyrics.has(song.id) ||
[song.title, song.artist.name, song.album.title].some((value) =>
value.toLowerCase().includes(normalized)
)
)
return songs.filter((song) => {
if (byLyrics.has(song.id)) return true
const fields = [song.title, song.artist.name, song.album.title]
return (
fields.some((value) => value.toLowerCase().includes(normalized)) ||
matchWords(searchWords(fields.join(" ")), terms) !== null
)
})
}
+27 -11
View File
@@ -27,6 +27,7 @@ import { chunk, type Chunked } from "./limits"
import { recordIntentCatalogChanges } from "./intentCatalogChanges"
import { playlistCoverVersion } from "./playlistCover"
import { deleteSongLyrics, searchSongLyrics, writeSongLyrics } from "./lyrics"
import { matchWords, searchWords } from "../client/fuzzy-search"
export type {
BrowseAlbum,
@@ -618,7 +619,16 @@ export const browseArtistDetail = query({
},
})
function matchScore(text: string, query: string): number {
/**
* How well `text` matches a lowercase search, from 100 (the whole text) down
* to 20 (every word, give or take typos); 0 is no match. `terms` are the
* query's `searchWords`.
*/
function matchScore(
text: string,
query: string,
terms: readonly string[]
): number {
const lower = text.toLowerCase()
if (lower === query) {
return 100
@@ -632,15 +642,20 @@ function matchScore(text: string, query: string): number {
if (lower.includes(query)) {
return 40
}
return 0
const words = matchWords(searchWords(text), terms)
if (words === "exact") {
return 30
}
return words === "fuzzy" ? 20 : 0
}
function matchScoreSongArtists(
artist: string | string[],
query: string
query: string,
terms: readonly string[]
): number {
return getSongArtistNames(artist).reduce(
(best, name) => Math.max(best, matchScore(name, query)),
(best, name) => Math.max(best, matchScore(name, query, terms)),
0
)
}
@@ -658,6 +673,7 @@ export const searchLibrary = query({
args: { query: v.string() },
handler: async (ctx, args) => {
const queryText = args.query.trim().toLowerCase()
const terms = searchWords(queryText)
if (!queryText || !(await isSignedIn(ctx))) {
return {
topResults: [],
@@ -678,7 +694,7 @@ export const searchLibrary = query({
.map((artist) => ({
kind: "artist" as const,
item: toBrowseArtist(artist),
score: matchScore(artist.name, queryText),
score: matchScore(artist.name, queryText, terms),
}))
.filter((result) => result.score > 0)
.sort(
@@ -692,8 +708,8 @@ export const searchLibrary = query({
return []
}
const score = Math.max(
matchScore(album.name, queryText),
matchScore(artist.name, queryText)
matchScore(album.name, queryText, terms),
matchScore(artist.name, queryText, terms)
)
if (score === 0) {
return []
@@ -718,10 +734,10 @@ export const searchLibrary = query({
return []
}
const score = Math.max(
matchScore(song.name, queryText),
matchScoreSongArtists(song.artist, queryText),
matchScore(album.name, queryText),
matchScore(albumArtist.name, queryText)
matchScore(song.name, queryText, terms),
matchScoreSongArtists(song.artist, queryText, terms),
matchScore(album.name, queryText, terms),
matchScore(albumArtist.name, queryText, terms)
)
if (score === 0) {
return []
+13 -13
View File
@@ -62,10 +62,10 @@ export async function deleteSongLyrics(ctx: MutationCtx, songId: Id<"songs">) {
}
/**
* Songs with a lyrics line matching `query` (see `matchLyrics`), with that
* line. Lines holding the query as typed come first, then the search index's
* relevance order. The index matches words anywhere in the lyrics, so its
* results are checked line by line.
* Up to `limit` songs with a lyrics line matching `query` (see `matchLyrics`),
* with that line, best matches first. The search index matches any word
* anywhere in the lyrics and ranks common words poorly, so its whole page is
* checked line by line before trimming.
*/
export async function searchSongLyrics(
ctx: QueryCtx,
@@ -77,15 +77,15 @@ export async function searchSongLyrics(
const rows = await ctx.db
.query("lyricsSearch")
.withSearchIndex("search_plain", (q) => q.search("plain", text))
.take(limit)
const matches = rows.flatMap((row) => {
const match = matchLyrics(row.plain, text)
return match ? [{ song: row.song, ...match }] : []
})
return [
...matches.filter((match) => match.exact),
...matches.filter((match) => !match.exact),
].map(({ song, snippet }) => ({ song, snippet }))
.take(MAX_LYRICS_MATCHES)
return rows
.flatMap((row) => {
const match = matchLyrics(row.plain, text)
return match ? [{ song: row.song, ...match }] : []
})
.sort((a, b) => b.score - a.score)
.slice(0, limit)
.map(({ song, snippet }) => ({ song, snippet }))
}
/** The song's lyrics tag (see `client/lyrics.ts`), or null without lyrics. */
+10 -3
View File
@@ -2,6 +2,7 @@ import type { PlaybackSource, PlaybackStreamPlan } from "./playback-stream"
/** Qualities a listener can pick when downloading, lowest first. */
export const DOWNLOAD_QUALITIES = [
"low",
"medium",
"high",
"lossless",
@@ -11,6 +12,7 @@ export const DOWNLOAD_QUALITIES = [
export type DownloadQuality = (typeof DOWNLOAD_QUALITIES)[number]
export const DOWNLOAD_QUALITY_LABELS: Record<DownloadQuality, string> = {
low: "Low",
medium: "Medium",
high: "High",
lossless: "Lossless",
@@ -18,12 +20,14 @@ export const DOWNLOAD_QUALITY_LABELS: Record<DownloadQuality, string> = {
}
export const DOWNLOAD_QUALITY_DETAILS: Record<DownloadQuality, string> = {
low: "AAC 64 kbps",
medium: "AAC 128 kbps",
high: "AAC 256 kbps",
lossless: "ALAC or FLAC",
atmos: "Spatial audio",
}
const LOW_KBPS = 64
const MEDIUM_KBPS = 128
const HIGH_KBPS = 256
@@ -54,13 +58,14 @@ function highPlan(files: Record<string, unknown>): DownloadPlan {
/**
* Picks the file for one song. Lossless and Dolby Atmos fall back to High when
* the song lacks them, and Medium is always transcoded.
* the song lacks them, and Low and Medium are always transcoded.
*/
export function downloadPlan(
files: Record<string, unknown>,
quality: DownloadQuality
): DownloadPlan {
switch (quality) {
case "low":
case "medium":
return {
quality,
@@ -70,7 +75,7 @@ export function downloadPlan(
: "normal" in files
? "normal"
: "atmos",
kbps: MEDIUM_KBPS,
kbps: quality === "low" ? LOW_KBPS : MEDIUM_KBPS,
}
case "high":
return highPlan(files)
@@ -84,7 +89,7 @@ export function downloadPlan(
/**
* The download quality holding the same audio a stream plan plays, so a
* download can stand in for streaming. Low has no download equivalent.
* download can stand in for streaming.
*/
export function streamDownloadQuality(
plan: PlaybackStreamPlan
@@ -95,6 +100,7 @@ export function streamDownloadQuality(
}
if (plan.kbps === HIGH_KBPS) return "high"
if (plan.kbps === MEDIUM_KBPS) return "medium"
if (plan.kbps === LOW_KBPS) return "low"
return undefined
}
@@ -129,6 +135,7 @@ export function downloadOptions(
).length
if (
fallbackCount === songs.length &&
quality !== "low" &&
quality !== "medium" &&
quality !== "high"
) {
+43
View File
@@ -279,6 +279,9 @@ importers:
'@react-native-community/slider':
specifier: 5.2.1
version: 5.2.1(patch_hash=73deacaea9aae000a42050d343517da9e16e736e92a4fff3f61f81dba093a1c4)
'@react-native-masked-view/masked-view':
specifier: 0.3.2
version: 0.3.2(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)
'@react-native/metro-config':
specifier: 0.88.0
version: 0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)
@@ -363,12 +366,18 @@ importers:
react-native:
specifier: 0.88.0
version: 0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1)
react-native-continued-task:
specifier: 0.1.0
version: 0.1.0(react-native-nitro-modules@0.37.2(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)
react-native-gesture-handler:
specifier: ~3.3.0
version: 3.3.0(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)
react-native-image-colors:
specifier: ^2.6.0
version: 2.6.0(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)(supports-color@8.1.1)
react-native-nitro-modules:
specifier: 0.37.2
version: 0.37.2(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)
react-native-reanimated:
specifier: 4.7.1
version: 4.7.1(patch_hash=badfed6babfff7fa495b3a06ba8f324be0e5ff82cedb6084f9f4d1dad65984d3)(react-native-worklets@0.13.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)(supports-color@8.1.1))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)
@@ -5438,6 +5447,9 @@ packages:
sass:
optional: true
nitro-core@0.37.2:
resolution: {integrity: sha512-dhagikz9VXXzfidRH/vPNJfYWPmTBArDOo9wE/wEqeERU9C8uRWz9YccOyNUOvADccPAZq319yzhDMoJ9excSQ==}
node-exports-info@1.6.2:
resolution: {integrity: sha512-kXs9Go0cah0qHVV2v389IXQLdLCeE1xfFtjOAF+iobu0OIoG1pje8At2vMHyaPMiPMnG/LWP50twML21eMcAag==}
engines: {node: '>= 0.4'}
@@ -5889,6 +5901,16 @@ packages:
react-is@19.2.7:
resolution: {integrity: sha512-kZFnouyVv7eP/Phmrlo9FK+zcAdriZJvzxXHF1Sl1P377WSGe2G/JxVolhTrB/jeV47lKImhNUsijjHAAbcl/A==}
react-native-continued-task@0.1.0:
resolution: {integrity: sha512-6x9YesK++u6vraaReebWEKbcDjMeRInsQzd+uWXAbNiXasgZ2zulTextzK/zBZ2mBrCZqTZVK60eoPp07BF0MA==}
peerDependencies:
react: '*'
react-native: '*'
react-native-nitro-modules: '*'
peerDependenciesMeta:
react-native-nitro-modules:
optional: true
react-native-drawer-layout@4.2.12:
resolution: {integrity: sha512-qYmntEctkMSodN7pnC2llV21nswImLFPHJeT3PJXSJqZdU4jzDATR8iVi66sXkrtoOLJ2+EvXxgd7sMMpV4ViA==}
peerDependencies:
@@ -5916,6 +5938,12 @@ packages:
react: '*'
react-native: '*'
react-native-nitro-modules@0.37.2:
resolution: {integrity: sha512-Odnrq/p6/q0R01qZlkqeXu9VHHMuGEnZZmyxMvehEu6QiACNHhBCmAHgyBDqOSo9Lb3G0TscFAT+HG0uxsR/GA==}
peerDependencies:
react: '*'
react-native: '*'
react-native-reanimated@4.7.1:
resolution: {integrity: sha512-HviDFSZ6V4KTRsrLS6hRbBJ4j63l/L8a5az0EoWdJwaMLYnBNyYISTDxwXpEYkMbAbLzCMCviIdiOxXHYQWcNA==}
peerDependencies:
@@ -12473,6 +12501,8 @@ snapshots:
- '@types/node'
- babel-plugin-macros
nitro-core@0.37.2: {}
node-exports-info@1.6.2:
dependencies:
array.prototype.flatmap: 1.3.3
@@ -12936,6 +12966,13 @@ snapshots:
react-is@19.2.7: {}
react-native-continued-task@0.1.0(react-native-nitro-modules@0.37.2(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0):
dependencies:
react: 19.3.0
react-native: 0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1)
optionalDependencies:
react-native-nitro-modules: 0.37.2(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)
react-native-drawer-layout@4.2.12(309f9235979e0472ca5a2d24f8d225b6):
dependencies:
color: 4.2.3
@@ -12967,6 +13004,12 @@ snapshots:
react: 19.3.0
react-native: 0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1)
react-native-nitro-modules@0.37.2(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0):
dependencies:
nitro-core: 0.37.2
react: 19.3.0
react-native: 0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1)
react-native-reanimated@4.7.1(patch_hash=badfed6babfff7fa495b3a06ba8f324be0e5ff82cedb6084f9f4d1dad65984d3)(react-native-worklets@0.13.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)(supports-color@8.1.1))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0):
dependencies:
react: 19.3.0