392 lines
10 KiB
TypeScript
392 lines
10 KiB
TypeScript
import { useMutation } from "convex/react"
|
|
import { Image } from "expo-image"
|
|
import * as ImagePicker from "expo-image-picker"
|
|
import { router, Stack, useLocalSearchParams } from "expo-router"
|
|
import { useMemo, useState, type ReactNode } from "react"
|
|
import {
|
|
Pressable,
|
|
ScrollView,
|
|
StyleSheet,
|
|
Text,
|
|
useWindowDimensions,
|
|
View,
|
|
} from "react-native"
|
|
|
|
import { CoverImage } from "@/components/cover-image"
|
|
import { Button, LoadingView } from "@/components/ui/primitives"
|
|
import { useServerConfig } from "@/contexts/server-config"
|
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
|
import { showError } from "@/lib/toast"
|
|
import { albumCoverUrl, playlistCoverUrl } from "@/lib/urls"
|
|
import { radius, spacing, useThemeColors } from "@/lib/theme"
|
|
import { api } from "@otunes/convex/_generated/api"
|
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
|
import {
|
|
COVER_GRID_ALBUMS,
|
|
playlistCoverAlbums,
|
|
randomPlaylistCovers,
|
|
} from "@otunes/convex/client/playlist-cover"
|
|
|
|
type Choice =
|
|
| { kind: "current" }
|
|
| { kind: "albums"; albumIds: Id<"albums">[] }
|
|
| { kind: "upload"; uri: string; image: string }
|
|
|
|
const STRIP_GAP = spacing.sm
|
|
/** Selection border and padding around each thumb, both sides. */
|
|
const THUMB_CHROME = 6
|
|
|
|
/**
|
|
* Full screen cover editor for a playlist owner: a large preview of the
|
|
* selected cover, the current cover pinned apart from four random album
|
|
* grids, and Save in the header. Opened from the playlist's menu.
|
|
*/
|
|
export default function PlaylistCoverScreen() {
|
|
const { id } = useLocalSearchParams<{ id: string }>()
|
|
const playlistId = id as Id<"playlists">
|
|
const playlist = useCachedQuery(api.playlists.browsePlaylistDetail, {
|
|
id: playlistId,
|
|
})
|
|
const { config } = useServerConfig()
|
|
const colors = useThemeColors()
|
|
const { width } = useWindowDimensions()
|
|
const setCoverAlbums = useMutation(api.playlists.setPlaylistCoverAlbums)
|
|
const uploadCover = useMutation(api.playlists.uploadPlaylistCover)
|
|
|
|
const albums = useMemo(
|
|
() => (playlist ? playlistCoverAlbums(playlist.songs) : []),
|
|
[playlist]
|
|
)
|
|
const [options, setOptions] = useState<Id<"albums">[][] | null>(null)
|
|
const [selected, setSelected] = useState<Choice | null>(null)
|
|
const [saving, setSaving] = useState(false)
|
|
|
|
// Draw options once the songs arrive.
|
|
if (options === null && playlist) {
|
|
setOptions(randomPlaylistCovers(albums))
|
|
}
|
|
|
|
const hasCurrent = playlist?.cover != null
|
|
const choice: Choice | null =
|
|
selected ??
|
|
(hasCurrent
|
|
? { kind: "current" }
|
|
: options?.[0]
|
|
? { kind: "albums", albumIds: options[0] }
|
|
: null)
|
|
|
|
async function pickImage() {
|
|
const result = await ImagePicker.launchImageLibraryAsync({
|
|
mediaTypes: ["images"],
|
|
allowsEditing: true,
|
|
aspect: [1, 1],
|
|
quality: 0.7,
|
|
base64: true,
|
|
})
|
|
const asset = result.canceled ? undefined : result.assets[0]
|
|
if (!asset?.base64) return
|
|
setSelected({
|
|
kind: "upload",
|
|
uri: asset.uri,
|
|
image: `data:${asset.mimeType ?? "image/jpeg"};base64,${asset.base64}`,
|
|
})
|
|
}
|
|
|
|
async function save() {
|
|
if (!choice || choice.kind === "current") {
|
|
router.back()
|
|
return
|
|
}
|
|
setSaving(true)
|
|
try {
|
|
if (choice.kind === "albums") {
|
|
await setCoverAlbums({ playlistId, albumIds: choice.albumIds })
|
|
} else {
|
|
await uploadCover({ playlistId, image: choice.image })
|
|
}
|
|
router.back()
|
|
} catch (error) {
|
|
showError(
|
|
error instanceof Error ? error.message : "Failed to change cover"
|
|
)
|
|
setSaving(false)
|
|
}
|
|
}
|
|
|
|
const header = (
|
|
<Stack.Screen
|
|
options={{
|
|
headerLeft: () => (
|
|
<HeaderButton label="Cancel" onPress={() => router.back()} />
|
|
),
|
|
headerRight: () => (
|
|
<HeaderButton
|
|
label="Save"
|
|
bold
|
|
disabled={saving || !choice}
|
|
onPress={() => void save()}
|
|
/>
|
|
),
|
|
}}
|
|
/>
|
|
)
|
|
|
|
if (!playlist || !config || !options) {
|
|
return (
|
|
<>
|
|
{header}
|
|
<LoadingView />
|
|
</>
|
|
)
|
|
}
|
|
|
|
const serverUrl = config.serverUrl
|
|
const currentUri = playlistCoverUrl(serverUrl, playlistId, playlist.cover)
|
|
const previewSize = Math.min(width - spacing.lg * 2, 360)
|
|
// One row: current | uploaded? | options, thumbs at most 72pt.
|
|
const thumbCount =
|
|
options.length + (hasCurrent ? 1 : 0) + (choice?.kind === "upload" ? 1 : 0)
|
|
const rowItems = thumbCount + (hasCurrent ? 1 : 0)
|
|
const thumbSize = Math.min(
|
|
72,
|
|
Math.floor(
|
|
(width - spacing.lg * 2 - STRIP_GAP * (rowItems - 1) - 1) /
|
|
Math.max(thumbCount, 1)
|
|
) - THUMB_CHROME
|
|
)
|
|
|
|
function renderChoice(item: Choice, size: number) {
|
|
if (item.kind === "current") {
|
|
return (
|
|
<CoverImage
|
|
uri={currentUri}
|
|
hasCover
|
|
style={{ width: size, height: size }}
|
|
/>
|
|
)
|
|
}
|
|
if (item.kind === "upload") {
|
|
return (
|
|
<Image
|
|
source={{ uri: item.uri }}
|
|
style={{ width: size, height: size }}
|
|
/>
|
|
)
|
|
}
|
|
return (
|
|
<AlbumGrid serverUrl={serverUrl} albumIds={item.albumIds} size={size} />
|
|
)
|
|
}
|
|
|
|
const isSelected = (item: Choice) =>
|
|
choice?.kind === item.kind &&
|
|
(item.kind !== "albums" ||
|
|
(choice.kind === "albums" && choice.albumIds === item.albumIds))
|
|
|
|
return (
|
|
<ScrollView
|
|
style={{ backgroundColor: colors.background }}
|
|
contentContainerStyle={styles.content}
|
|
>
|
|
{header}
|
|
<View
|
|
style={[
|
|
styles.preview,
|
|
{
|
|
width: previewSize,
|
|
height: previewSize,
|
|
backgroundColor: colors.coverPlaceholder,
|
|
},
|
|
]}
|
|
>
|
|
{choice ? renderChoice(choice, previewSize) : null}
|
|
</View>
|
|
|
|
<View style={styles.strip}>
|
|
{hasCurrent ? (
|
|
<>
|
|
<Thumb
|
|
size={thumbSize}
|
|
selected={isSelected({ kind: "current" })}
|
|
label="Current cover"
|
|
onPress={() => setSelected({ kind: "current" })}
|
|
>
|
|
{renderChoice({ kind: "current" }, thumbSize)}
|
|
</Thumb>
|
|
<View
|
|
style={[styles.separator, { backgroundColor: colors.border }]}
|
|
/>
|
|
</>
|
|
) : null}
|
|
{choice?.kind === "upload" ? (
|
|
<Thumb size={thumbSize} selected label="Uploaded image">
|
|
{renderChoice(choice, thumbSize)}
|
|
</Thumb>
|
|
) : null}
|
|
{options.map((albumIds) => {
|
|
const item: Choice = { kind: "albums", albumIds }
|
|
return (
|
|
<Thumb
|
|
key={albumIds.join(",")}
|
|
size={thumbSize}
|
|
selected={isSelected(item)}
|
|
label="Album cover option"
|
|
onPress={() => setSelected(item)}
|
|
>
|
|
{renderChoice(item, thumbSize)}
|
|
</Thumb>
|
|
)
|
|
})}
|
|
</View>
|
|
|
|
{albums.length === 0 ? (
|
|
<Text style={{ color: colors.mutedForeground, textAlign: "center" }}>
|
|
No album artwork in this playlist yet.
|
|
</Text>
|
|
) : null}
|
|
|
|
<View style={styles.actions}>
|
|
{albums.length >= COVER_GRID_ALBUMS ? (
|
|
<Button
|
|
title="Shuffle"
|
|
icon="shuffle"
|
|
variant="secondary"
|
|
onPress={() => {
|
|
setOptions(randomPlaylistCovers(albums))
|
|
if (selected?.kind === "albums") setSelected(null)
|
|
}}
|
|
/>
|
|
) : null}
|
|
<Button
|
|
title="Upload"
|
|
icon="arrow-up"
|
|
variant="secondary"
|
|
onPress={() => void pickImage()}
|
|
/>
|
|
</View>
|
|
</ScrollView>
|
|
)
|
|
}
|
|
|
|
function HeaderButton({
|
|
label,
|
|
bold = false,
|
|
disabled = false,
|
|
onPress,
|
|
}: {
|
|
label: string
|
|
bold?: boolean
|
|
disabled?: boolean
|
|
onPress: () => void
|
|
}) {
|
|
const colors = useThemeColors()
|
|
return (
|
|
<Pressable
|
|
accessibilityRole="button"
|
|
hitSlop={8}
|
|
disabled={disabled}
|
|
onPress={onPress}
|
|
style={{ opacity: disabled ? 0.4 : 1, paddingHorizontal: spacing.xs }}
|
|
>
|
|
<Text
|
|
style={{
|
|
color: colors.foreground,
|
|
fontSize: 17,
|
|
fontWeight: bold ? "600" : "400",
|
|
}}
|
|
>
|
|
{label}
|
|
</Text>
|
|
</Pressable>
|
|
)
|
|
}
|
|
|
|
function Thumb({
|
|
size,
|
|
selected,
|
|
label,
|
|
onPress,
|
|
children,
|
|
}: {
|
|
size: number
|
|
selected: boolean
|
|
label: string
|
|
onPress?: () => void
|
|
children: ReactNode
|
|
}) {
|
|
const colors = useThemeColors()
|
|
return (
|
|
<Pressable
|
|
accessibilityRole="button"
|
|
accessibilityLabel={label}
|
|
accessibilityState={{ selected }}
|
|
onPress={onPress}
|
|
style={[
|
|
styles.thumb,
|
|
{
|
|
width: size + THUMB_CHROME,
|
|
height: size + THUMB_CHROME,
|
|
borderColor: selected ? colors.foreground : "transparent",
|
|
},
|
|
]}
|
|
>
|
|
<View style={styles.thumbInner}>{children}</View>
|
|
</Pressable>
|
|
)
|
|
}
|
|
|
|
/** A generated cover option: one album alone, or four tiled 2x2. */
|
|
function AlbumGrid({
|
|
serverUrl,
|
|
albumIds,
|
|
size,
|
|
}: {
|
|
serverUrl: string
|
|
albumIds: Id<"albums">[]
|
|
size: number
|
|
}) {
|
|
const tile = albumIds.length > 1 ? size / 2 : size
|
|
return (
|
|
<View
|
|
style={{
|
|
width: size,
|
|
height: size,
|
|
flexDirection: "row",
|
|
flexWrap: "wrap",
|
|
}}
|
|
>
|
|
{albumIds.map((albumId) => (
|
|
<CoverImage
|
|
key={albumId}
|
|
uri={albumCoverUrl(serverUrl, albumId)}
|
|
hasCover
|
|
style={{ width: tile, height: tile }}
|
|
/>
|
|
))}
|
|
</View>
|
|
)
|
|
}
|
|
|
|
const styles = StyleSheet.create({
|
|
content: {
|
|
alignItems: "center",
|
|
gap: spacing.xl,
|
|
padding: spacing.lg,
|
|
},
|
|
preview: { borderRadius: radius.lg, overflow: "hidden" },
|
|
strip: {
|
|
flexDirection: "row",
|
|
alignItems: "center",
|
|
justifyContent: "center",
|
|
gap: STRIP_GAP,
|
|
},
|
|
separator: { width: StyleSheet.hairlineWidth, alignSelf: "stretch" },
|
|
thumb: {
|
|
borderWidth: 2,
|
|
borderRadius: radius.sm + 2,
|
|
padding: 1,
|
|
},
|
|
thumbInner: { flex: 1, borderRadius: radius.sm, overflow: "hidden" },
|
|
actions: { flexDirection: "row", gap: spacing.sm },
|
|
})
|