Compare commits

..
40 changed files with 528 additions and 512 deletions

No files matched your search

@@ -1,8 +1,11 @@
import { Stack } from "expo-router"
import { TabStackContext } from "@/lib/app-navigation"
import { renderTabScreenContent } from "@/components/tab-screen-content"
import { useStackScreenOptions, tabStackScreenTitles } from "@/lib/navigation"
import {
inlineTitleOptions,
tabStackScreenTitles,
useStackScreenOptions,
} from "@/lib/navigation"
import { tabletSections, TabletSectionContext } from "@/lib/tablet-navigation"
export default function TabletSectionLayout({ segment }: { segment: string }) {
@@ -11,18 +14,17 @@ export default function TabletSectionLayout({ segment }: { segment: string }) {
return (
<TabletSectionContext value={section}>
<TabStackContext value={section?.group}>
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...options,
title:
route.name === "index"
? section?.title
: tabStackScreenTitles[route.name],
})}
/>
</TabStackContext>
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...options,
...inlineTitleOptions,
title:
route.name === "index"
? section?.title
: tabStackScreenTitles[route.name],
})}
/>
</TabletSectionContext>
)
}
+25 -23
View File
@@ -1,9 +1,12 @@
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 { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
import {
inlineTitleOptions,
tabStackScreenTitles,
useStackScreenOptions,
} from "@/lib/navigation"
export const unstable_settings = {
anchor: "index",
@@ -13,26 +16,25 @@ export default function HomeLayout() {
const baseOptions = useStackScreenOptions({ title: "Home" })
return (
<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>
<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,
})}
/>
)
}
@@ -53,7 +53,7 @@ export default function AlbumsScreen() {
return (
<>
{searchBar}
<MediaGridSkeleton />
<MediaGridSkeleton title="Albums" />
</>
)
}
@@ -63,6 +63,7 @@ export default function AlbumsScreen() {
{searchBar}
<MediaGridList
title="Albums"
content={albums}
paddingBottom={contentBottomInset}
onEndReached={() => {
@@ -2,12 +2,13 @@ import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router"
import { memo, useCallback } from "react"
import {
FlatList,
type FlatList,
Pressable,
StyleSheet,
Text,
type ListRenderItemInfo,
} from "react-native"
import Animated from "react-native-reanimated"
import {
MediaContextMenu,
@@ -15,6 +16,7 @@ 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 {
@@ -33,6 +35,7 @@ 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()
@@ -94,7 +97,7 @@ export default function ArtistsScreen() {
return (
<>
{searchBar}
<ArtistListSkeleton />
<ArtistListSkeleton title="Artists" />
</>
)
}
@@ -103,8 +106,11 @@ export default function ArtistsScreen() {
<>
{searchBar}
<FlatList
<Animated.FlatList
{...longListProps}
ref={ref}
scrollEventThrottle={16}
ListHeaderComponent={<ScreenTitle title="Artists" scrollY={scrollY} />}
data={artists}
keyExtractor={artistKey}
renderItem={renderItem}
@@ -1,3 +1,4 @@
import { useContext } from "react"
import { Pressable } from "react-native"
import { MediaGridList } from "@/components/media-cards"
@@ -10,19 +11,20 @@ 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: "Playlists",
headerLargeTitle: true,
title,
headerRight: () => (
<Pressable
onPress={openCreatePlaylist}
@@ -38,7 +40,7 @@ export default function PlaylistsTabScreen() {
),
}}
/>
<MediaGridSkeleton />
<MediaGridSkeleton title={title} />
</>
)
}
@@ -47,8 +49,7 @@ export default function PlaylistsTabScreen() {
<>
<Stack.Screen
options={{
title: "Playlists",
headerLargeTitle: true,
title,
headerRight: () => (
<Pressable
onPress={openCreatePlaylist}
@@ -61,6 +62,7 @@ export default function PlaylistsTabScreen() {
}}
/>
<MediaGridList
title={title}
content={playlists}
paddingBottom={tabContentBottomInset}
/>
@@ -1,10 +1,16 @@
import { Stack } from "expo-router"
import { useCallback, useState } from "react"
import { FlatList, StyleSheet, type ListRenderItemInfo } from "react-native"
import {
type FlatList,
StyleSheet,
type ListRenderItemInfo,
} from "react-native"
import Animated from "react-native-reanimated"
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 {
@@ -20,6 +26,7 @@ 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()
@@ -87,7 +94,7 @@ export default function SongsScreen() {
return (
<>
{searchBar}
<SongListSkeleton />
<SongListSkeleton title="Songs" />
</>
)
}
@@ -96,8 +103,11 @@ export default function SongsScreen() {
<>
{searchBar}
<FlatList
<Animated.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 {
FlatList,
type FlatList,
Pressable,
StyleSheet,
Text,
@@ -8,8 +8,10 @@ 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,
@@ -53,6 +55,7 @@ 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 []
@@ -135,8 +138,10 @@ export default function DownloadsScreen() {
return (
<>
<Stack.Screen options={{ title: "Downloads", headerLargeTitle: true }} />
<FlatList
<Stack.Screen options={{ title: "Downloads" }} />
<Animated.FlatList
ref={ref}
scrollEventThrottle={16}
key={columns}
onLayout={onLayout}
data={cards}
@@ -149,13 +154,20 @@ 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,15 +1,17 @@
import { useCallback, useMemo } from "react"
import {
FlatList,
type 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"
@@ -52,6 +54,7 @@ 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),
@@ -90,11 +93,11 @@ export default function OtherDownloadsScreen() {
return (
<>
<Stack.Screen
options={{ title: OTHER_DOWNLOADS_TITLE, headerLargeTitle: false }}
/>
<FlatList
<Stack.Screen options={{ title: OTHER_DOWNLOADS_TITLE }} />
<Animated.FlatList
{...longListProps}
ref={ref}
scrollEventThrottle={16}
data={songs}
keyExtractor={(song) => song.id}
renderItem={renderItem}
@@ -103,25 +106,32 @@ export default function OtherDownloadsScreen() {
contentInsetAdjustmentBehavior="automatic"
onScrollBeginDrag={swipeGroup.closeOpenRow}
ListHeaderComponent={
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
<>
<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}
</>
}
ListEmptyComponent={
<Text style={[styles.empty, { color: colors.mutedForeground }]}>
@@ -137,15 +147,14 @@ const styles = StyleSheet.create({
actions: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: spacing.sm,
padding: spacing.lg,
},
playButton: { borderRadius: 999, minWidth: 160 },
iconAction: {
width: 44,
height: 44,
borderRadius: 22,
play: { flex: 1 },
shuffle: {
width: 48,
height: 48,
borderRadius: 24,
alignItems: "center",
justifyContent: "center",
},
+16 -4
View File
@@ -1,8 +1,10 @@
import { memo } from "react"
import { ScrollView, StyleSheet } from "react-native"
import { type ScrollViewInstance, StyleSheet } from "react-native"
import Animated from "react-native-reanimated"
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"
@@ -38,6 +40,7 @@ const HomeCarousels = memo(function HomeCarousels({
export default function HomeScreen() {
const colors = useThemeColors()
const { ref, scrollY } = useScreenTitleScroll<ScrollViewInstance>()
const recentlyAdded = useCachedPaginatedQuery(
api.library.browseRecentlyAddedPaginated,
{},
@@ -53,14 +56,16 @@ export default function HomeScreen() {
(result) => result.status === "LoadingFirstPage" && !result.isCached
)
if (isLoading) {
return <HomeSkeleton />
return <HomeSkeleton title="Home" />
}
const added = recentlyAdded.results.slice(0, CAROUSEL_ITEM_LIMIT)
const played = recentlyPlayed.results.slice(0, CAROUSEL_ITEM_LIMIT)
return (
<ScrollView
<Animated.ScrollView
ref={ref}
scrollEventThrottle={16}
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={[
styles.content,
@@ -68,8 +73,9 @@ export default function HomeScreen() {
]}
contentInsetAdjustmentBehavior="automatic"
>
<ScreenTitle title="Home" scrollY={scrollY} style={styles.title} />
<HomeCarousels recentlyAdded={added} recentlyPlayed={played} />
</ScrollView>
</Animated.ScrollView>
)
}
@@ -78,4 +84,10 @@ 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,11 +14,12 @@ export default function RecentlyAddedScreen() {
)
if (status === "LoadingFirstPage" && !isCached) {
return <MediaGridSkeleton />
return <MediaGridSkeleton title="Recently Added" />
}
return (
<MediaGridList
title="Recently Added"
content={results}
paddingBottom={contentBottomInset}
onEndReached={() => {
@@ -14,11 +14,12 @@ export default function RecentlyPlayedScreen() {
)
if (status === "LoadingFirstPage" && !isCached) {
return <MediaGridSkeleton />
return <MediaGridSkeleton title="Recently Played" />
}
return (
<MediaGridList
title="Recently Played"
content={results}
paddingBottom={contentBottomInset}
onEndReached={() => {
@@ -2,9 +2,12 @@ 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 { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
import {
inlineTitleOptions,
tabStackScreenTitles,
useStackScreenOptions,
} from "@/lib/navigation"
export const unstable_settings = {
anchor: "index",
@@ -15,28 +18,27 @@ export default function LibraryLayout() {
const baseOptions = useStackScreenOptions({ title: "Library" })
return (
<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>
<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,
})}
/>
)
}
@@ -72,6 +72,7 @@ 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,
{},
@@ -124,11 +125,18 @@ export default function LibraryScreen() {
)
if (status === "LoadingFirstPage" && !isCached) {
return <MediaGridSkeleton contentInset={false} header={listHeader} />
return (
<MediaGridSkeleton
title={title}
contentInset={false}
header={listHeader}
/>
)
}
return (
<MediaGridList
title={title}
content={results}
paddingBottom={tabContentBottomInset}
contentInset={false}
+25 -23
View File
@@ -1,9 +1,12 @@
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 { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
import {
inlineTitleOptions,
tabStackScreenTitles,
useStackScreenOptions,
} from "@/lib/navigation"
export const unstable_settings = {
anchor: "index",
@@ -13,26 +16,25 @@ export default function SearchLayout() {
const baseOptions = useStackScreenOptions({ title: "Search" })
return (
<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>
<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,
})}
/>
)
}
@@ -35,7 +35,7 @@ export default function SearchScreen() {
: {})}
/>
<SearchResults searchQuery={searchQuery} />
<SearchResults searchQuery={searchQuery} title="Search" />
</>
)
}
+7 -12
View File
@@ -12,7 +12,6 @@ import Animated, {
Easing,
useAnimatedStyle,
useSharedValue,
withSequence,
withTiming,
type SharedValue,
} from "react-native-reanimated"
@@ -285,17 +284,13 @@ function FilledWords({
useEffect(() => {
cancelAnimation(sung)
// Jump to the reported time first, so the wipe never runs from a stale one.
sung.value =
isPlaying && end > time
? withSequence(
withTiming(time, { duration: 0 }),
withTiming(end, {
duration: (end - time) * 1000,
easing: Easing.linear,
})
)
: time
sung.value = time
if (isPlaying && end > time) {
sung.value = withTiming(end, {
duration: (end - time) * 1000,
easing: Easing.linear,
})
}
}, [sung, time, isPlaying, end])
return (
+25 -2
View File
@@ -4,6 +4,7 @@ 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"
@@ -300,17 +301,21 @@ 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 }}>
@@ -328,13 +333,30 @@ 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 (
<FlatList
<Animated.FlatList
ref={ref}
scrollEventThrottle={16}
key={columns}
onLayout={onLayout}
data={content}
@@ -351,6 +373,7 @@ export function MediaGridList({
paddingBottom,
gap,
...(contentInset ? { paddingHorizontal: horizontalPadding } : {}),
...(title ? { paddingTop: 0 } : {}),
},
]}
columnWrapperStyle={[
@@ -359,7 +382,7 @@ export function MediaGridList({
{ gap },
]}
contentInsetAdjustmentBehavior="automatic"
ListHeaderComponent={ListHeaderComponent}
ListHeaderComponent={header}
onEndReached={onEndReached}
onEndReachedThreshold={0.5}
/>
+84
View File
@@ -0,0 +1,84 @@
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,
},
})
+22 -13
View File
@@ -1,13 +1,15 @@
import { memo, useCallback, useMemo } from "react"
import {
FlatList,
type 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"
@@ -19,8 +21,16 @@ import { api } from "@otunes/convex/_generated/api"
import type { BrowseSong, SearchSong } from "@otunes/convex/types"
import { spacing, useThemeColors } from "@/lib/theme"
function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
function SearchResultsBody({
searchQuery,
title,
}: {
searchQuery: string
/** iOS `ScreenTitle`, shown above the results and while idle. */
title: string
}) {
const colors = useThemeColors()
const { ref, scrollY } = useScreenTitleScroll<FlatList<BrowseSong>>()
const { playFromSong } = usePlaybackActions()
const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions()
@@ -76,16 +86,14 @@ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
)
if (isSearching) {
return <SongListSkeleton />
}
if (!hasQuery) {
return <></>
return <SongListSkeleton title={title} />
}
return (
<FlatList
data={results?.songs ?? []}
<Animated.FlatList
ref={ref}
scrollEventThrottle={16}
data={hasQuery ? (results?.songs ?? []) : []}
keyExtractor={(song) => song.id}
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{ paddingBottom: tabContentBottomInset }}
@@ -93,7 +101,8 @@ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
keyboardShouldPersistTaps="handled"
ListHeaderComponent={
<>
{!hasResults ? (
<ScreenTitle title={title} scrollY={scrollY} />
{hasQuery && !hasResults ? (
<View style={styles.empty}>
<Text
style={[styles.emptyText, { color: colors.mutedForeground }]}
@@ -103,13 +112,13 @@ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
</View>
) : null}
{results?.artists.length ? (
{hasQuery && results?.artists.length ? (
<View style={styles.section}>
<ContentCarousel title="Artists" content={results.artists} />
</View>
) : null}
{results?.albums.length ? (
{hasQuery && results?.albums.length ? (
<View style={styles.section}>
<ContentCarousel title="Albums" content={results.albums} />
</View>
@@ -118,7 +127,7 @@ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
}
renderItem={renderItem}
ListFooterComponent={
playlistResults && playlistResults.length > 0 ? (
hasQuery && playlistResults && playlistResults.length > 0 ? (
<View style={styles.section}>
<ContentCarousel title="Playlists" content={playlistResults} />
</View>
+49 -5
View File
@@ -9,6 +9,7 @@ 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"
@@ -151,9 +152,16 @@ function SongRows({ rows, inset }: { rows: number; inset?: boolean }) {
))
}
export function SongListSkeleton({ rows = 10 }: { rows?: number }) {
export function SongListSkeleton({
rows = 10,
title,
}: {
rows?: number
title?: string
}) {
return (
<SkeletonScreen>
{title ? <ScreenTitle title={title} /> : null}
<SongRows rows={rows} />
</SkeletonScreen>
)
@@ -234,23 +242,45 @@ 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}
header={header}
contentInset={contentInset && !title}
header={
title ? (
<>
<MediaGridTitle title={title} />
{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}>
@@ -264,10 +294,11 @@ export function CarouselSkeleton() {
)
}
export function HomeSkeleton() {
export function HomeSkeleton({ title }: { title: string }) {
return (
<SkeletonScreen>
<View style={styles.home}>
<ScreenTitle title={title} style={styles.homeTitle} />
<CarouselSkeleton />
<CarouselSkeleton />
</View>
@@ -388,10 +419,17 @@ export function CollectionDetailSkeleton({
)
}
export function ArtistListSkeleton({ rows = 12 }: { rows?: number }) {
export function ArtistListSkeleton({
rows = 12,
title,
}: {
rows?: number
title?: string
}) {
const colors = useThemeColors()
return (
<SkeletonScreen>
{title ? <ScreenTitle title={title} /> : null}
{Array.from({ length: rows }, (_, index) => (
<View
key={index}
@@ -456,6 +494,12 @@ 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",
+20 -5
View File
@@ -6,7 +6,7 @@ import {
type ReactElement,
} from "react"
import {
ScrollView,
type ScrollViewInstance,
View,
type NativeSyntheticEvent,
type NativeScrollEvent,
@@ -15,6 +15,7 @@ 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"
@@ -28,6 +29,8 @@ 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
}
@@ -41,9 +44,12 @@ 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()
@@ -102,18 +108,27 @@ export function TabletMediaGrid({
setViewportHeight(event.nativeEvent.layout.height)
}}
>
<ScrollView
<Animated.ScrollView
ref={ref}
onScroll={onScroll}
scrollEventThrottle={32}
// Every frame, so the title pins smoothly on pull-down.
scrollEventThrottle={16}
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={{
paddingTop: contentInset ? horizontalPadding : 0,
paddingTop: contentInset && !title ? 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 }}>
@@ -136,7 +151,7 @@ export function TabletMediaGrid({
)
})}
</View>
</ScrollView>
</Animated.ScrollView>
</Animated.View>
)
}
+8 -22
View File
@@ -1,5 +1,5 @@
import { useRouter, useSegments, type Href } from "expo-router"
import { createContext, use, useCallback } from "react"
import { useCallback } from "react"
import { tabletSections } from "@/lib/tablet-navigation"
@@ -30,13 +30,6 @@ 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)
}
@@ -48,15 +41,8 @@ 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) => {
@@ -67,26 +53,26 @@ export function useAppNavigation() {
return
}
router.push(tabPath(currentTab(), path))
router.push(tabPath(getActiveTabFromRef(), path))
},
[router, currentTab]
[router]
)
const replace = useCallback(
(path: string) => {
router.replace(tabPath(currentTab(), path))
router.replace(tabPath(getActiveTabFromRef(), path))
},
[router, currentTab]
[router]
)
const href = useCallback(
(path: string) => tabPath(currentTab(), path),
[currentTab]
(path: string) => tabPath(getActiveTabFromRef(), path),
[]
)
return {
get tab() {
return currentTab()
return getActiveTabFromRef()
},
href,
push,
+8 -1
View File
@@ -17,13 +17,20 @@ 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: true,
headerLargeTitle: false,
headerTransparent: true,
headerTintColor: theme.foreground,
headerLargeTitleStyle: { color: theme.foreground },
@@ -1,3 +0,0 @@
{
"platforms": ["apple"]
}
@@ -1,37 +0,0 @@
// 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
@@ -1,14 +0,0 @@
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,7 +114,6 @@ export function AlbumView({
}) {
const {
isSongFavorite,
areSongsFavorite,
isAlbumFavorite,
toggleSongFavorite,
toggleAlbumFavorite,
@@ -155,7 +154,6 @@ export function AlbumView({
handlePointerDown,
prepareContextMenu,
} = useTrackSelection(album.tracks, validHighlightedSongId)
const selectionFavorited = areSongsFavorite(selectedIds)
const selectionPositions = React.useMemo(
() =>
@@ -415,7 +413,6 @@ export function AlbumView({
isFavorite={isSongFavorite(track.id)}
selectedCount={selectedCount}
selectionStationArtistId={album.artist.id}
selectionFavorited={selectionFavorited}
isNowPlaying={currentSongId === track.id}
onPointerDown={handlePointerDown}
onSelect={handleRowSelect}
+21 -12
View File
@@ -37,8 +37,7 @@ type FavoritesContextValue = {
) => Promise<boolean>
toggleAlbumFavorite: (albumId: Id<"albums">) => Promise<void>
toggleArtistFavorite: (artistId: Id<"artists">) => Promise<void>
/** True when `songIds` is non-empty and every song is favorited. */
areSongsFavorite: (songIds: Iterable<string>) => boolean
favoriteSongs: (songIds: Id<"songs">[]) => Promise<void>
}
const FavoritesContext = React.createContext<FavoritesContextValue | null>(null)
@@ -131,16 +130,26 @@ export function FavoritesProvider({ children }: { children: React.ReactNode }) {
[songIds, favoriteSong, unfavoriteSong]
)
const areSongsFavorite = React.useCallback(
(ids: Iterable<string>) => {
let any = false
for (const id of ids) {
if (!songIds.has(id)) return false
any = true
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"
)
}
return any
},
[songIds]
[favoriteSongsMutation]
)
const toggleSongsFavorite = React.useCallback(
@@ -223,7 +232,7 @@ export function FavoritesProvider({ children }: { children: React.ReactNode }) {
toggleSongsFavorite,
toggleAlbumFavorite,
toggleArtistFavorite,
areSongsFavorite,
favoriteSongs,
}),
[
isSongFavorite,
@@ -233,7 +242,7 @@ export function FavoritesProvider({ children }: { children: React.ReactNode }) {
toggleSongsFavorite,
toggleAlbumFavorite,
toggleArtistFavorite,
areSongsFavorite,
favoriteSongs,
]
)
+5 -6
View File
@@ -183,8 +183,7 @@ 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 on the song's timeline (a word's start is its
* delay); playback updates only correct their drift.
* browser runs the fills; playback updates only correct their drift.
*/
function FilledWords({
words,
@@ -201,7 +200,6 @@ 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",
@@ -211,14 +209,15 @@ 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 to the start.
if (isPlaying && time < words[index].end) fill.play()
// `play` on a finished fill would rewind it.
const duration = Number(fill.effect?.getTiming().duration ?? 0)
if (isPlaying && at < duration) fill.play()
else fill.pause()
})
}, [words, time, isPlaying])
+1 -4
View File
@@ -48,8 +48,7 @@ export function OtherDownloadsView() {
[songs]
)
const { isSongFavorite, areSongsFavorite, toggleSongFavorite } =
useFavorites()
const { isSongFavorite, toggleSongFavorite } = useFavorites()
const { playFromSong, playInOrder, playShuffled } = usePlaybackActions()
const {
selectedIds,
@@ -63,7 +62,6 @@ export function OtherDownloadsView() {
() => stationArtistId(songs, selectedIds),
[songs, selectedIds]
)
const selectionFavorited = areSongsFavorite(selectedIds)
const selectionPositions = useMemo(
() =>
getSelectionRangePositions(
@@ -142,7 +140,6 @@ export function OtherDownloadsView() {
isFavorite={isSongFavorite(songs[index].id)}
selectedCount={selectedCount}
selectionStationArtistId={selectedStationArtistId}
selectionFavorited={selectionFavorited}
onPointerDown={handlePointerDown}
onSelect={handleRowSelect}
onPlay={handleRowPlay}
+2 -9
View File
@@ -74,12 +74,8 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
currentUser === undefined
? playlist.isOwner
: currentUser?._id === playlist.owner.id
const {
isSongFavorite,
areSongsFavorite,
toggleSongFavorite,
toggleSongsFavorite,
} = useFavorites()
const { isSongFavorite, toggleSongFavorite, toggleSongsFavorite } =
useFavorites()
const currentSongId = useCurrentSongId()
const {
playInOrder,
@@ -147,7 +143,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
() => stationArtistId(songs, selectedIds),
[songs, selectedIds]
)
const selectionFavorited = areSongsFavorite(selectedIds)
const selectionPositions = React.useMemo(
() =>
@@ -470,7 +465,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
onAction={handlePlaylistMediaAction}
playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
showFavorite={!isFavorites}
favorited={areSongsFavorite(playlistSongIds)}
downloaded={playlistDownloaded}
trackRowTrigger={false}
triggerVariant="secondary"
@@ -528,7 +522,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
selectionPosition={selectionPositions[index]}
selectedCount={selectedCount}
selectionStationArtistId={selectedStationArtistId}
selectionFavorited={selectionFavorited}
playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
downloadCollection={downloadRef}
showFavoriteInMenu={!isFavorites}
+1 -7
View File
@@ -244,7 +244,7 @@ export function QueuePanel() {
prepareContextMenu,
clearSelection,
} = useTrackSelection(selectionItems)
const { isSongFavorite, areSongsFavorite } = useFavorites()
const { isSongFavorite } = useFavorites()
const { runSongsAction } = useMediaActions()
/** The rows a menu acts on: the selection, else just the clicked row. */
@@ -268,11 +268,6 @@ 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) => {
@@ -458,7 +453,6 @@ 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)}
+1 -4
View File
@@ -47,8 +47,7 @@ const SONGS_PAGE_SIZE = 50
const estimateSongRowSize = () => 56
export function SongsView() {
const { isSongFavorite, areSongsFavorite, toggleSongFavorite } =
useFavorites()
const { isSongFavorite, toggleSongFavorite } = useFavorites()
const { playFromLibrarySong } = usePlaybackActions()
const [sortKey, setSortKey] = useState<SortKey>("title")
const [sortDirection, setSortDirection] = useState<SortDirection>("asc")
@@ -99,7 +98,6 @@ export function SongsView() {
() => stationArtistId(songs, selectedIds),
[songs, selectedIds]
)
const selectionFavorited = areSongsFavorite(selectedIds)
const selectionPositions = useMemo(
() =>
@@ -224,7 +222,6 @@ export function SongsView() {
isFavorite={isSongFavorite(songs[index].id)}
selectedCount={selectedCount}
selectionStationArtistId={selectedStationArtistId}
selectionFavorited={selectionFavorited}
onPointerDown={handlePointerDown}
onSelect={handleRowSelect}
onPlay={handleRowPlay}
+1 -7
View File
@@ -68,8 +68,6 @@ 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`. */
@@ -270,7 +268,6 @@ function TrackRowComponent({
isDragging = false,
selectedCount = 0,
selectionStationArtistId,
selectionFavorited,
playlistLabel,
showFavoriteInMenu = true,
removeLabel,
@@ -348,10 +345,7 @@ function TrackRowComponent({
onAction: (action) => onMediaAction(action, rowId),
playlistLabel,
showFavorite: showFavoriteInMenu,
favorited:
inRange && selectedCount > 0
? (selectionFavorited ?? isFavorite)
: isFavorite,
favorited: isFavorite,
navigation: {
artist: { id: song.artist.id },
album: { id: song.album.id },
+3 -6
View File
@@ -26,8 +26,7 @@ function songsTitle(songIds: readonly string[]) {
export function useMediaActions() {
const { openAddToPlaylist, openAddArtistToPlaylist } = useAddToPlaylist()
const { areSongsFavorite, toggleSongsFavorite, toggleArtistFavorite } =
useFavorites()
const { favoriteSongs, toggleArtistFavorite } = useFavorites()
const { runQueueAction, createStation } = useQueueMediaActions()
const convex = useConvex()
const cacheScope = useCacheScope()
@@ -45,8 +44,7 @@ export function useMediaActions() {
if (stationArtist) void createStation(stationArtist)
break
case "favorite":
// Unfavorite only when every song already is, matching the menu label.
void toggleSongsFavorite(songIds, areSongsFavorite(songIds))
void favoriteSongs(songIds)
break
case "playlist":
openAddToPlaylist(songIds)
@@ -75,8 +73,7 @@ export function useMediaActions() {
},
[
createStation,
areSongsFavorite,
toggleSongsFavorite,
favoriteSongs,
openAddToPlaylist,
runQueueAction,
requestDownload,
-93
View File
@@ -1,93 +0,0 @@
/**
* 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
}
+27 -54
View File
@@ -5,8 +5,6 @@
* 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
@@ -18,15 +16,11 @@ export type LyricLine = {
text: string
/** Seconds; `null` for plain lyrics. */
start: number | null
/**
* The line's words as they are sung. Line-timed lyrics get estimated
* ones (see `estimateWords`); plain lyrics have none.
*/
/** Set only on word-timed lines. */
words: LyricWord[] | null
}
export type Lyrics = {
/** How the source was timed, whatever `words` were estimated. */
synced: "none" | "line" | "word"
lines: LyricLine[]
}
@@ -35,8 +29,6 @@ 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(":", "."))
@@ -115,31 +107,10 @@ export function parseLyrics(raw: string): Lyrics | null {
}
lines.sort((a, b) => a.start! - b.start!)
if (lines.length === 0) return null
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 }
})
})
return {
synced: lines.every((line) => line.words) ? "word" : "line",
lines,
}
}
/** The text without timestamps, one line per row, for search and snippets. */
@@ -214,32 +185,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
/**
* 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
/** Whether the line holds the query as typed, not just its words. */
exact: boolean
}
/**
* 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.
* 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.
*/
export function matchLyrics(plain: string, query: string): LyricsMatch | null {
const needle = query.trim().toLowerCase()
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
}
const terms = searchTerms(needle)
const last = terms.at(-1)
if (!needle || last === undefined) return null
let loose: LyricsMatch | null = null
let loose: string | null = null
for (const line of plain.split("\n")) {
const column = line.toLowerCase().indexOf(needle)
if (column !== -1) {
@@ -247,13 +218,15 @@ export function matchLyrics(plain: string, query: string): LyricsMatch | null {
column > SNIPPET_LEAD
? `…${line.slice(column - SNIPPET_LEAD).trimStart()}`
: line.trim()
return { snippet, score: 2 }
return { snippet, exact: true }
}
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 }
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()
}
}
return loose
return loose === null ? null : { snippet: loose, exact: false }
}
+10 -14
View File
@@ -1,5 +1,3 @@
import { matchWords, searchWords } from "./fuzzy-search"
type SearchableSong = {
id: string
title: string
@@ -8,9 +6,9 @@ type SearchableSong = {
}
/**
* 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.
* Case-insensitive match on title, artist, or album, plus the songs in
* `lyricsMatches` (from `api.lyrics.matchingSongIds`). A blank query keeps
* every song.
*/
export function filterSongs<T extends SearchableSong>(
songs: T[],
@@ -21,14 +19,12 @@ export function filterSongs<T extends SearchableSong>(
if (!normalized) {
return songs
}
const terms = searchWords(normalized)
const byLyrics = new Set(lyricsMatches)
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
)
})
return songs.filter(
(song) =>
byLyrics.has(song.id) ||
[song.title, song.artist.name, song.album.title].some((value) =>
value.toLowerCase().includes(normalized)
)
)
}
+11 -27
View File
@@ -27,7 +27,6 @@ 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,
@@ -619,16 +618,7 @@ export const browseArtistDetail = query({
},
})
/**
* 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 {
function matchScore(text: string, query: string): number {
const lower = text.toLowerCase()
if (lower === query) {
return 100
@@ -642,20 +632,15 @@ function matchScore(
if (lower.includes(query)) {
return 40
}
const words = matchWords(searchWords(text), terms)
if (words === "exact") {
return 30
}
return words === "fuzzy" ? 20 : 0
return 0
}
function matchScoreSongArtists(
artist: string | string[],
query: string,
terms: readonly string[]
query: string
): number {
return getSongArtistNames(artist).reduce(
(best, name) => Math.max(best, matchScore(name, query, terms)),
(best, name) => Math.max(best, matchScore(name, query)),
0
)
}
@@ -673,7 +658,6 @@ 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: [],
@@ -694,7 +678,7 @@ export const searchLibrary = query({
.map((artist) => ({
kind: "artist" as const,
item: toBrowseArtist(artist),
score: matchScore(artist.name, queryText, terms),
score: matchScore(artist.name, queryText),
}))
.filter((result) => result.score > 0)
.sort(
@@ -708,8 +692,8 @@ export const searchLibrary = query({
return []
}
const score = Math.max(
matchScore(album.name, queryText, terms),
matchScore(artist.name, queryText, terms)
matchScore(album.name, queryText),
matchScore(artist.name, queryText)
)
if (score === 0) {
return []
@@ -734,10 +718,10 @@ export const searchLibrary = query({
return []
}
const score = Math.max(
matchScore(song.name, queryText, terms),
matchScoreSongArtists(song.artist, queryText, terms),
matchScore(album.name, queryText, terms),
matchScore(albumArtist.name, queryText, terms)
matchScore(song.name, queryText),
matchScoreSongArtists(song.artist, queryText),
matchScore(album.name, queryText),
matchScore(albumArtist.name, queryText)
)
if (score === 0) {
return []
+13 -13
View File
@@ -62,10 +62,10 @@ export async function deleteSongLyrics(ctx: MutationCtx, songId: Id<"songs">) {
}
/**
* 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.
* 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.
*/
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(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 }))
.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 }))
}
/** The song's lyrics tag (see `client/lyrics.ts`), or null without lyrics. */