Compare commits

...
42 changed files with 693 additions and 582 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, # 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 # 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 \ RUN ./configure \
--prefix=/opt/ffmpeg \ --prefix=/opt/ffmpeg \
--disable-shared \ --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-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-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-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-parser=aac,aac_latm,ac3,flac,mpegaudio,opus,vorbis \
--enable-bsf=aac_adtstoasc \ --enable-bsf=aac_adtstoasc \
--enable-filter=aresample,aformat \ --enable-filter=aresample,aformat \
@@ -1,11 +1,8 @@
import { Stack } from "expo-router" import { Stack } from "expo-router"
import { TabStackContext } from "@/lib/app-navigation"
import { renderTabScreenContent } from "@/components/tab-screen-content" import { renderTabScreenContent } from "@/components/tab-screen-content"
import { import { useStackScreenOptions, tabStackScreenTitles } from "@/lib/navigation"
inlineTitleOptions,
tabStackScreenTitles,
useStackScreenOptions,
} from "@/lib/navigation"
import { tabletSections, TabletSectionContext } from "@/lib/tablet-navigation" import { tabletSections, TabletSectionContext } from "@/lib/tablet-navigation"
export default function TabletSectionLayout({ segment }: { segment: string }) { export default function TabletSectionLayout({ segment }: { segment: string }) {
@@ -14,17 +11,18 @@ export default function TabletSectionLayout({ segment }: { segment: string }) {
return ( return (
<TabletSectionContext value={section}> <TabletSectionContext value={section}>
<Stack <TabStackContext value={section?.group}>
screenLayout={renderTabScreenContent} <Stack
screenOptions={({ route }) => ({ screenLayout={renderTabScreenContent}
...options, screenOptions={({ route }) => ({
...inlineTitleOptions, ...options,
title: title:
route.name === "index" route.name === "index"
? section?.title ? section?.title
: tabStackScreenTitles[route.name], : tabStackScreenTitles[route.name],
})} })}
/> />
</TabStackContext>
</TabletSectionContext> </TabletSectionContext>
) )
} }
+23 -25
View File
@@ -1,12 +1,9 @@
import { renderTabScreenContent } from "@/components/tab-screen-content" import { renderTabScreenContent } from "@/components/tab-screen-content"
import { Stack } from "expo-router" import { Stack } from "expo-router"
import { TabStackContext } from "@/lib/app-navigation"
import { ProfileHeaderButton } from "@/components/profile-header-button" import { ProfileHeaderButton } from "@/components/profile-header-button"
import { import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
inlineTitleOptions,
tabStackScreenTitles,
useStackScreenOptions,
} from "@/lib/navigation"
export const unstable_settings = { export const unstable_settings = {
anchor: "index", anchor: "index",
@@ -16,25 +13,26 @@ export default function HomeLayout() {
const baseOptions = useStackScreenOptions({ title: "Home" }) const baseOptions = useStackScreenOptions({ title: "Home" })
return ( return (
<Stack <TabStackContext value="home">
screenLayout={renderTabScreenContent} <Stack
screenOptions={({ route }) => ({ screenLayout={renderTabScreenContent}
...baseOptions, screenOptions={({ route }) => ({
...inlineTitleOptions, ...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Home", title: tabStackScreenTitles[route.name] ?? "Home",
headerRight: headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined, route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems: unstable_headerRightItems:
route.name === "index" route.name === "index"
? () => [ ? () => [
{ {
type: "custom", type: "custom",
element: <ProfileHeaderButton />, element: <ProfileHeaderButton />,
hidesSharedBackground: true, hidesSharedBackground: true,
}, },
] ]
: undefined, : undefined,
})} })}
/> />
</TabStackContext>
) )
} }
@@ -53,7 +53,7 @@ export default function AlbumsScreen() {
return ( return (
<> <>
{searchBar} {searchBar}
<MediaGridSkeleton title="Albums" /> <MediaGridSkeleton />
</> </>
) )
} }
@@ -63,7 +63,6 @@ export default function AlbumsScreen() {
{searchBar} {searchBar}
<MediaGridList <MediaGridList
title="Albums"
content={albums} content={albums}
paddingBottom={contentBottomInset} paddingBottom={contentBottomInset}
onEndReached={() => { onEndReached={() => {
@@ -2,13 +2,12 @@ import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router" import { Stack } from "expo-router"
import { memo, useCallback } from "react" import { memo, useCallback } from "react"
import { import {
type FlatList, FlatList,
Pressable, Pressable,
StyleSheet, StyleSheet,
Text, Text,
type ListRenderItemInfo, type ListRenderItemInfo,
} from "react-native" } from "react-native"
import Animated from "react-native-reanimated"
import { import {
MediaContextMenu, MediaContextMenu,
@@ -16,7 +15,6 @@ import {
} from "@/components/media-context-menu" } from "@/components/media-context-menu"
import { CoverImage } from "@/components/cover-image" import { CoverImage } from "@/components/cover-image"
import { ArtistListSkeleton } from "@/components/skeletons" import { ArtistListSkeleton } from "@/components/skeletons"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { contentBottomInset } from "@/components/player" import { contentBottomInset } from "@/components/player"
import { useServerConfig } from "@/contexts/server-config" import { useServerConfig } from "@/contexts/server-config"
import { import {
@@ -35,7 +33,6 @@ import { spacing, useThemeColors } from "@/lib/theme"
const PAGE_SIZE = 50 const PAGE_SIZE = 50
export default function ArtistsScreen() { export default function ArtistsScreen() {
const { ref, scrollY } = useScreenTitleScroll<FlatList<BrowseArtist>>()
const { push } = useAppNavigation() const { push } = useAppNavigation()
const colors = useThemeColors() const colors = useThemeColors()
const { config } = useServerConfig() const { config } = useServerConfig()
@@ -97,7 +94,7 @@ export default function ArtistsScreen() {
return ( return (
<> <>
{searchBar} {searchBar}
<ArtistListSkeleton title="Artists" /> <ArtistListSkeleton />
</> </>
) )
} }
@@ -106,11 +103,8 @@ export default function ArtistsScreen() {
<> <>
{searchBar} {searchBar}
<Animated.FlatList <FlatList
{...longListProps} {...longListProps}
ref={ref}
scrollEventThrottle={16}
ListHeaderComponent={<ScreenTitle title="Artists" scrollY={scrollY} />}
data={artists} data={artists}
keyExtractor={artistKey} keyExtractor={artistKey}
renderItem={renderItem} renderItem={renderItem}
@@ -1,4 +1,3 @@
import { useContext } from "react"
import { Pressable } from "react-native" import { Pressable } from "react-native"
import { MediaGridList } from "@/components/media-cards" import { MediaGridList } from "@/components/media-cards"
@@ -11,20 +10,19 @@ import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router" import { Stack } from "expo-router"
import { SymbolView } from "expo-symbols" import { SymbolView } from "expo-symbols"
import { useAddToPlaylist } from "@/contexts/add-to-playlist" import { useAddToPlaylist } from "@/contexts/add-to-playlist"
import { TabletSectionContext } from "@/lib/tablet-navigation"
export default function PlaylistsTabScreen() { export default function PlaylistsTabScreen() {
const colors = useThemeColors() const colors = useThemeColors()
const playlists = useCachedQuery(api.playlists.listAllPlaylists) const playlists = useCachedQuery(api.playlists.listAllPlaylists)
const { openCreatePlaylist } = useAddToPlaylist() const { openCreatePlaylist } = useAddToPlaylist()
const title = useContext(TabletSectionContext)?.title ?? "Playlists"
if (playlists === undefined) { if (playlists === undefined) {
return ( return (
<> <>
<Stack.Screen <Stack.Screen
options={{ options={{
title, title: "Playlists",
headerLargeTitle: true,
headerRight: () => ( headerRight: () => (
<Pressable <Pressable
onPress={openCreatePlaylist} onPress={openCreatePlaylist}
@@ -40,7 +38,7 @@ export default function PlaylistsTabScreen() {
), ),
}} }}
/> />
<MediaGridSkeleton title={title} /> <MediaGridSkeleton />
</> </>
) )
} }
@@ -49,7 +47,8 @@ export default function PlaylistsTabScreen() {
<> <>
<Stack.Screen <Stack.Screen
options={{ options={{
title, title: "Playlists",
headerLargeTitle: true,
headerRight: () => ( headerRight: () => (
<Pressable <Pressable
onPress={openCreatePlaylist} onPress={openCreatePlaylist}
@@ -62,7 +61,6 @@ export default function PlaylistsTabScreen() {
}} }}
/> />
<MediaGridList <MediaGridList
title={title}
content={playlists} content={playlists}
paddingBottom={tabContentBottomInset} paddingBottom={tabContentBottomInset}
/> />
@@ -1,16 +1,10 @@
import { Stack } from "expo-router" import { Stack } from "expo-router"
import { useCallback, useState } from "react" import { useCallback, useState } from "react"
import { import { FlatList, StyleSheet, type ListRenderItemInfo } from "react-native"
type FlatList,
StyleSheet,
type ListRenderItemInfo,
} from "react-native"
import Animated from "react-native-reanimated"
import type { MediaAction } from "@/components/media-context-menu" import type { MediaAction } from "@/components/media-context-menu"
import { contentBottomInset, SongListRow } from "@/components/player" import { contentBottomInset, SongListRow } from "@/components/player"
import { SongListSkeleton } from "@/components/skeletons" import { SongListSkeleton } from "@/components/skeletons"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { useFavorites } from "@/contexts/favorites" import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback" import { usePlaybackActions } from "@/contexts/playback"
import { import {
@@ -26,7 +20,6 @@ import { longListProps } from "@/lib/list"
const PAGE_SIZE = 50 const PAGE_SIZE = 50
export default function SongsScreen() { export default function SongsScreen() {
const { ref, scrollY } = useScreenTitleScroll<FlatList<BrowseSong>>()
const { playFromLibrarySong } = usePlaybackActions() const { playFromLibrarySong } = usePlaybackActions()
const { isSongFavorite } = useFavorites() const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions() const { handleSongAction } = useMediaMenuActions()
@@ -94,7 +87,7 @@ export default function SongsScreen() {
return ( return (
<> <>
{searchBar} {searchBar}
<SongListSkeleton title="Songs" /> <SongListSkeleton />
</> </>
) )
} }
@@ -103,11 +96,8 @@ export default function SongsScreen() {
<> <>
{searchBar} {searchBar}
<Animated.FlatList <FlatList
{...longListProps} {...longListProps}
ref={ref}
scrollEventThrottle={16}
ListHeaderComponent={<ScreenTitle title="Songs" scrollY={scrollY} />}
data={songs} data={songs}
keyExtractor={songKey} keyExtractor={songKey}
renderItem={renderItem} renderItem={renderItem}
@@ -1,6 +1,6 @@
import { useMemo } from "react" import { useMemo } from "react"
import { import {
type FlatList, FlatList,
Pressable, Pressable,
StyleSheet, StyleSheet,
Text, Text,
@@ -8,10 +8,8 @@ import {
type ListRenderItemInfo, type ListRenderItemInfo,
} from "react-native" } from "react-native"
import { Stack } from "expo-router" import { Stack } from "expo-router"
import Animated from "react-native-reanimated"
import { CoverImage } from "@/components/cover-image" import { CoverImage } from "@/components/cover-image"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { tabContentBottomInset } from "@/components/player" import { tabContentBottomInset } from "@/components/player"
import { import {
FAVORITES_DOWNLOAD_ID, FAVORITES_DOWNLOAD_ID,
@@ -55,7 +53,6 @@ export default function DownloadsScreen() {
const { push } = useAppNavigation() const { push } = useAppNavigation()
const { columns, cardWidth, onLayout, horizontalPadding, gap } = const { columns, cardWidth, onLayout, horizontalPadding, gap } =
useMediaGridLayout() useMediaGridLayout()
const { ref, scrollY } = useScreenTitleScroll<FlatList<Card>>()
const cards = useMemo<Card[]>(() => { const cards = useMemo<Card[]>(() => {
if (!queue) return [] if (!queue) return []
@@ -138,10 +135,8 @@ export default function DownloadsScreen() {
return ( return (
<> <>
<Stack.Screen options={{ title: "Downloads" }} /> <Stack.Screen options={{ title: "Downloads", headerLargeTitle: true }} />
<Animated.FlatList <FlatList
ref={ref}
scrollEventThrottle={16}
key={columns} key={columns}
onLayout={onLayout} onLayout={onLayout}
data={cards} data={cards}
@@ -154,20 +149,13 @@ export default function DownloadsScreen() {
numColumns={columns} numColumns={columns}
style={{ flex: 1, backgroundColor: colors.background }} style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{ contentContainerStyle={{
paddingTop: spacing.lg,
paddingHorizontal: horizontalPadding, paddingHorizontal: horizontalPadding,
paddingBottom: tabContentBottomInset, paddingBottom: tabContentBottomInset,
gap, gap,
}} }}
columnWrapperStyle={columns > 1 ? { gap } : undefined} columnWrapperStyle={columns > 1 ? { gap } : undefined}
contentInsetAdjustmentBehavior="automatic" contentInsetAdjustmentBehavior="automatic"
ListHeaderComponent={
<ScreenTitle
title="Downloads"
scrollY={scrollY}
// The list padding already insets the title.
style={{ paddingHorizontal: 0 }}
/>
}
ListEmptyComponent={ ListEmptyComponent={
<View style={styles.empty}> <View style={styles.empty}>
<Text style={{ color: colors.mutedForeground }}> <Text style={{ color: colors.mutedForeground }}>
@@ -1,17 +1,15 @@
import { useCallback, useMemo } from "react" import { useCallback, useMemo } from "react"
import { import {
type FlatList, FlatList,
Pressable, Pressable,
StyleSheet, StyleSheet,
Text, Text,
View, View,
type ListRenderItemInfo, type ListRenderItemInfo,
} from "react-native" } from "react-native"
import Animated from "react-native-reanimated"
import { Ionicons } from "@expo/vector-icons" import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router" import { Stack } from "expo-router"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { useSwipeRowGroup } from "@/components/ios-swipe-to-remove-row" import { useSwipeRowGroup } from "@/components/ios-swipe-to-remove-row"
import type { MediaAction } from "@/components/media-context-menu" import type { MediaAction } from "@/components/media-context-menu"
import { contentBottomInset, SongListRow } from "@/components/player" import { contentBottomInset, SongListRow } from "@/components/player"
@@ -54,7 +52,6 @@ export default function OtherDownloadsScreen() {
const { isSongFavorite } = useFavorites() const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions() const { handleSongAction } = useMediaMenuActions()
const swipeGroup = useSwipeRowGroup() const swipeGroup = useSwipeRowGroup()
const { ref, scrollY } = useScreenTitleScroll<FlatList<BrowseSong>>()
const handlePlaySong = useCallback( const handlePlaySong = useCallback(
(song: BrowseSong) => void playFromSong(song.id, playableIds, PLAY_ORIGIN), (song: BrowseSong) => void playFromSong(song.id, playableIds, PLAY_ORIGIN),
@@ -93,11 +90,11 @@ export default function OtherDownloadsScreen() {
return ( return (
<> <>
<Stack.Screen options={{ title: OTHER_DOWNLOADS_TITLE }} /> <Stack.Screen
<Animated.FlatList options={{ title: OTHER_DOWNLOADS_TITLE, headerLargeTitle: false }}
/>
<FlatList
{...longListProps} {...longListProps}
ref={ref}
scrollEventThrottle={16}
data={songs} data={songs}
keyExtractor={(song) => song.id} keyExtractor={(song) => song.id}
renderItem={renderItem} renderItem={renderItem}
@@ -106,32 +103,25 @@ export default function OtherDownloadsScreen() {
contentInsetAdjustmentBehavior="automatic" contentInsetAdjustmentBehavior="automatic"
onScrollBeginDrag={swipeGroup.closeOpenRow} onScrollBeginDrag={swipeGroup.closeOpenRow}
ListHeaderComponent={ ListHeaderComponent={
<> songs.length > 0 ? (
<ScreenTitle title={OTHER_DOWNLOADS_TITLE} scrollY={scrollY} /> <View style={styles.actions}>
{songs.length > 0 ? ( <Pressable
<View style={styles.actions}> accessibilityRole="button"
<Button accessibilityLabel="Shuffle"
title="Play" hitSlop={8}
icon="play" onPress={() => void playShuffled(playableIds, PLAY_ORIGIN)}
onPress={() => void playInOrder(playableIds, PLAY_ORIGIN)} style={[styles.iconAction, { backgroundColor: colors.muted }]}
style={styles.play} >
/> <Ionicons name="shuffle" size={24} color={colors.foreground} />
<Pressable </Pressable>
accessibilityRole="button" <Button
accessibilityLabel="Shuffle" title="Play"
hitSlop={8} icon="play"
onPress={() => void playShuffled(playableIds, PLAY_ORIGIN)} onPress={() => void playInOrder(playableIds, PLAY_ORIGIN)}
style={[styles.shuffle, { backgroundColor: colors.card }]} style={styles.playButton}
> />
<Ionicons </View>
name="shuffle" ) : undefined
size={24}
color={colors.foreground}
/>
</Pressable>
</View>
) : null}
</>
} }
ListEmptyComponent={ ListEmptyComponent={
<Text style={[styles.empty, { color: colors.mutedForeground }]}> <Text style={[styles.empty, { color: colors.mutedForeground }]}>
@@ -147,14 +137,15 @@ const styles = StyleSheet.create({
actions: { actions: {
flexDirection: "row", flexDirection: "row",
alignItems: "center", alignItems: "center",
justifyContent: "center",
gap: spacing.sm, gap: spacing.sm,
padding: spacing.lg, padding: spacing.lg,
}, },
play: { flex: 1 }, playButton: { borderRadius: 999, minWidth: 160 },
shuffle: { iconAction: {
width: 48, width: 44,
height: 48, height: 44,
borderRadius: 24, borderRadius: 22,
alignItems: "center", alignItems: "center",
justifyContent: "center", justifyContent: "center",
}, },
+4 -16
View File
@@ -1,10 +1,8 @@
import { memo } from "react" import { memo } from "react"
import { type ScrollViewInstance, StyleSheet } from "react-native" import { ScrollView, StyleSheet } from "react-native"
import Animated from "react-native-reanimated"
import { ContentCarousel } from "@/components/media-cards" import { ContentCarousel } from "@/components/media-cards"
import { HomeSkeleton } from "@/components/skeletons" import { HomeSkeleton } from "@/components/skeletons"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { tabContentBottomInset } from "@/components/player" import { tabContentBottomInset } from "@/components/player"
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query" import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
@@ -40,7 +38,6 @@ const HomeCarousels = memo(function HomeCarousels({
export default function HomeScreen() { export default function HomeScreen() {
const colors = useThemeColors() const colors = useThemeColors()
const { ref, scrollY } = useScreenTitleScroll<ScrollViewInstance>()
const recentlyAdded = useCachedPaginatedQuery( const recentlyAdded = useCachedPaginatedQuery(
api.library.browseRecentlyAddedPaginated, api.library.browseRecentlyAddedPaginated,
{}, {},
@@ -56,16 +53,14 @@ export default function HomeScreen() {
(result) => result.status === "LoadingFirstPage" && !result.isCached (result) => result.status === "LoadingFirstPage" && !result.isCached
) )
if (isLoading) { if (isLoading) {
return <HomeSkeleton title="Home" /> return <HomeSkeleton />
} }
const added = recentlyAdded.results.slice(0, CAROUSEL_ITEM_LIMIT) const added = recentlyAdded.results.slice(0, CAROUSEL_ITEM_LIMIT)
const played = recentlyPlayed.results.slice(0, CAROUSEL_ITEM_LIMIT) const played = recentlyPlayed.results.slice(0, CAROUSEL_ITEM_LIMIT)
return ( return (
<Animated.ScrollView <ScrollView
ref={ref}
scrollEventThrottle={16}
style={{ flex: 1, backgroundColor: colors.background }} style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={[ contentContainerStyle={[
styles.content, styles.content,
@@ -73,9 +68,8 @@ export default function HomeScreen() {
]} ]}
contentInsetAdjustmentBehavior="automatic" contentInsetAdjustmentBehavior="automatic"
> >
<ScreenTitle title="Home" scrollY={scrollY} style={styles.title} />
<HomeCarousels recentlyAdded={added} recentlyPlayed={played} /> <HomeCarousels recentlyAdded={added} recentlyPlayed={played} />
</Animated.ScrollView> </ScrollView>
) )
} }
@@ -84,10 +78,4 @@ const styles = StyleSheet.create({
padding: spacing.lg, padding: spacing.lg,
gap: spacing.xl, 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) { if (status === "LoadingFirstPage" && !isCached) {
return <MediaGridSkeleton title="Recently Added" /> return <MediaGridSkeleton />
} }
return ( return (
<MediaGridList <MediaGridList
title="Recently Added"
content={results} content={results}
paddingBottom={contentBottomInset} paddingBottom={contentBottomInset}
onEndReached={() => { onEndReached={() => {
@@ -14,12 +14,11 @@ export default function RecentlyPlayedScreen() {
) )
if (status === "LoadingFirstPage" && !isCached) { if (status === "LoadingFirstPage" && !isCached) {
return <MediaGridSkeleton title="Recently Played" /> return <MediaGridSkeleton />
} }
return ( return (
<MediaGridList <MediaGridList
title="Recently Played"
content={results} content={results}
paddingBottom={contentBottomInset} paddingBottom={contentBottomInset}
onEndReached={() => { onEndReached={() => {
@@ -2,12 +2,9 @@ import { useTabletLayout } from "@/hooks/use-tablet-layout"
import { renderTabScreenContent } from "@/components/tab-screen-content" import { renderTabScreenContent } from "@/components/tab-screen-content"
import { Stack } from "expo-router" import { Stack } from "expo-router"
import { TabStackContext } from "@/lib/app-navigation"
import { ProfileHeaderButton } from "@/components/profile-header-button" import { ProfileHeaderButton } from "@/components/profile-header-button"
import { import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
inlineTitleOptions,
tabStackScreenTitles,
useStackScreenOptions,
} from "@/lib/navigation"
export const unstable_settings = { export const unstable_settings = {
anchor: "index", anchor: "index",
@@ -18,27 +15,28 @@ export default function LibraryLayout() {
const baseOptions = useStackScreenOptions({ title: "Library" }) const baseOptions = useStackScreenOptions({ title: "Library" })
return ( return (
<Stack <TabStackContext value="library">
screenLayout={renderTabScreenContent} <Stack
screenOptions={({ route }) => ({ screenLayout={renderTabScreenContent}
...baseOptions, screenOptions={({ route }) => ({
...inlineTitleOptions, ...baseOptions,
title: title:
tabStackScreenTitles[route.name] ?? tabStackScreenTitles[route.name] ??
(tabletLayout ? "Recently Added" : "Library"), (tabletLayout ? "Recently Added" : "Library"),
headerRight: headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined, route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems: unstable_headerRightItems:
route.name === "index" route.name === "index"
? () => [ ? () => [
{ {
type: "custom", type: "custom",
element: <ProfileHeaderButton />, element: <ProfileHeaderButton />,
hidesSharedBackground: true, hidesSharedBackground: true,
}, },
] ]
: undefined, : undefined,
})} })}
/> />
</TabStackContext>
) )
} }
@@ -72,7 +72,6 @@ export default function LibraryScreen() {
const { push } = useAppNavigation() const { push } = useAppNavigation()
const isTablet = tabletLayout const isTablet = tabletLayout
const colors = useThemeColors() const colors = useThemeColors()
const title = isTablet ? "Recently Added" : "Library"
const { results, status, loadMore, isCached } = useCachedPaginatedQuery( const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
api.library.browseRecentlyAddedPaginated, api.library.browseRecentlyAddedPaginated,
{}, {},
@@ -125,18 +124,11 @@ export default function LibraryScreen() {
) )
if (status === "LoadingFirstPage" && !isCached) { if (status === "LoadingFirstPage" && !isCached) {
return ( return <MediaGridSkeleton contentInset={false} header={listHeader} />
<MediaGridSkeleton
title={title}
contentInset={false}
header={listHeader}
/>
)
} }
return ( return (
<MediaGridList <MediaGridList
title={title}
content={results} content={results}
paddingBottom={tabContentBottomInset} paddingBottom={tabContentBottomInset}
contentInset={false} contentInset={false}
+23 -25
View File
@@ -1,12 +1,9 @@
import { renderTabScreenContent } from "@/components/tab-screen-content" import { renderTabScreenContent } from "@/components/tab-screen-content"
import { Stack } from "expo-router" import { Stack } from "expo-router"
import { TabStackContext } from "@/lib/app-navigation"
import { ProfileHeaderButton } from "@/components/profile-header-button" import { ProfileHeaderButton } from "@/components/profile-header-button"
import { import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
inlineTitleOptions,
tabStackScreenTitles,
useStackScreenOptions,
} from "@/lib/navigation"
export const unstable_settings = { export const unstable_settings = {
anchor: "index", anchor: "index",
@@ -16,25 +13,26 @@ export default function SearchLayout() {
const baseOptions = useStackScreenOptions({ title: "Search" }) const baseOptions = useStackScreenOptions({ title: "Search" })
return ( return (
<Stack <TabStackContext value="search">
screenLayout={renderTabScreenContent} <Stack
screenOptions={({ route }) => ({ screenLayout={renderTabScreenContent}
...baseOptions, screenOptions={({ route }) => ({
...inlineTitleOptions, ...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Search", title: tabStackScreenTitles[route.name] ?? "Search",
headerRight: headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined, route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems: unstable_headerRightItems:
route.name === "index" route.name === "index"
? () => [ ? () => [
{ {
type: "custom", type: "custom",
element: <ProfileHeaderButton />, element: <ProfileHeaderButton />,
hidesSharedBackground: true, hidesSharedBackground: true,
}, },
] ]
: undefined, : undefined,
})} })}
/> />
</TabStackContext>
) )
} }
@@ -35,7 +35,7 @@ export default function SearchScreen() {
: {})} : {})}
/> />
<SearchResults searchQuery={searchQuery} title="Search" /> <SearchResults searchQuery={searchQuery} />
</> </>
) )
} }
+12 -7
View File
@@ -12,6 +12,7 @@ import Animated, {
Easing, Easing,
useAnimatedStyle, useAnimatedStyle,
useSharedValue, useSharedValue,
withSequence,
withTiming, withTiming,
type SharedValue, type SharedValue,
} from "react-native-reanimated" } from "react-native-reanimated"
@@ -284,13 +285,17 @@ function FilledWords({
useEffect(() => { useEffect(() => {
cancelAnimation(sung) cancelAnimation(sung)
sung.value = time // Jump to the reported time first, so the wipe never runs from a stale one.
if (isPlaying && end > time) { sung.value =
sung.value = withTiming(end, { isPlaying && end > time
duration: (end - time) * 1000, ? withSequence(
easing: Easing.linear, withTiming(time, { duration: 0 }),
}) withTiming(end, {
} duration: (end - time) * 1000,
easing: Easing.linear,
})
)
: time
}, [sung, time, isPlaying, end]) }, [sung, time, isPlaying, end])
return ( return (
+2 -25
View File
@@ -4,7 +4,6 @@ import { tabletLayoutTransition } from "@/lib/tablet-motion"
import { TabletMediaGrid } from "@/components/tablet-media-grid" import { TabletMediaGrid } from "@/components/tablet-media-grid"
import { useMediaGridLayout } from "@/hooks/use-media-grid-layout" import { useMediaGridLayout } from "@/hooks/use-media-grid-layout"
import { MusicEntityView } from "@/components/music-entity-view" import { MusicEntityView } from "@/components/music-entity-view"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { Link } from "expo-router" import { Link } from "expo-router"
import { Ionicons } from "@expo/vector-icons" import { Ionicons } from "@expo/vector-icons"
import { memo, useCallback, type ReactElement } from "react" import { memo, useCallback, type ReactElement } from "react"
@@ -301,21 +300,17 @@ export function MediaGridList({
onEndReached, onEndReached,
ListHeaderComponent, ListHeaderComponent,
contentInset = true, contentInset = true,
title,
}: { }: {
content: MediaItem[] content: MediaItem[]
paddingBottom: number paddingBottom: number
onEndReached?: () => void onEndReached?: () => void
ListHeaderComponent?: ReactElement ListHeaderComponent?: ReactElement
contentInset?: boolean contentInset?: boolean
/** iOS `ScreenTitle` shown above the grid; it replaces the top inset. */
title?: string
}) { }) {
const tabletLayout = useTabletLayout() const tabletLayout = useTabletLayout()
const { columns, cardWidth, onLayout, horizontalPadding, gap } = const { columns, cardWidth, onLayout, horizontalPadding, gap } =
useMediaGridLayout() useMediaGridLayout()
const colors = useThemeColors() const colors = useThemeColors()
const { ref, scrollY } = useScreenTitleScroll<FlatList<MediaItem>>()
const renderItem = useCallback( const renderItem = useCallback(
({ item }: ListRenderItemInfo<MediaItem>) => ( ({ item }: ListRenderItemInfo<MediaItem>) => (
<View style={{ width: cardWidth }}> <View style={{ width: cardWidth }}>
@@ -333,30 +328,13 @@ export function MediaGridList({
onEndReached={onEndReached} onEndReached={onEndReached}
ListHeaderComponent={ListHeaderComponent} ListHeaderComponent={ListHeaderComponent}
contentInset={contentInset} contentInset={contentInset}
title={title}
renderCard={renderTabletCard} 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 ( return (
<Animated.FlatList <FlatList
ref={ref}
scrollEventThrottle={16}
key={columns} key={columns}
onLayout={onLayout} onLayout={onLayout}
data={content} data={content}
@@ -373,7 +351,6 @@ export function MediaGridList({
paddingBottom, paddingBottom,
gap, gap,
...(contentInset ? { paddingHorizontal: horizontalPadding } : {}), ...(contentInset ? { paddingHorizontal: horizontalPadding } : {}),
...(title ? { paddingTop: 0 } : {}),
}, },
]} ]}
columnWrapperStyle={[ columnWrapperStyle={[
@@ -382,7 +359,7 @@ export function MediaGridList({
{ gap }, { gap },
]} ]}
contentInsetAdjustmentBehavior="automatic" contentInsetAdjustmentBehavior="automatic"
ListHeaderComponent={header} ListHeaderComponent={ListHeaderComponent}
onEndReached={onEndReached} onEndReached={onEndReached}
onEndReachedThreshold={0.5} onEndReachedThreshold={0.5}
/> />
-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 { memo, useCallback, useMemo } from "react"
import { import {
type FlatList, FlatList,
StyleSheet, StyleSheet,
Text, Text,
View, View,
type ListRenderItemInfo, type ListRenderItemInfo,
} from "react-native" } from "react-native"
import Animated from "react-native-reanimated"
import { ContentCarousel } from "@/components/media-cards" import { ContentCarousel } from "@/components/media-cards"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import type { MediaAction } from "@/components/media-context-menu" import type { MediaAction } from "@/components/media-context-menu"
import { tabContentBottomInset, SongListRow } from "@/components/player" import { tabContentBottomInset, SongListRow } from "@/components/player"
import { SongListSkeleton } from "@/components/skeletons" 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 type { BrowseSong, SearchSong } from "@otunes/convex/types"
import { spacing, useThemeColors } from "@/lib/theme" import { spacing, useThemeColors } from "@/lib/theme"
function SearchResultsBody({ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
searchQuery,
title,
}: {
searchQuery: string
/** iOS `ScreenTitle`, shown above the results and while idle. */
title: string
}) {
const colors = useThemeColors() const colors = useThemeColors()
const { ref, scrollY } = useScreenTitleScroll<FlatList<BrowseSong>>()
const { playFromSong } = usePlaybackActions() const { playFromSong } = usePlaybackActions()
const { isSongFavorite } = useFavorites() const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions() const { handleSongAction } = useMediaMenuActions()
@@ -86,14 +76,16 @@ function SearchResultsBody({
) )
if (isSearching) { if (isSearching) {
return <SongListSkeleton title={title} /> return <SongListSkeleton />
}
if (!hasQuery) {
return <></>
} }
return ( return (
<Animated.FlatList <FlatList
ref={ref} data={results?.songs ?? []}
scrollEventThrottle={16}
data={hasQuery ? (results?.songs ?? []) : []}
keyExtractor={(song) => song.id} keyExtractor={(song) => song.id}
style={{ flex: 1, backgroundColor: colors.background }} style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{ paddingBottom: tabContentBottomInset }} contentContainerStyle={{ paddingBottom: tabContentBottomInset }}
@@ -101,8 +93,7 @@ function SearchResultsBody({
keyboardShouldPersistTaps="handled" keyboardShouldPersistTaps="handled"
ListHeaderComponent={ ListHeaderComponent={
<> <>
<ScreenTitle title={title} scrollY={scrollY} /> {!hasResults ? (
{hasQuery && !hasResults ? (
<View style={styles.empty}> <View style={styles.empty}>
<Text <Text
style={[styles.emptyText, { color: colors.mutedForeground }]} style={[styles.emptyText, { color: colors.mutedForeground }]}
@@ -112,13 +103,13 @@ function SearchResultsBody({
</View> </View>
) : null} ) : null}
{hasQuery && results?.artists.length ? ( {results?.artists.length ? (
<View style={styles.section}> <View style={styles.section}>
<ContentCarousel title="Artists" content={results.artists} /> <ContentCarousel title="Artists" content={results.artists} />
</View> </View>
) : null} ) : null}
{hasQuery && results?.albums.length ? ( {results?.albums.length ? (
<View style={styles.section}> <View style={styles.section}>
<ContentCarousel title="Albums" content={results.albums} /> <ContentCarousel title="Albums" content={results.albums} />
</View> </View>
@@ -127,7 +118,7 @@ function SearchResultsBody({
} }
renderItem={renderItem} renderItem={renderItem}
ListFooterComponent={ ListFooterComponent={
hasQuery && playlistResults && playlistResults.length > 0 ? ( playlistResults && playlistResults.length > 0 ? (
<View style={styles.section}> <View style={styles.section}>
<ContentCarousel title="Playlists" content={playlistResults} /> <ContentCarousel title="Playlists" content={playlistResults} />
</View> </View>
+5 -49
View File
@@ -9,7 +9,6 @@ import {
collectionInset, collectionInset,
} from "@/components/collection-list" } from "@/components/collection-list"
import { tabletCardTextHeight } from "@/components/tablet-media-grid" import { tabletCardTextHeight } from "@/components/tablet-media-grid"
import { ScreenTitle } from "@/components/screen-title"
import { Link } from "expo-router" import { Link } from "expo-router"
import { useHeaderHeight } from "expo-router/react-navigation" import { useHeaderHeight } from "expo-router/react-navigation"
import Reanimated from "react-native-reanimated" import Reanimated from "react-native-reanimated"
@@ -152,16 +151,9 @@ function SongRows({ rows, inset }: { rows: number; inset?: boolean }) {
)) ))
} }
export function SongListSkeleton({ export function SongListSkeleton({ rows = 10 }: { rows?: number }) {
rows = 10,
title,
}: {
rows?: number
title?: string
}) {
return ( return (
<SkeletonScreen> <SkeletonScreen>
{title ? <ScreenTitle title={title} /> : null}
<SongRows rows={rows} /> <SongRows rows={rows} />
</SkeletonScreen> </SkeletonScreen>
) )
@@ -242,45 +234,23 @@ export function MediaGridSkeleton({
items = 6, items = 6,
contentInset = true, contentInset = true,
header, header,
title,
}: { }: {
items?: number items?: number
contentInset?: boolean contentInset?: boolean
/** The loaded list's `ListHeaderComponent`, so it keeps its position. */ /** The loaded list's `ListHeaderComponent`, so it keeps its position. */
header?: ReactNode header?: ReactNode
/** The loaded list's `ScreenTitle`, which replaces its top inset. */
title?: string
}) { }) {
return ( return (
<SkeletonScreen> <SkeletonScreen>
<MediaGridContent <MediaGridContent
items={items} items={items}
contentInset={contentInset && !title} contentInset={contentInset}
header={ header={header}
title ? (
<>
<MediaGridTitle title={title} />
{header}
</>
) : (
header
)
}
/> />
</SkeletonScreen> </SkeletonScreen>
) )
} }
function MediaGridTitle({ title }: { title: string }) {
const { horizontalPadding } = useMediaGridLayout()
return (
<ScreenTitle
title={title}
style={{ paddingHorizontal: horizontalPadding }}
/>
)
}
export function CarouselSkeleton() { export function CarouselSkeleton() {
return ( return (
<View style={styles.carousel}> <View style={styles.carousel}>
@@ -294,11 +264,10 @@ export function CarouselSkeleton() {
) )
} }
export function HomeSkeleton({ title }: { title: string }) { export function HomeSkeleton() {
return ( return (
<SkeletonScreen> <SkeletonScreen>
<View style={styles.home}> <View style={styles.home}>
<ScreenTitle title={title} style={styles.homeTitle} />
<CarouselSkeleton /> <CarouselSkeleton />
<CarouselSkeleton /> <CarouselSkeleton />
</View> </View>
@@ -419,17 +388,10 @@ export function CollectionDetailSkeleton({
) )
} }
export function ArtistListSkeleton({ export function ArtistListSkeleton({ rows = 12 }: { rows?: number }) {
rows = 12,
title,
}: {
rows?: number
title?: string
}) {
const colors = useThemeColors() const colors = useThemeColors()
return ( return (
<SkeletonScreen> <SkeletonScreen>
{title ? <ScreenTitle title={title} /> : null}
{Array.from({ length: rows }, (_, index) => ( {Array.from({ length: rows }, (_, index) => (
<View <View
key={index} key={index}
@@ -494,12 +456,6 @@ const styles = StyleSheet.create({
carousel: { gap: spacing.md, overflow: "hidden" }, carousel: { gap: spacing.md, overflow: "hidden" },
carouselRow: { flexDirection: "row", gap: spacing.md }, carouselRow: { flexDirection: "row", gap: spacing.md },
home: { padding: spacing.lg, gap: spacing.xl }, 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 }, centeredHero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm },
actions: { actions: {
flexDirection: "row", flexDirection: "row",
+5 -20
View File
@@ -6,7 +6,7 @@ import {
type ReactElement, type ReactElement,
} from "react" } from "react"
import { import {
type ScrollViewInstance, ScrollView,
View, View,
type NativeSyntheticEvent, type NativeSyntheticEvent,
type NativeScrollEvent, type NativeScrollEvent,
@@ -15,7 +15,6 @@ import Animated from "react-native-reanimated"
import { useSafeAreaInsets } from "react-native-safe-area-context" import { useSafeAreaInsets } from "react-native-safe-area-context"
import type { MediaItem } from "@/components/media-cards" import type { MediaItem } from "@/components/media-cards"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { useMediaGridLayout } from "@/hooks/use-media-grid-layout" import { useMediaGridLayout } from "@/hooks/use-media-grid-layout"
import { tabletLayoutTransition } from "@/lib/tablet-motion" import { tabletLayoutTransition } from "@/lib/tablet-motion"
import { useThemeColors } from "@/lib/theme" import { useThemeColors } from "@/lib/theme"
@@ -29,8 +28,6 @@ type GridProps = {
onEndReached?: () => void onEndReached?: () => void
ListHeaderComponent?: ReactElement ListHeaderComponent?: ReactElement
contentInset?: boolean contentInset?: boolean
/** iOS `ScreenTitle` shown above the grid; it replaces the top inset. */
title?: string
renderCard: (item: MediaItem, width: number) => ReactElement renderCard: (item: MediaItem, width: number) => ReactElement
} }
@@ -44,12 +41,9 @@ export function TabletMediaGrid({
onEndReached, onEndReached,
ListHeaderComponent, ListHeaderComponent,
contentInset = true, contentInset = true,
title,
renderCard, renderCard,
}: GridProps) { }: GridProps) {
const colors = useThemeColors() const colors = useThemeColors()
const { ref, scrollY: titleScrollY } =
useScreenTitleScroll<ScrollViewInstance>()
const insets = useSafeAreaInsets() const insets = useSafeAreaInsets()
const { columns, cardWidth, onLayout, horizontalPadding, gap, ready } = const { columns, cardWidth, onLayout, horizontalPadding, gap, ready } =
useMediaGridLayout() useMediaGridLayout()
@@ -108,27 +102,18 @@ export function TabletMediaGrid({
setViewportHeight(event.nativeEvent.layout.height) setViewportHeight(event.nativeEvent.layout.height)
}} }}
> >
<Animated.ScrollView <ScrollView
ref={ref}
onScroll={onScroll} onScroll={onScroll}
// Every frame, so the title pins smoothly on pull-down. scrollEventThrottle={32}
scrollEventThrottle={16}
contentInsetAdjustmentBehavior="automatic" contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={{ contentContainerStyle={{
paddingTop: contentInset && !title ? horizontalPadding : 0, paddingTop: contentInset ? horizontalPadding : 0,
paddingBottom: paddingBottom + insets.bottom, paddingBottom: paddingBottom + insets.bottom,
}} }}
> >
<View <View
onLayout={(event) => setHeaderHeight(event.nativeEvent.layout.height)} onLayout={(event) => setHeaderHeight(event.nativeEvent.layout.height)}
> >
{title ? (
<ScreenTitle
title={title}
scrollY={titleScrollY}
style={{ paddingHorizontal: horizontalPadding }}
/>
) : null}
{ListHeaderComponent} {ListHeaderComponent}
</View> </View>
<View style={{ height: gridHeight }}> <View style={{ height: gridHeight }}>
@@ -151,7 +136,7 @@ export function TabletMediaGrid({
) )
})} })}
</View> </View>
</Animated.ScrollView> </ScrollView>
</Animated.View> </Animated.View>
) )
} }
+2 -4
View File
@@ -9,15 +9,13 @@
"APP_VARIANT": "development" "APP_VARIANT": "development"
}, },
"developmentClient": true, "developmentClient": true,
"distribution": "internal", "distribution": "internal"
"credentialsSource": "local"
}, },
"preview": { "preview": {
"env": { "env": {
"APP_VARIANT": "preview" "APP_VARIANT": "preview"
}, },
"distribution": "internal", "distribution": "internal"
"credentialsSource": "local"
}, },
"production": { "production": {
"env": { "env": {
+22 -8
View File
@@ -1,5 +1,5 @@
import { useRouter, useSegments, type Href } from "expo-router" import { useRouter, useSegments, type Href } from "expo-router"
import { useCallback } from "react" import { createContext, use, useCallback } from "react"
import { tabletSections } from "@/lib/tablet-navigation" 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 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 { function getActiveTabFromRef(): AppTab {
return getActiveTab(activeSegmentsRef.current) return getActiveTab(activeSegmentsRef.current)
} }
@@ -41,8 +48,15 @@ export function AppNavigationSync() {
return null return null
} }
/** Tab-aware navigation: paths resolve inside the caller's tab stack, falling back to the active tab outside one. */
export function useAppNavigation() { export function useAppNavigation() {
const router = useRouter() const router = useRouter()
const stackTab = use(TabStackContext)
const currentTab = useCallback(
() => stackTab ?? getActiveTabFromRef(),
[stackTab]
)
const push = useCallback( const push = useCallback(
(path: string) => { (path: string) => {
@@ -53,26 +67,26 @@ export function useAppNavigation() {
return return
} }
router.push(tabPath(getActiveTabFromRef(), path)) router.push(tabPath(currentTab(), path))
}, },
[router] [router, currentTab]
) )
const replace = useCallback( const replace = useCallback(
(path: string) => { (path: string) => {
router.replace(tabPath(getActiveTabFromRef(), path)) router.replace(tabPath(currentTab(), path))
}, },
[router] [router, currentTab]
) )
const href = useCallback( const href = useCallback(
(path: string) => tabPath(getActiveTabFromRef(), path), (path: string) => tabPath(currentTab(), path),
[] [currentTab]
) )
return { return {
get tab() { get tab() {
return getActiveTabFromRef() return currentTab()
}, },
href, href,
push, push,
+1 -8
View File
@@ -17,20 +17,13 @@ export const tabStackScreenTitles: Record<string, string> = {
"downloads/other": "Other Downloaded Songs", "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( export function useStackScreenOptions(
overrides?: StackScreenOptions overrides?: StackScreenOptions
): StackScreenOptions { ): StackScreenOptions {
const theme = useThemeColors() const theme = useThemeColors()
return { return {
headerLargeTitle: false, headerLargeTitle: true,
headerTransparent: true, headerTransparent: true,
headerTintColor: theme.foreground, headerTintColor: theme.foreground,
headerLargeTitleStyle: { color: theme.foreground }, headerLargeTitleStyle: { color: theme.foreground },
@@ -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
@@ -114,6 +114,7 @@ export function AlbumView({
}) { }) {
const { const {
isSongFavorite, isSongFavorite,
areSongsFavorite,
isAlbumFavorite, isAlbumFavorite,
toggleSongFavorite, toggleSongFavorite,
toggleAlbumFavorite, toggleAlbumFavorite,
@@ -154,6 +155,7 @@ export function AlbumView({
handlePointerDown, handlePointerDown,
prepareContextMenu, prepareContextMenu,
} = useTrackSelection(album.tracks, validHighlightedSongId) } = useTrackSelection(album.tracks, validHighlightedSongId)
const selectionFavorited = areSongsFavorite(selectedIds)
const selectionPositions = React.useMemo( const selectionPositions = React.useMemo(
() => () =>
@@ -413,6 +415,7 @@ export function AlbumView({
isFavorite={isSongFavorite(track.id)} isFavorite={isSongFavorite(track.id)}
selectedCount={selectedCount} selectedCount={selectedCount}
selectionStationArtistId={album.artist.id} selectionStationArtistId={album.artist.id}
selectionFavorited={selectionFavorited}
isNowPlaying={currentSongId === track.id} isNowPlaying={currentSongId === track.id}
onPointerDown={handlePointerDown} onPointerDown={handlePointerDown}
onSelect={handleRowSelect} onSelect={handleRowSelect}
+12 -21
View File
@@ -37,7 +37,8 @@ type FavoritesContextValue = {
) => Promise<boolean> ) => Promise<boolean>
toggleAlbumFavorite: (albumId: Id<"albums">) => Promise<void> toggleAlbumFavorite: (albumId: Id<"albums">) => Promise<void>
toggleArtistFavorite: (artistId: Id<"artists">) => 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) const FavoritesContext = React.createContext<FavoritesContextValue | null>(null)
@@ -130,26 +131,16 @@ export function FavoritesProvider({ children }: { children: React.ReactNode }) {
[songIds, favoriteSong, unfavoriteSong] [songIds, favoriteSong, unfavoriteSong]
) )
const favoriteSongs = React.useCallback( const areSongsFavorite = React.useCallback(
async (ids: Id<"songs">[]) => { (ids: Iterable<string>) => {
const unique = [...new Set(ids)] let any = false
if (unique.length === 0) { for (const id of ids) {
return if (!songIds.has(id)) return false
} any = true
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"
)
} }
return any
}, },
[favoriteSongsMutation] [songIds]
) )
const toggleSongsFavorite = React.useCallback( const toggleSongsFavorite = React.useCallback(
@@ -232,7 +223,7 @@ export function FavoritesProvider({ children }: { children: React.ReactNode }) {
toggleSongsFavorite, toggleSongsFavorite,
toggleAlbumFavorite, toggleAlbumFavorite,
toggleArtistFavorite, toggleArtistFavorite,
favoriteSongs, areSongsFavorite,
}), }),
[ [
isSongFavorite, isSongFavorite,
@@ -242,7 +233,7 @@ export function FavoritesProvider({ children }: { children: React.ReactNode }) {
toggleSongsFavorite, toggleSongsFavorite,
toggleAlbumFavorite, toggleAlbumFavorite,
toggleArtistFavorite, 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 * 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({ function FilledWords({
words, words,
@@ -200,6 +201,7 @@ function FilledWords({
React.useEffect(() => { React.useEffect(() => {
fills.current = words.map((word, index) => fills.current = words.map((word, index) =>
spans.current[index]?.animate(WORD_FILL_FRAMES, { spans.current[index]?.animate(WORD_FILL_FRAMES, {
delay: word.start * 1000,
duration: Math.max(word.end - word.start, 0.05) * 1000, duration: Math.max(word.end - word.start, 0.05) * 1000,
easing: "linear", easing: "linear",
fill: "both", fill: "both",
@@ -209,15 +211,14 @@ function FilledWords({
}, [words]) }, [words])
React.useEffect(() => { React.useEffect(() => {
const at = time * 1000
fills.current.forEach((fill, index) => { fills.current.forEach((fill, index) => {
if (!fill) return if (!fill) return
const at = (time - words[index].start) * 1000
if (Math.abs(Number(fill.currentTime ?? 0) - at) > FILL_DRIFT_MS) { if (Math.abs(Number(fill.currentTime ?? 0) - at) > FILL_DRIFT_MS) {
fill.currentTime = at fill.currentTime = at
} }
// `play` on a finished fill would rewind it. // `play` on a finished fill would rewind it to the start.
const duration = Number(fill.effect?.getTiming().duration ?? 0) if (isPlaying && time < words[index].end) fill.play()
if (isPlaying && at < duration) fill.play()
else fill.pause() else fill.pause()
}) })
}, [words, time, isPlaying]) }, [words, time, isPlaying])
+4 -1
View File
@@ -48,7 +48,8 @@ export function OtherDownloadsView() {
[songs] [songs]
) )
const { isSongFavorite, toggleSongFavorite } = useFavorites() const { isSongFavorite, areSongsFavorite, toggleSongFavorite } =
useFavorites()
const { playFromSong, playInOrder, playShuffled } = usePlaybackActions() const { playFromSong, playInOrder, playShuffled } = usePlaybackActions()
const { const {
selectedIds, selectedIds,
@@ -62,6 +63,7 @@ export function OtherDownloadsView() {
() => stationArtistId(songs, selectedIds), () => stationArtistId(songs, selectedIds),
[songs, selectedIds] [songs, selectedIds]
) )
const selectionFavorited = areSongsFavorite(selectedIds)
const selectionPositions = useMemo( const selectionPositions = useMemo(
() => () =>
getSelectionRangePositions( getSelectionRangePositions(
@@ -140,6 +142,7 @@ export function OtherDownloadsView() {
isFavorite={isSongFavorite(songs[index].id)} isFavorite={isSongFavorite(songs[index].id)}
selectedCount={selectedCount} selectedCount={selectedCount}
selectionStationArtistId={selectedStationArtistId} selectionStationArtistId={selectedStationArtistId}
selectionFavorited={selectionFavorited}
onPointerDown={handlePointerDown} onPointerDown={handlePointerDown}
onSelect={handleRowSelect} onSelect={handleRowSelect}
onPlay={handleRowPlay} onPlay={handleRowPlay}
+9 -2
View File
@@ -74,8 +74,12 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
currentUser === undefined currentUser === undefined
? playlist.isOwner ? playlist.isOwner
: currentUser?._id === playlist.owner.id : currentUser?._id === playlist.owner.id
const { isSongFavorite, toggleSongFavorite, toggleSongsFavorite } = const {
useFavorites() isSongFavorite,
areSongsFavorite,
toggleSongFavorite,
toggleSongsFavorite,
} = useFavorites()
const currentSongId = useCurrentSongId() const currentSongId = useCurrentSongId()
const { const {
playInOrder, playInOrder,
@@ -143,6 +147,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
() => stationArtistId(songs, selectedIds), () => stationArtistId(songs, selectedIds),
[songs, selectedIds] [songs, selectedIds]
) )
const selectionFavorited = areSongsFavorite(selectedIds)
const selectionPositions = React.useMemo( const selectionPositions = React.useMemo(
() => () =>
@@ -465,6 +470,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
onAction={handlePlaylistMediaAction} onAction={handlePlaylistMediaAction}
playlistLabel={ADD_TO_ANOTHER_PLAYLIST} playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
showFavorite={!isFavorites} showFavorite={!isFavorites}
favorited={areSongsFavorite(playlistSongIds)}
downloaded={playlistDownloaded} downloaded={playlistDownloaded}
trackRowTrigger={false} trackRowTrigger={false}
triggerVariant="secondary" triggerVariant="secondary"
@@ -522,6 +528,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
selectionPosition={selectionPositions[index]} selectionPosition={selectionPositions[index]}
selectedCount={selectedCount} selectedCount={selectedCount}
selectionStationArtistId={selectedStationArtistId} selectionStationArtistId={selectedStationArtistId}
selectionFavorited={selectionFavorited}
playlistLabel={ADD_TO_ANOTHER_PLAYLIST} playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
downloadCollection={downloadRef} downloadCollection={downloadRef}
showFavoriteInMenu={!isFavorites} showFavoriteInMenu={!isFavorites}
+167 -40
View File
@@ -2,11 +2,18 @@
import * as React from "react" import * as React from "react"
import { useFavorites } from "@/components/favorites-provider"
import {
MediaContextMenuArea,
type MediaContextAction,
} from "@/components/media-context-menu"
import { PlaybackSongMeta } from "@/components/playback-song-meta" import { PlaybackSongMeta } from "@/components/playback-song-meta"
import { usePlayback } from "@/components/playback-provider" import { usePlayback } from "@/components/playback-provider"
import { TrackCover, TrackRow } from "@/components/track-row" import { TrackCover, TrackRow } from "@/components/track-row"
import { Skeleton } from "@/components/ui/skeleton" import { Skeleton } from "@/components/ui/skeleton"
import { Spinner } from "@/components/ui/spinner" import { Spinner } from "@/components/ui/spinner"
import { useSongDownloadState } from "@/hooks/use-downloads"
import { useMediaActions } from "@/hooks/use-media-actions"
import { useTrackSelection } from "@/hooks/use-track-selection" import { useTrackSelection } from "@/hooks/use-track-selection"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong, QueueSong } from "@otunes/convex/types" import type { BrowseSong, QueueSong } from "@otunes/convex/types"
@@ -15,6 +22,7 @@ import {
moveQueueBlock, moveQueueBlock,
} from "@/lib/move-queue-block" } from "@/lib/move-queue-block"
import { getSelectionRangePositions } from "@/lib/selection-range-styles" import { getSelectionRangePositions } from "@/lib/selection-range-styles"
import { stationArtistId } from "@/lib/station-artist"
import { useSongs } from "@/lib/song-cache" import { useSongs } from "@/lib/song-cache"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
@@ -46,6 +54,51 @@ function toSelectableQueue(
}) })
} }
/**
* Opens the song's right-click menu over `children`, for the queue rows that
* stand alone (history and the current song) rather than in the selection.
*/
function SongMenuArea({
song,
children,
}: {
song: BrowseSong
children: React.ReactElement
}) {
const { isSongFavorite, toggleSongFavorite } = useFavorites()
const { runSongsAction } = useMediaActions()
const downloaded = useSongDownloadState(song.id) === "here"
function handleAction(action: MediaContextAction) {
if (action === "favorite") {
void toggleSongFavorite(song.id)
return
}
runSongsAction(action, [song.id], song.artist.id)
}
return (
<MediaContextMenuArea
menu={{
label: `More options for ${song.title}`,
stationArtistId: song.artist.id,
selectedCount: 1,
onOpenMenu: () => {},
onAction: handleAction,
favorited: isSongFavorite(song.id),
downloaded,
navigation: {
artist: { id: song.artist.id },
album: { id: song.album.id },
},
share: { type: "song", albumId: song.album.id, songId: song.id },
}}
>
{children}
</MediaContextMenuArea>
)
}
/** A played song; clicking it plays it again from that point in history. */ /** A played song; clicking it plays it again from that point in history. */
function HistorySongRow({ function HistorySongRow({
song, song,
@@ -61,25 +114,27 @@ function HistorySongRow({
} }
return ( return (
<li <SongMenuArea song={song}>
role="button" <li
tabIndex={0} role="button"
className="flex cursor-pointer items-center gap-3 px-4 py-2 text-sm hover:bg-foreground/5" tabIndex={0}
onClick={() => onPlay(historyIndex)} className="flex cursor-pointer items-center gap-3 px-4 py-2 text-sm hover:bg-foreground/5 data-[state=open]:bg-foreground/5"
onKeyDown={(event) => { onClick={() => onPlay(historyIndex)}
if (event.key === "Enter" || event.key === " ") { onKeyDown={(event) => {
event.preventDefault() if (event.key === "Enter" || event.key === " ") {
onPlay(historyIndex) event.preventDefault()
} onPlay(historyIndex)
}} }
> }}
<TrackCover >
albumId={song.album.id} <TrackCover
alt={song.album.title} albumId={song.album.id}
inRange={false} alt={song.album.title}
/> inRange={false}
<PlaybackSongMeta song={song} align="start" showAlbum={false} /> />
</li> <PlaybackSongMeta song={song} align="start" showAlbum={false} />
</li>
</SongMenuArea>
) )
} }
@@ -181,8 +236,71 @@ export function QueuePanel() {
() => selectableQueue.map((item) => ({ id: item.selectionId })), () => selectableQueue.map((item) => ({ id: item.selectionId })),
[selectableQueue] [selectableQueue]
) )
const { selectedIds, handleSelect, handlePointerDown } = const {
useTrackSelection(selectionItems) selectedIds,
selectedCount,
handleSelect,
handlePointerDown,
prepareContextMenu,
clearSelection,
} = useTrackSelection(selectionItems)
const { isSongFavorite, areSongsFavorite } = useFavorites()
const { runSongsAction } = useMediaActions()
/** The rows a menu acts on: the selection, else just the clicked row. */
const menuTargets = React.useCallback(
(selectionId: string) => {
const ids = selectedIds.has(selectionId)
? selectedIds
: new Set([selectionId])
return selectableQueue.filter((item) => ids.has(item.selectionId))
},
[selectableQueue, selectedIds]
)
const selectedStationArtistId = React.useMemo(
() =>
stationArtistId(
selectableQueue.flatMap((item) =>
item.song ? [{ id: item.selectionId, artist: item.song.artist }] : []
),
selectedIds
),
[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) => {
const songs = menuTargets(selectionId).flatMap((item) =>
item.song ? [item.song] : []
)
const artistId = songs[0]?.artist.id
runSongsAction(
action,
songs.map((song) => song.id),
songs.every((song) => song.artist.id === artistId)
? artistId
: undefined
)
},
[menuTargets, runSongsAction]
)
const handleRemove = React.useCallback(
(selectionId: string) => {
const removed = new Set(
menuTargets(selectionId).map((item) => item.queueIndex)
)
clearSelection()
void reorderQueue(queueSongIds.filter((_, index) => !removed.has(index)))
},
[clearSelection, menuTargets, queueSongIds, reorderQueue]
)
const handleRowSelect = React.useCallback( const handleRowSelect = React.useCallback(
(index: number, event: React.MouseEvent) => { (index: number, event: React.MouseEvent) => {
@@ -292,25 +410,25 @@ export function QueuePanel() {
{/* Fills the viewport so the current song can always scroll to the top. */} {/* Fills the viewport so the current song can always scroll to the top. */}
<div ref={currentRef} className="flex min-h-full flex-col"> <div ref={currentRef} className="flex min-h-full flex-col">
{currentQueueSongId ? ( {currentSong ? (
<div className="flex items-center gap-3 px-4 py-3"> <SongMenuArea song={currentSong}>
{currentSong ? ( <div className="flex items-center gap-3 px-4 py-3">
<> <TrackCover
<TrackCover albumId={currentSong.album.id}
albumId={currentSong.album.id} alt={currentSong.album.title}
alt={currentSong.album.title} inRange={false}
inRange={false} size="lg"
size="lg" />
/> <PlaybackSongMeta
<PlaybackSongMeta song={currentSong}
song={currentSong} align="start"
align="start" showAlbum={false}
showAlbum={false} />
/> </div>
</> </SongMenuArea>
) : ( ) : currentQueueSongId ? (
<Skeleton className="size-14 shrink-0 rounded-md" /> <div className="px-4 py-3">
)} <Skeleton className="size-14 shrink-0 rounded-md" />
</div> </div>
) : null} ) : null}
@@ -336,6 +454,12 @@ export function QueuePanel() {
variant="queue" variant="queue"
song={item.song} song={item.song}
index={index} index={index}
selectionId={item.selectionId}
isFavorite={isSongFavorite(item.song.id)}
selectedCount={selectedCount}
selectionStationArtistId={selectedStationArtistId}
selectionFavorited={selectionFavorited}
removeLabel="Remove from Queue"
selectionPosition={selectionPositions[index]} selectionPosition={selectionPositions[index]}
isDragging={draggingIndices.has(index)} isDragging={draggingIndices.has(index)}
onPointerDown={handlePointerDown} onPointerDown={handlePointerDown}
@@ -343,6 +467,9 @@ export function QueuePanel() {
onPlay={handleRowPlay} onPlay={handleRowPlay}
onDragStart={setDragIndex} onDragStart={setDragIndex}
onDrop={handleDrop} onDrop={handleDrop}
onPrepareContextMenu={prepareContextMenu}
onMediaAction={handleMediaAction}
onRemove={handleRemove}
/> />
) : ( ) : (
<QueueSongRowSkeleton key={item.selectionId} /> <QueueSongRowSkeleton key={item.selectionId} />
+4 -1
View File
@@ -47,7 +47,8 @@ const SONGS_PAGE_SIZE = 50
const estimateSongRowSize = () => 56 const estimateSongRowSize = () => 56
export function SongsView() { export function SongsView() {
const { isSongFavorite, toggleSongFavorite } = useFavorites() const { isSongFavorite, areSongsFavorite, toggleSongFavorite } =
useFavorites()
const { playFromLibrarySong } = usePlaybackActions() const { playFromLibrarySong } = usePlaybackActions()
const [sortKey, setSortKey] = useState<SortKey>("title") const [sortKey, setSortKey] = useState<SortKey>("title")
const [sortDirection, setSortDirection] = useState<SortDirection>("asc") const [sortDirection, setSortDirection] = useState<SortDirection>("asc")
@@ -98,6 +99,7 @@ export function SongsView() {
() => stationArtistId(songs, selectedIds), () => stationArtistId(songs, selectedIds),
[songs, selectedIds] [songs, selectedIds]
) )
const selectionFavorited = areSongsFavorite(selectedIds)
const selectionPositions = useMemo( const selectionPositions = useMemo(
() => () =>
@@ -222,6 +224,7 @@ export function SongsView() {
isFavorite={isSongFavorite(songs[index].id)} isFavorite={isSongFavorite(songs[index].id)}
selectedCount={selectedCount} selectedCount={selectedCount}
selectionStationArtistId={selectedStationArtistId} selectionStationArtistId={selectedStationArtistId}
selectionFavorited={selectionFavorited}
onPointerDown={handlePointerDown} onPointerDown={handlePointerDown}
onSelect={handleRowSelect} onSelect={handleRowSelect}
onPlay={handleRowPlay} onPlay={handleRowPlay}
+24 -10
View File
@@ -38,7 +38,7 @@ import type { DownloadSource } from "@otunes/convex/client/download-queue"
* columns (use with `LibraryTrackListHeader`). * columns (use with `LibraryTrackListHeader`).
* - `album`: favorite star, track number, title with optional credits. * - `album`: favorite star, track number, title with optional credits.
* - `playlist`: cover with favorite overlay, track number, title. * - `playlist`: cover with favorite overlay, track number, title.
* - `queue`: cover, title and artist, duration, and a reorder grip. No menu. * - `queue`: cover, title and artist, duration, and a reorder grip.
*/ */
export type TrackRowVariant = "library" | "album" | "playlist" | "queue" export type TrackRowVariant = "library" | "album" | "playlist" | "queue"
@@ -47,6 +47,12 @@ export type TrackRowProps = {
song: BrowseSong song: BrowseSong
/** Position in the list the selection hook was given. */ /** Position in the list the selection hook was given. */
index: number index: number
/**
* The id the selection hook knows this row by, passed to the menu and
* remove callbacks. Defaults to the song id; the queue uses a per-position
* id since a song can appear more than once.
*/
selectionId?: string
/** Number shown in the track number column (`album` and `playlist`). */ /** Number shown in the track number column (`album` and `playlist`). */
trackNumber?: number trackNumber?: number
/** Secondary line under the title, e.g. album track credits. */ /** Secondary line under the title, e.g. album track credits. */
@@ -62,6 +68,8 @@ export type TrackRowProps = {
selectedCount?: number selectedCount?: number
/** Station artist for the selection when this row is selected. */ /** Station artist for the selection when this row is selected. */
selectionStationArtistId?: string selectionStationArtistId?: string
/** Whether every selected song is favorited, when this row is selected. */
selectionFavorited?: boolean
playlistLabel?: string playlistLabel?: string
showFavoriteInMenu?: boolean showFavoriteInMenu?: boolean
/** Adds a destructive menu item calling `onRemove`. */ /** Adds a destructive menu item calling `onRemove`. */
@@ -71,10 +79,10 @@ export type TrackRowProps = {
onPointerDown: (event: React.MouseEvent) => void onPointerDown: (event: React.MouseEvent) => void
onPlay: (index: number) => void onPlay: (index: number) => void
onToggleFavorite?: (songId: string) => void onToggleFavorite?: (songId: string) => void
onPrepareContextMenu?: (songId: string) => void onPrepareContextMenu?: (selectionId: string) => void
/** Renders the "more options" and right-click menus when provided. */ /** Renders the "more options" and right-click menus when provided. */
onMediaAction?: (action: MediaContextAction, songId: string) => void onMediaAction?: (action: MediaContextAction, selectionId: string) => void
onRemove?: (songId: string) => void onRemove?: (selectionId: string) => void
/** Makes the row draggable when provided. */ /** Makes the row draggable when provided. */
onDragStart?: (index: number) => void onDragStart?: (index: number) => void
onDrop?: (index: number) => void onDrop?: (index: number) => void
@@ -251,6 +259,7 @@ function TrackRowComponent({
variant, variant,
song, song,
index, index,
selectionId,
trackNumber, trackNumber,
subtitle, subtitle,
downloadCollection, downloadCollection,
@@ -261,6 +270,7 @@ function TrackRowComponent({
isDragging = false, isDragging = false,
selectedCount = 0, selectedCount = 0,
selectionStationArtistId, selectionStationArtistId,
selectionFavorited,
playlistLabel, playlistLabel,
showFavoriteInMenu = true, showFavoriteInMenu = true,
removeLabel, removeLabel,
@@ -284,6 +294,7 @@ function TrackRowComponent({
const flush = variant === "library" || variant === "queue" const flush = variant === "library" || variant === "queue"
const play = () => onPlay(index) const play = () => onPlay(index)
const toggleFavorite = () => onToggleFavorite?.(song.id) const toggleFavorite = () => onToggleFavorite?.(song.id)
const rowId = selectionId ?? song.id
const favoriteStar = ( const favoriteStar = (
<div className="flex shrink-0 items-center justify-center"> <div className="flex shrink-0 items-center justify-center">
@@ -333,11 +344,14 @@ function TrackRowComponent({
stationArtistId: inRange ? selectionStationArtistId : song.artist.id, stationArtistId: inRange ? selectionStationArtistId : song.artist.id,
selectedCount: inRange && selectedCount > 0 ? selectedCount : 1, selectedCount: inRange && selectedCount > 0 ? selectedCount : 1,
inSelectionRange: inRange, inSelectionRange: inRange,
onOpenMenu: () => onPrepareContextMenu?.(song.id), onOpenMenu: () => onPrepareContextMenu?.(rowId),
onAction: (action) => onMediaAction(action, song.id), onAction: (action) => onMediaAction(action, rowId),
playlistLabel, playlistLabel,
showFavorite: showFavoriteInMenu, showFavorite: showFavoriteInMenu,
favorited: isFavorite, favorited:
inRange && selectedCount > 0
? (selectionFavorited ?? isFavorite)
: isFavorite,
navigation: { navigation: {
artist: { id: song.artist.id }, artist: { id: song.artist.id },
album: { id: song.album.id }, album: { id: song.album.id },
@@ -351,7 +365,7 @@ function TrackRowComponent({
<MediaMenuItem <MediaMenuItem
variant="destructive" variant="destructive"
className="justify-between" className="justify-between"
onClick={() => onRemove(song.id)} onClick={() => onRemove(rowId)}
> >
{removeLabel} {removeLabel}
<Trash2 /> <Trash2 />
@@ -555,7 +569,7 @@ function TrackRowComponent({
} }
/** /**
* Pass stable callbacks: they receive the row's `index` or song id, so one * Pass stable callbacks: they receive the row's `index`, song id or
* handler can serve every row. * `selectionId`, so one handler can serve every row.
*/ */
export const TrackRow = React.memo(TrackRowComponent) export const TrackRow = React.memo(TrackRowComponent)
+6 -3
View File
@@ -26,7 +26,8 @@ function songsTitle(songIds: readonly string[]) {
export function useMediaActions() { export function useMediaActions() {
const { openAddToPlaylist, openAddArtistToPlaylist } = useAddToPlaylist() const { openAddToPlaylist, openAddArtistToPlaylist } = useAddToPlaylist()
const { favoriteSongs, toggleArtistFavorite } = useFavorites() const { areSongsFavorite, toggleSongsFavorite, toggleArtistFavorite } =
useFavorites()
const { runQueueAction, createStation } = useQueueMediaActions() const { runQueueAction, createStation } = useQueueMediaActions()
const convex = useConvex() const convex = useConvex()
const cacheScope = useCacheScope() const cacheScope = useCacheScope()
@@ -44,7 +45,8 @@ export function useMediaActions() {
if (stationArtist) void createStation(stationArtist) if (stationArtist) void createStation(stationArtist)
break break
case "favorite": case "favorite":
void favoriteSongs(songIds) // Unfavorite only when every song already is, matching the menu label.
void toggleSongsFavorite(songIds, areSongsFavorite(songIds))
break break
case "playlist": case "playlist":
openAddToPlaylist(songIds) openAddToPlaylist(songIds)
@@ -73,7 +75,8 @@ export function useMediaActions() {
}, },
[ [
createStation, createStation,
favoriteSongs, areSongsFavorite,
toggleSongsFavorite,
openAddToPlaylist, openAddToPlaylist,
runQueueAction, runQueueAction,
requestDownload, requestDownload,
+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. * the same.
*/ */
import { matchWords, searchWords } from "./fuzzy-search"
export type LyricWord = { export type LyricWord = {
/** Includes its trailing space, so a line's words join back into its text. */ /** Includes its trailing space, so a line's words join back into its text. */
text: string text: string
@@ -16,11 +18,15 @@ export type LyricLine = {
text: string text: string
/** Seconds; `null` for plain lyrics. */ /** Seconds; `null` for plain lyrics. */
start: number | null 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 words: LyricWord[] | null
} }
export type Lyrics = { export type Lyrics = {
/** How the source was timed, whatever `words` were estimated. */
synced: "none" | "line" | "word" synced: "none" | "line" | "word"
lines: LyricLine[] lines: LyricLine[]
} }
@@ -29,6 +35,8 @@ const LINE_STAMP = /^\[(\d+):(\d+(?:[.:]\d+)?)\]/
const WORD_STAMP = /<(\d+):(\d+(?:[.:]\d+)?)>/g const WORD_STAMP = /<(\d+):(\d+(?:[.:]\d+)?)>/g
const HAS_WORD_STAMP = /<\d+:\d+(?:[.:]\d+)?>/ const HAS_WORD_STAMP = /<\d+:\d+(?:[.:]\d+)?>/
const ID_TAG = /^\[[a-z]+:.*\]$/i 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) { function seconds(minutes: string, rest: string) {
return Number(minutes) * 60 + Number(rest.replace(":", ".")) 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!) lines.sort((a, b) => a.start! - b.start!)
if (lines.length === 0) return null if (lines.length === 0) return null
return { const synced = lines.every((line) => line.words) ? "word" : "line"
synced: lines.every((line) => line.words) ? "word" : "line", if (synced === "line") estimateWords(lines)
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. */ /** The text without timestamps, one line per row, for search and snippets. */
@@ -185,32 +214,32 @@ export function followLyrics(
return () => clearTimeout(timer) 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 const SNIPPET_LEAD = 24
export type LyricsMatch = { export type LyricsMatch = {
/** The matched line, trimmed to start near the match. */ /** The matched line, trimmed to start near the match. */
snippet: string 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 * Where a search matched the lyrics: the best line holding the query as
* else a line holding every word of it (the last may be a prefix, as when * typed, or else every word of it (see `matchWords`). Null when no single
* typing). Null when no single line does. * line does.
*/ */
export function matchLyrics(plain: string, query: string): LyricsMatch | null { export function matchLyrics(plain: string, query: string): LyricsMatch | null {
const needle = query.trim().toLowerCase() const needle = query.trim().toLowerCase()
const terms = searchTerms(needle) const terms = searchWords(needle)
const last = terms.at(-1) // Most songs miss a word entirely, so skip them before checking lines.
if (!needle || last === undefined) return null 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")) { for (const line of plain.split("\n")) {
const column = line.toLowerCase().indexOf(needle) const column = line.toLowerCase().indexOf(needle)
if (column !== -1) { if (column !== -1) {
@@ -218,15 +247,13 @@ export function matchLyrics(plain: string, query: string): LyricsMatch | null {
column > SNIPPET_LEAD column > SNIPPET_LEAD
? `…${line.slice(column - SNIPPET_LEAD).trimStart()}` ? `…${line.slice(column - SNIPPET_LEAD).trimStart()}`
: line.trim() : line.trim()
return { snippet, exact: true } return { snippet, score: 2 }
} }
if (loose === null) { if (loose?.score === 1) continue
const words = searchTerms(line) const quality = matchWords(searchWords(line), terms)
const hasAll = if (quality === "exact" || (quality && !loose)) {
terms.slice(0, -1).every((term) => words.includes(term)) && loose = { snippet: line.trim(), score: quality === "exact" ? 1 : 0 }
words.some((word) => word.startsWith(last))
if (hasAll) loose = line.trim()
} }
} }
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 = { type SearchableSong = {
id: string id: string
title: string title: string
@@ -6,9 +8,9 @@ type SearchableSong = {
} }
/** /**
* Case-insensitive match on title, artist, or album, plus the songs in * Case-insensitive match on title, artist, or album, give or take typos (see
* `lyricsMatches` (from `api.lyrics.matchingSongIds`). A blank query keeps * `matchWords`), plus the songs in `lyricsMatches` (from
* every song. * `api.lyrics.matchingSongIds`). A blank query keeps every song.
*/ */
export function filterSongs<T extends SearchableSong>( export function filterSongs<T extends SearchableSong>(
songs: T[], songs: T[],
@@ -19,12 +21,14 @@ export function filterSongs<T extends SearchableSong>(
if (!normalized) { if (!normalized) {
return songs return songs
} }
const terms = searchWords(normalized)
const byLyrics = new Set(lyricsMatches) const byLyrics = new Set(lyricsMatches)
return songs.filter( return songs.filter((song) => {
(song) => if (byLyrics.has(song.id)) return true
byLyrics.has(song.id) || const fields = [song.title, song.artist.name, song.album.title]
[song.title, song.artist.name, song.album.title].some((value) => return (
value.toLowerCase().includes(normalized) 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 { recordIntentCatalogChanges } from "./intentCatalogChanges"
import { playlistCoverVersion } from "./playlistCover" import { playlistCoverVersion } from "./playlistCover"
import { deleteSongLyrics, searchSongLyrics, writeSongLyrics } from "./lyrics" import { deleteSongLyrics, searchSongLyrics, writeSongLyrics } from "./lyrics"
import { matchWords, searchWords } from "../client/fuzzy-search"
export type { export type {
BrowseAlbum, 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() const lower = text.toLowerCase()
if (lower === query) { if (lower === query) {
return 100 return 100
@@ -632,15 +642,20 @@ function matchScore(text: string, query: string): number {
if (lower.includes(query)) { if (lower.includes(query)) {
return 40 return 40
} }
return 0 const words = matchWords(searchWords(text), terms)
if (words === "exact") {
return 30
}
return words === "fuzzy" ? 20 : 0
} }
function matchScoreSongArtists( function matchScoreSongArtists(
artist: string | string[], artist: string | string[],
query: string query: string,
terms: readonly string[]
): number { ): number {
return getSongArtistNames(artist).reduce( return getSongArtistNames(artist).reduce(
(best, name) => Math.max(best, matchScore(name, query)), (best, name) => Math.max(best, matchScore(name, query, terms)),
0 0
) )
} }
@@ -658,6 +673,7 @@ export const searchLibrary = query({
args: { query: v.string() }, args: { query: v.string() },
handler: async (ctx, args) => { handler: async (ctx, args) => {
const queryText = args.query.trim().toLowerCase() const queryText = args.query.trim().toLowerCase()
const terms = searchWords(queryText)
if (!queryText || !(await isSignedIn(ctx))) { if (!queryText || !(await isSignedIn(ctx))) {
return { return {
topResults: [], topResults: [],
@@ -678,7 +694,7 @@ export const searchLibrary = query({
.map((artist) => ({ .map((artist) => ({
kind: "artist" as const, kind: "artist" as const,
item: toBrowseArtist(artist), item: toBrowseArtist(artist),
score: matchScore(artist.name, queryText), score: matchScore(artist.name, queryText, terms),
})) }))
.filter((result) => result.score > 0) .filter((result) => result.score > 0)
.sort( .sort(
@@ -692,8 +708,8 @@ export const searchLibrary = query({
return [] return []
} }
const score = Math.max( const score = Math.max(
matchScore(album.name, queryText), matchScore(album.name, queryText, terms),
matchScore(artist.name, queryText) matchScore(artist.name, queryText, terms)
) )
if (score === 0) { if (score === 0) {
return [] return []
@@ -718,10 +734,10 @@ export const searchLibrary = query({
return [] return []
} }
const score = Math.max( const score = Math.max(
matchScore(song.name, queryText), matchScore(song.name, queryText, terms),
matchScoreSongArtists(song.artist, queryText), matchScoreSongArtists(song.artist, queryText, terms),
matchScore(album.name, queryText), matchScore(album.name, queryText, terms),
matchScore(albumArtist.name, queryText) matchScore(albumArtist.name, queryText, terms)
) )
if (score === 0) { if (score === 0) {
return [] 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 * Up to `limit` songs with a lyrics line matching `query` (see `matchLyrics`),
* line. Lines holding the query as typed come first, then the search index's * with that line, best matches first. The search index matches any word
* relevance order. The index matches words anywhere in the lyrics, so its * anywhere in the lyrics and ranks common words poorly, so its whole page is
* results are checked line by line. * checked line by line before trimming.
*/ */
export async function searchSongLyrics( export async function searchSongLyrics(
ctx: QueryCtx, ctx: QueryCtx,
@@ -77,15 +77,15 @@ export async function searchSongLyrics(
const rows = await ctx.db const rows = await ctx.db
.query("lyricsSearch") .query("lyricsSearch")
.withSearchIndex("search_plain", (q) => q.search("plain", text)) .withSearchIndex("search_plain", (q) => q.search("plain", text))
.take(limit) .take(MAX_LYRICS_MATCHES)
const matches = rows.flatMap((row) => { return rows
const match = matchLyrics(row.plain, text) .flatMap((row) => {
return match ? [{ song: row.song, ...match }] : [] const match = matchLyrics(row.plain, text)
}) return match ? [{ song: row.song, ...match }] : []
return [ })
...matches.filter((match) => match.exact), .sort((a, b) => b.score - a.score)
...matches.filter((match) => !match.exact), .slice(0, limit)
].map(({ song, snippet }) => ({ song, snippet })) .map(({ song, snippet }) => ({ song, snippet }))
} }
/** The song's lyrics tag (see `client/lyrics.ts`), or null without lyrics. */ /** The song's lyrics tag (see `client/lyrics.ts`), or null without lyrics. */