feat(smart): smart playlists made for everybody, without making them
- A fixed set that is there with no setup: recently added, never played, most played, not heard for a while, high quality files and long tracks. The rules are the same for everyone and are worked out on each one's own library and history, like the mixes; nothing is stored, so they follow the library.
- GET /smart-playlists/suggested, GET /smart-playlists/suggested/{key}/tracks and POST /smart-playlists/suggested/{key}/playlist.
- The Smart playlists page begins with them, with names and descriptions in the language of the page. A suggested one can be played, shuffled again, kept as a playlist, or made one's own: a copy of its rules opens in the editor.
This commit is contained in:
parent
b598842c6d
commit
17f70d582d
8 changed files with 920 additions and 28 deletions
183
web/src/api/schema.d.ts
vendored
183
web/src/api/schema.d.ts
vendored
|
|
@ -962,6 +962,78 @@ export interface paths {
|
|||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/smart-playlists/suggested": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
/**
|
||||
* The smart playlists Sonda makes for you
|
||||
* @description A fixed set that is there without anybody making it, the same rules for everyone and worked out on your
|
||||
* own library and history: `recently-added`, `never-played`, `most-played`, `forgotten` (played once, but not
|
||||
* in the last 90 days), `high-quality` (bitrate of 900 kbps or more) and `long-tracks` (6 minutes or more).
|
||||
* Nothing is stored for them. A client says their names in its own language from the `key`. To change one,
|
||||
* make a smart playlist of your own from its rules with `POST /smart-playlists`.
|
||||
*/
|
||||
get: operations["listSuggestedSmartPlaylists"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/smart-playlists/suggested/{key}/tracks": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
/** @description A key from `GET /smart-playlists/suggested`. */
|
||||
key: components["parameters"]["SuggestedKey"];
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
/**
|
||||
* The songs of a suggested smart playlist, now
|
||||
* @description Works the rules out for you, as `GET /smart-playlists/{id}/tracks` does for yours. With the random order
|
||||
* the songs stay the same all day, and another `variant` gives other ones.
|
||||
*/
|
||||
get: operations["getSuggestedSmartPlaylistTracks"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/smart-playlists/suggested/{key}/playlist": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
/** @description A key from `GET /smart-playlists/suggested`. */
|
||||
key: components["parameters"]["SuggestedKey"];
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Keep a suggested smart playlist as a playlist
|
||||
* @description Makes a playlist of your own with the songs that `variant` gives now, in the same order. It is a copy,
|
||||
* and is yours to edit. The body is optional; without a name the playlist is called by the `key`.
|
||||
*/
|
||||
post: operations["saveSuggestedSmartPlaylist"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/smart-playlists/{id}": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
|
@ -2312,6 +2384,16 @@ export interface components {
|
|||
min_duration_sec?: number;
|
||||
max_duration_sec?: number;
|
||||
};
|
||||
SuggestedSmartPlaylist: {
|
||||
/** @enum {string} */
|
||||
key: "recently-added" | "never-played" | "most-played" | "forgotten" | "high-quality" | "long-tracks";
|
||||
rules: components["schemas"]["SmartRules"];
|
||||
sort: components["schemas"]["SmartSort"];
|
||||
limit: number;
|
||||
};
|
||||
SuggestedSmartPlaylistList: {
|
||||
items: components["schemas"]["SuggestedSmartPlaylist"][];
|
||||
};
|
||||
/**
|
||||
* @description A tie always goes to the lower song id.
|
||||
* @enum {string}
|
||||
|
|
@ -2727,6 +2809,15 @@ export interface components {
|
|||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
/** @description No such suggested smart playlist (`suggested_not_found`). */
|
||||
SuggestedNotFound: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
/** @description No such smart playlist, or it is somebody else's (`smart_playlist_not_found`). */
|
||||
SmartPlaylistNotFound: {
|
||||
headers: {
|
||||
|
|
@ -2788,6 +2879,8 @@ export interface components {
|
|||
/** @description Page size. 50 when absent or 0; values above 200 are lowered to 200. */
|
||||
Limit: number;
|
||||
Offset: number;
|
||||
/** @description A key from `GET /smart-playlists/suggested`. */
|
||||
SuggestedKey: "recently-added" | "never-played" | "most-played" | "forgotten" | "high-quality" | "long-tracks";
|
||||
/** @description `favourites`, `rediscover`, `unheard` or `genre:<name>` (percent-encoded). */
|
||||
MixId: string;
|
||||
/** @description Only items with a playable file in this library. */
|
||||
|
|
@ -4344,6 +4437,96 @@ export interface operations {
|
|||
401: components["responses"]["Unauthorized"];
|
||||
};
|
||||
};
|
||||
listSuggestedSmartPlaylists: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description The suggested smart playlists. */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["SuggestedSmartPlaylistList"];
|
||||
};
|
||||
};
|
||||
401: components["responses"]["Unauthorized"];
|
||||
};
|
||||
};
|
||||
getSuggestedSmartPlaylistTracks: {
|
||||
parameters: {
|
||||
query?: {
|
||||
/** @description Other songs for the random order, from 0 (the songs of the day) up. */
|
||||
variant?: number;
|
||||
};
|
||||
header?: never;
|
||||
path: {
|
||||
/** @description A key from `GET /smart-playlists/suggested`. */
|
||||
key: components["parameters"]["SuggestedKey"];
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description The songs. */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["SmartTracks"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["InvalidInput"];
|
||||
401: components["responses"]["Unauthorized"];
|
||||
404: components["responses"]["SuggestedNotFound"];
|
||||
};
|
||||
};
|
||||
saveSuggestedSmartPlaylist: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
/** @description A key from `GET /smart-playlists/suggested`. */
|
||||
key: components["parameters"]["SuggestedKey"];
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["SaveSmartPlaylist"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description The playlist. */
|
||||
201: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Playlist"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["InvalidInput"];
|
||||
401: components["responses"]["Unauthorized"];
|
||||
404: components["responses"]["SuggestedNotFound"];
|
||||
409: components["responses"]["PlaylistLimit"];
|
||||
/** @description The rules give no songs to save (`smart_playlist_empty`). */
|
||||
422: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
getSmartPlaylist: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
|
|
|||
|
|
@ -51,6 +51,40 @@ export function useSmartPreview(input: SmartInput) {
|
|||
})
|
||||
}
|
||||
|
||||
/** A smart playlist that Sonda makes for everybody: a key (its name comes from the texts of the page) and its rules. */
|
||||
export interface SuggestedSmart extends SmartInput {
|
||||
key: string
|
||||
}
|
||||
|
||||
/** The smart playlists that are there without making them. */
|
||||
export function useSuggested() {
|
||||
return useQuery({
|
||||
queryKey: ['smart-suggested'],
|
||||
queryFn: () => api.get<{ items: SuggestedSmart[] }>('/smart-playlists/suggested').then((r) => r.items),
|
||||
staleTime: 10 * 60_000,
|
||||
})
|
||||
}
|
||||
|
||||
/** The songs of a suggested one now. The songs on screen stay until the next ones arrive. */
|
||||
export function useSuggestedTracks(key: string, variant: number) {
|
||||
return useQuery({
|
||||
queryKey: ['smart-suggested-tracks', key, variant],
|
||||
queryFn: () =>
|
||||
api.get<{ variant: number; tracks: Track[] }>(`/smart-playlists/suggested/${encodeURIComponent(key)}/tracks`, variant > 0 ? { variant } : undefined),
|
||||
placeholderData: keepPreviousData,
|
||||
})
|
||||
}
|
||||
|
||||
/** Keeps the songs of a suggested one on screen as a normal playlist of mine. */
|
||||
export function useSaveSuggested() {
|
||||
const client = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: ({ key, ...body }: { key: string; name: string; variant: number }) =>
|
||||
api.post<Playlist>(`/smart-playlists/suggested/${encodeURIComponent(key)}/playlist`, body),
|
||||
onSuccess: () => refreshPlaylists(client),
|
||||
})
|
||||
}
|
||||
|
||||
/** The genres of the library with their songs, the biggest first. */
|
||||
export function useGenres() {
|
||||
return useQuery({
|
||||
|
|
|
|||
|
|
@ -529,6 +529,7 @@
|
|||
"mix_not_found": "This mix is not available now.",
|
||||
"mix_empty": "This mix has no songs to keep.",
|
||||
"smart_playlist_not_found": "This smart playlist does not exist.",
|
||||
"suggested_not_found": "This suggested smart playlist does not exist.",
|
||||
"smart_playlist_empty": "These rules give no songs to keep."
|
||||
},
|
||||
"playlists": {
|
||||
|
|
@ -580,6 +581,18 @@
|
|||
"open": "Open the playlist"
|
||||
},
|
||||
"smart": {
|
||||
"forYou": "Made for you",
|
||||
"mine": "My smart playlists",
|
||||
"makeMine": "Make it mine",
|
||||
"notFoundSuggested": "This suggested smart playlist does not exist.",
|
||||
"suggested": {
|
||||
"recently-added": { "name": "Recently added", "description": "Songs added in the last 30 days, the newest first." },
|
||||
"never-played": { "name": "Never played", "description": "Songs you have never listened to." },
|
||||
"most-played": { "name": "Most played", "description": "The songs you have played most." },
|
||||
"forgotten": { "name": "Not heard in a while", "description": "Songs you played once, but not in the last 90 days." },
|
||||
"high-quality": { "name": "High quality", "description": "Files of 900 kbps or more." },
|
||||
"long-tracks": { "name": "Long tracks", "description": "Songs of 6 minutes or more." }
|
||||
},
|
||||
"empty": "You have no smart playlists yet. A smart playlist is a set of rules, like “rock I have never played”, and its songs change by themselves.",
|
||||
"new": "New smart playlist",
|
||||
"meta_one": "{{sort}} · up to {{count}} song",
|
||||
|
|
|
|||
|
|
@ -529,6 +529,7 @@
|
|||
"mix_not_found": "Questo mix ora non è disponibile.",
|
||||
"mix_empty": "Questo mix non ha brani da salvare.",
|
||||
"smart_playlist_not_found": "Questa playlist smart non esiste.",
|
||||
"suggested_not_found": "Questa playlist smart suggerita non esiste.",
|
||||
"smart_playlist_empty": "Queste regole non danno brani da salvare."
|
||||
},
|
||||
"playlists": {
|
||||
|
|
@ -580,6 +581,18 @@
|
|||
"open": "Apri la playlist"
|
||||
},
|
||||
"smart": {
|
||||
"forYou": "Fatte per te",
|
||||
"mine": "Le mie playlist smart",
|
||||
"makeMine": "Fanne una tua",
|
||||
"notFoundSuggested": "Questa playlist smart suggerita non esiste.",
|
||||
"suggested": {
|
||||
"recently-added": { "name": "Aggiunti da poco", "description": "Brani aggiunti negli ultimi 30 giorni, i più nuovi per primi." },
|
||||
"never-played": { "name": "Mai ascoltati", "description": "Brani che non hai mai ascoltato." },
|
||||
"most-played": { "name": "I più ascoltati", "description": "I brani che hai ascoltato di più." },
|
||||
"forgotten": { "name": "Non li senti da un po'", "description": "Brani ascoltati almeno una volta, ma non negli ultimi 90 giorni." },
|
||||
"high-quality": { "name": "Alta qualità", "description": "File da 900 kbps o più." },
|
||||
"long-tracks": { "name": "Brani lunghi", "description": "Brani da 6 minuti o più." }
|
||||
},
|
||||
"empty": "Non hai ancora playlist smart. Una playlist smart è un insieme di regole, come «rock che non ho mai ascoltato», e i suoi brani cambiano da soli.",
|
||||
"new": "Nuova playlist smart",
|
||||
"meta_one": "{{sort}} · fino a {{count}} brano",
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
import { Plus } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { useSmartPlaylists } from '@/api/smart'
|
||||
import { useSmartPlaylists, useSuggested } from '@/api/smart'
|
||||
import { CARD_GRID } from '@/components/cards'
|
||||
import LoadMore from '@/components/LoadMore'
|
||||
import Section from '@/components/Section'
|
||||
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
|
||||
import { buttonVariants } from '@/components/ui/button'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
|
@ -11,6 +13,7 @@ import { cn } from '@/lib/utils'
|
|||
export default function SmartPlaylistsPage() {
|
||||
const { t } = useTranslation()
|
||||
const query = useSmartPlaylists()
|
||||
const suggested = useSuggested()
|
||||
const items = query.data?.items ?? []
|
||||
|
||||
return (
|
||||
|
|
@ -23,29 +26,44 @@ export default function SmartPlaylistsPage() {
|
|||
</Link>
|
||||
</div>
|
||||
|
||||
{query.isError ? (
|
||||
<ErrorMessage error={query.error} onRetry={() => query.refetch()} />
|
||||
) : query.isPending ? (
|
||||
<Loading />
|
||||
) : items.length === 0 ? (
|
||||
<EmptyMessage>{t('smart.empty')}</EmptyMessage>
|
||||
) : (
|
||||
<>
|
||||
<ul className="flex flex-col">
|
||||
{items.map((p) => (
|
||||
<li key={p.id}>
|
||||
<Link to={`/smart-playlists/${p.id}`} className="flex min-h-14 items-center justify-between gap-4 rounded-lg px-4 hover:bg-secondary">
|
||||
<span className="truncate font-semibold">{p.name}</span>
|
||||
<span className="flex-none text-sm text-muted-foreground">
|
||||
{t('smart.meta', { count: p.limit, sort: t(`smart.sort.${p.sort}`) })}
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
{suggested.data && (
|
||||
<Section title={t('smart.forYou')}>
|
||||
<div className={CARD_GRID}>
|
||||
{suggested.data.map((s) => (
|
||||
<Link key={s.key} to={`/smart-playlists/suggested/${s.key}`} className="flex min-h-28 flex-col justify-between gap-3 rounded-xl bg-card p-4 text-card-foreground hover:bg-secondary">
|
||||
<span className="text-lg leading-tight font-bold">{t(`smart.suggested.${s.key}.name`)}</span>
|
||||
<span className="line-clamp-3 text-sm text-muted-foreground">{t(`smart.suggested.${s.key}.description`)}</span>
|
||||
</Link>
|
||||
))}
|
||||
</ul>
|
||||
<LoadMore query={query} />
|
||||
</>
|
||||
</div>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
<Section title={t('smart.mine')}>
|
||||
{query.isError ? (
|
||||
<ErrorMessage error={query.error} onRetry={() => query.refetch()} />
|
||||
) : query.isPending ? (
|
||||
<Loading />
|
||||
) : items.length === 0 ? (
|
||||
<EmptyMessage>{t('smart.empty')}</EmptyMessage>
|
||||
) : (
|
||||
<>
|
||||
<ul className="flex flex-col">
|
||||
{items.map((p) => (
|
||||
<li key={p.id}>
|
||||
<Link to={`/smart-playlists/${p.id}`} className="flex min-h-14 items-center justify-between gap-4 rounded-lg px-4 hover:bg-secondary">
|
||||
<span className="truncate font-semibold">{p.name}</span>
|
||||
<span className="flex-none text-sm text-muted-foreground">
|
||||
{t('smart.meta', { count: p.limit, sort: t(`smart.sort.${p.sort}`) })}
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<LoadMore query={query} />
|
||||
</>
|
||||
)}
|
||||
</Section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
126
web/src/pages/SuggestedSmartPage.tsx
Normal file
126
web/src/pages/SuggestedSmartPage.tsx
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
import { ListPlus, Play, Shuffle, Wand2 } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom'
|
||||
import { ApiError } from '@/api/client'
|
||||
import { useCreateSmart, useSaveSuggested, useSuggested, useSuggestedTracks } from '@/api/smart'
|
||||
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
|
||||
import TrackList from '@/components/TrackList'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { errorMessageKey } from '@/i18n'
|
||||
import { formatTime } from '@/lib/time'
|
||||
import { usePlayer } from '@/player/store'
|
||||
import { describeRules } from './smartRules'
|
||||
|
||||
/** One of the smart playlists that are there without making them: its songs, and a way to make it one's own. */
|
||||
export default function SuggestedSmartPage() {
|
||||
const key = useParams().key ?? ''
|
||||
return <SuggestedView key={key} name={key} />
|
||||
}
|
||||
|
||||
function errorLine(t: (key: string) => string, error: unknown) {
|
||||
return t(errorMessageKey(error instanceof ApiError ? error.code : 'unknown'))
|
||||
}
|
||||
|
||||
function SuggestedView({ name: key }: { name: string }) {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const [variant, setVariant] = useState(0)
|
||||
const list = useSuggested()
|
||||
const query = useSuggestedTracks(key, variant)
|
||||
const save = useSaveSuggested()
|
||||
const make = useCreateSmart()
|
||||
const playTracks = usePlayer((s) => s.playTracks)
|
||||
|
||||
if (query.isError) {
|
||||
if (query.error instanceof ApiError && query.error.status === 404) return <EmptyMessage>{t('smart.notFoundSuggested')}</EmptyMessage>
|
||||
return <ErrorMessage error={query.error} onRetry={() => query.refetch()} />
|
||||
}
|
||||
const suggested = list.data?.find((s) => s.key === key)
|
||||
if (list.isError) return <ErrorMessage error={list.error} onRetry={() => list.refetch()} />
|
||||
if (!suggested) return list.isPending ? <Loading /> : <EmptyMessage>{t('smart.notFoundSuggested')}</EmptyMessage>
|
||||
|
||||
const title = t(`smart.suggested.${key}.name`)
|
||||
const description = t(`smart.suggested.${key}.description`)
|
||||
const tracks = query.data?.tracks ?? []
|
||||
const shown = query.data?.variant ?? 0
|
||||
const waiting = query.isPlaceholderData
|
||||
const duration = tracks.reduce((sum, track) => sum + track.duration_ms, 0)
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-8">
|
||||
<header className="flex flex-col gap-3">
|
||||
<h1 className="text-4xl font-extrabold tracking-tight md:text-6xl">{title}</h1>
|
||||
<p className="max-w-2xl text-muted-foreground">{description}</p>
|
||||
<ul aria-label={t('smart.rulesTitle')} className="flex flex-wrap gap-2">
|
||||
{describeRules(t, suggested.rules).map((line) => (
|
||||
<li key={line} className="rounded-md bg-secondary px-3 py-1 text-sm font-semibold">
|
||||
{line}
|
||||
</li>
|
||||
))}
|
||||
<li className="rounded-md bg-secondary px-3 py-1 text-sm font-semibold">{t(`smart.sort.${suggested.sort}`)}</li>
|
||||
</ul>
|
||||
{query.data && <p className="text-muted-foreground">{t('smart.songs', { count: tracks.length, duration: formatTime(duration) })}</p>}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button className="h-12 gap-2 rounded-md px-6" disabled={tracks.length === 0} onClick={() => playTracks(tracks, 0)}>
|
||||
<Play />
|
||||
{t('player.play')}
|
||||
</Button>
|
||||
{suggested.sort === 'random' && (
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-12 gap-2"
|
||||
disabled={waiting}
|
||||
onClick={() => {
|
||||
save.reset()
|
||||
setVariant(variant + 1)
|
||||
}}
|
||||
>
|
||||
<Shuffle />
|
||||
{t('smart.shuffle')}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-12 gap-2"
|
||||
disabled={tracks.length === 0 || waiting || save.isPending}
|
||||
onClick={() => save.mutate({ key, name: title, variant: shown })}
|
||||
>
|
||||
<ListPlus />
|
||||
{t('smart.save')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-12 gap-2"
|
||||
disabled={make.isPending}
|
||||
onClick={() =>
|
||||
make.mutate(
|
||||
{ name: title, description, rules: suggested.rules, sort: suggested.sort, limit: suggested.limit },
|
||||
{ onSuccess: (p) => navigate(`/smart-playlists/${p.id}/edit`) },
|
||||
)
|
||||
}
|
||||
>
|
||||
<Wand2 />
|
||||
{t('smart.makeMine')}
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{save.isSuccess && (
|
||||
<p role="status" className="flex flex-wrap items-center gap-3 text-sm">
|
||||
<span>{t('smart.saved', { name: save.data.name })}</span>
|
||||
<Link to={`/playlists/${save.data.id}`} className="font-semibold underline">
|
||||
{t('smart.open')}
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
{(save.isError || make.isError) && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{errorLine(t, save.error ?? make.error)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{query.isPending ? <Loading /> : tracks.length === 0 ? <EmptyMessage>{t('smart.noSongs')}</EmptyMessage> : <TrackList tracks={tracks} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -10,6 +10,7 @@ import { apiError, mockFetch, type MockRoutes, type RecordedCall } from '@/test/
|
|||
import SmartEditorPage from './SmartEditorPage'
|
||||
import SmartPlaylistPage from './SmartPlaylistPage'
|
||||
import SmartPlaylistsPage from './SmartPlaylistsPage'
|
||||
import SuggestedSmartPage from './SuggestedSmartPage'
|
||||
import { describeRules, formFromRules, rulesFromForm } from './smartRules'
|
||||
|
||||
// --- fixtures ---------------------------------------------------------------------------------
|
||||
|
|
@ -52,6 +53,7 @@ function renderApp(path: string) {
|
|||
<Routes>
|
||||
<Route path="/smart-playlists" element={<SmartPlaylistsPage />} />
|
||||
<Route path="/smart-playlists/new" element={<SmartEditorPage />} />
|
||||
<Route path="/smart-playlists/suggested/:key" element={<SuggestedSmartPage />} />
|
||||
<Route path="/smart-playlists/:id" element={<SmartPlaylistPage />} />
|
||||
<Route path="/smart-playlists/:id/edit" element={<SmartEditorPage />} />
|
||||
<Route path="/playlists/:id" element={<p>THE PLAYLIST PAGE</p>} />
|
||||
|
|
@ -105,10 +107,22 @@ test('the rules are described in words, and no rule says so', async () => {
|
|||
])
|
||||
})
|
||||
|
||||
// --- the suggested ones ----------------------------------------------------------------------------
|
||||
|
||||
const SUGGESTED = [
|
||||
{ key: 'recently-added', rules: { added_within_days: 30 }, sort: 'recently_added', limit: 100 },
|
||||
{ key: 'never-played', rules: { never_played: true }, sort: 'random', limit: 50 },
|
||||
{ key: 'most-played', rules: { min_plays: 1 }, sort: 'most_played', limit: 50 },
|
||||
]
|
||||
|
||||
function suggestedRoutes(over: MockRoutes = {}): MockRoutes {
|
||||
return { 'GET /api/v1/smart-playlists/suggested': () => ({ items: SUGGESTED }), ...over }
|
||||
}
|
||||
|
||||
// --- the list ---------------------------------------------------------------------------------
|
||||
|
||||
test('the list shows each smart playlist with its order and limit, and a way to make one', async () => {
|
||||
mockFetch({ 'GET /api/v1/smart-playlists': () => page([smart(3, 'Fresh rock'), smart(4, 'Long ones', { sort: 'most_played', limit: 1 })]) })
|
||||
mockFetch({ ...suggestedRoutes(), 'GET /api/v1/smart-playlists': () => page([smart(3, 'Fresh rock'), smart(4, 'Long ones', { sort: 'most_played', limit: 1 })]) })
|
||||
renderApp('/smart-playlists')
|
||||
const link = await screen.findByRole('link', { name: /Fresh rock/ })
|
||||
expect(link).toHaveAttribute('href', '/smart-playlists/3')
|
||||
|
|
@ -118,7 +132,7 @@ test('the list shows each smart playlist with its order and limit, and a way to
|
|||
})
|
||||
|
||||
test('with none the page explains what a smart playlist is', async () => {
|
||||
mockFetch({ 'GET /api/v1/smart-playlists': () => page([]) })
|
||||
mockFetch({ ...suggestedRoutes(), 'GET /api/v1/smart-playlists': () => page([]) })
|
||||
renderApp('/smart-playlists')
|
||||
expect(await screen.findByText(/no smart playlists yet/i)).toBeInTheDocument()
|
||||
expect(screen.getByRole('link', { name: 'New smart playlist' })).toBeInTheDocument()
|
||||
|
|
@ -209,7 +223,7 @@ test('rules that give no songs say so and cannot be played or kept; a refused sa
|
|||
})
|
||||
|
||||
test('a smart playlist is deleted after asking, and the page goes back to the list', async () => {
|
||||
const { calls } = mockFetch(one({ 'DELETE /api/v1/smart-playlists/3': () => new Response(null, { status: 204 }), 'GET /api/v1/smart-playlists': () => page([]) }))
|
||||
const { calls } = mockFetch(one({ ...suggestedRoutes(), 'DELETE /api/v1/smart-playlists/3': () => new Response(null, { status: 204 }), 'GET /api/v1/smart-playlists': () => page([]) }))
|
||||
renderApp('/smart-playlists/3')
|
||||
await userEvent.click(await screen.findByRole('button', { name: 'Delete' }))
|
||||
const dialog = await screen.findByRole('alertdialog').catch(() => screen.findByRole('dialog'))
|
||||
|
|
@ -358,3 +372,95 @@ test('a smart playlist that does not exist cannot be edited', async () => {
|
|||
renderApp('/smart-playlists/3/edit')
|
||||
expect(await screen.findByText('This smart playlist does not exist.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
// --- the suggested ones, on the list and on their own page ---------------------------------------------
|
||||
|
||||
test('the list begins with the smart playlists that are there without making them, in my language', async () => {
|
||||
mockFetch({ ...suggestedRoutes(), 'GET /api/v1/smart-playlists': () => page([smart(3, 'Fresh rock')]) })
|
||||
renderApp('/smart-playlists')
|
||||
const made = await screen.findByRole('region', { name: 'Made for you' })
|
||||
const links = within(made).getAllByRole('link')
|
||||
expect(links.map((l) => l.getAttribute('href'))).toEqual([
|
||||
'/smart-playlists/suggested/recently-added', '/smart-playlists/suggested/never-played', '/smart-playlists/suggested/most-played',
|
||||
])
|
||||
expect(links[0]).toHaveTextContent('Recently added')
|
||||
expect(links[0]).toHaveTextContent('Songs added in the last 30 days')
|
||||
const mine = screen.getByRole('region', { name: 'My smart playlists' })
|
||||
expect(within(mine).getByRole('link', { name: /Fresh rock/ })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('the suggested ones are there even when the list of mine fails', async () => {
|
||||
mockFetch({ ...suggestedRoutes(), 'GET /api/v1/smart-playlists': () => apiError(500, 'unknown') })
|
||||
renderApp('/smart-playlists')
|
||||
expect(await screen.findByRole('link', { name: /Never played/ })).toBeInTheDocument()
|
||||
expect(await screen.findByRole('alert')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
function suggestedOne(over: MockRoutes = {}): MockRoutes {
|
||||
return {
|
||||
...suggestedRoutes(),
|
||||
'GET /api/v1/smart-playlists/suggested/never-played/tracks': () => tracks(0, 1, 2, 3),
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
test('a suggested smart playlist shows its name, its rules and its songs, and cannot be edited or deleted', async () => {
|
||||
mockFetch(suggestedOne())
|
||||
renderApp('/smart-playlists/suggested/never-played')
|
||||
expect(await screen.findByRole('heading', { level: 1, name: 'Never played' })).toBeInTheDocument()
|
||||
expect(screen.getByText('Songs you have never listened to.')).toBeInTheDocument()
|
||||
expect(within(screen.getByRole('list', { name: 'Rules' })).getByText('Never played', { selector: 'li' })).toBeInTheDocument()
|
||||
expect(await screen.findByRole('button', { name: /Song 1/ })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('link', { name: 'Edit' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Delete' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('a suggested one plays, shuffles again and is kept as a playlist under its name', async () => {
|
||||
let saved: unknown
|
||||
const { calls } = mockFetch(
|
||||
suggestedOne({
|
||||
'GET /api/v1/smart-playlists/suggested/never-played/tracks': ({ url }) => tracks(Number(url.searchParams.get('variant') ?? 0), 1, 2),
|
||||
'POST /api/v1/smart-playlists/suggested/never-played/playlist': ({ init }) => {
|
||||
saved = JSON.parse(init.body as string)
|
||||
return json(201, { id: 42, name: 'Never played', description: '', track_count: 2, duration_ms: 400_000, created_at: '2026-11-12T10:00:00Z', updated_at: '2026-11-12T10:00:00Z' })
|
||||
},
|
||||
}),
|
||||
)
|
||||
renderApp('/smart-playlists/suggested/never-played')
|
||||
await userEvent.click(await screen.findByRole('button', { name: 'Play' }))
|
||||
expect(usePlayer.getState().queue.map((t) => t.id)).toEqual([1, 2])
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Shuffle again' }))
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Save as playlist' })).toBeEnabled())
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Save as playlist' }))
|
||||
expect(await screen.findByRole('status')).toHaveTextContent('Saved as “Never played”')
|
||||
expect(saved).toEqual({ name: 'Never played', variant: 1 })
|
||||
expect(calls.filter((c) => c.key.endsWith('/tracks')).map((c) => c.url.searchParams.get('variant'))).toEqual([null, '1'])
|
||||
})
|
||||
|
||||
test('an order that is not random has no Shuffle again on a suggested one either', async () => {
|
||||
mockFetch(suggestedOne({ 'GET /api/v1/smart-playlists/suggested/most-played/tracks': () => tracks(0, 1) }))
|
||||
renderApp('/smart-playlists/suggested/most-played')
|
||||
await screen.findByRole('button', { name: 'Play' })
|
||||
expect(screen.queryByRole('button', { name: 'Shuffle again' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('Make it mine makes a smart playlist of my own with the same rules, and opens it to be changed', async () => {
|
||||
const { calls } = mockFetch(
|
||||
suggestedOne({
|
||||
'POST /api/v1/smart-playlists': () => json(201, smart(9, 'Never played', { rules: { never_played: true }, description: 'Songs you have never listened to.' })),
|
||||
'GET /api/v1/smart-playlists/9': () => smart(9, 'Never played', { rules: { never_played: true } }),
|
||||
'POST /api/v1/smart-playlists/preview': () => tracks(0, 1),
|
||||
}),
|
||||
)
|
||||
renderApp('/smart-playlists/suggested/never-played')
|
||||
await userEvent.click(await screen.findByRole('button', { name: 'Make it mine' }))
|
||||
const post = calls.find((c) => c.key === 'POST /api/v1/smart-playlists')!
|
||||
expect(body(post)).toEqual({ name: 'Never played', description: 'Songs you have never listened to.', rules: { never_played: true }, sort: 'random', limit: 50 })
|
||||
expect(await screen.findByRole('heading', { level: 1, name: 'Edit smart playlist' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('a suggested one that does not exist says so', async () => {
|
||||
mockFetch(suggestedOne({ 'GET /api/v1/smart-playlists/suggested/nonsense/tracks': () => apiError(404, 'suggested_not_found') }))
|
||||
renderApp('/smart-playlists/suggested/nonsense')
|
||||
expect(await screen.findByText('This suggested smart playlist does not exist.')).toBeInTheDocument()
|
||||
})
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ import SmartPlaylistPage from '@/pages/SmartPlaylistPage'
|
|||
import SmartPlaylistsPage from '@/pages/SmartPlaylistsPage'
|
||||
import SettingsPage from '@/pages/SettingsPage'
|
||||
import SongsPage from '@/pages/SongsPage'
|
||||
import SuggestedSmartPage from '@/pages/SuggestedSmartPage'
|
||||
|
||||
export const routes: RouteObject[] = [
|
||||
{
|
||||
|
|
@ -41,6 +42,7 @@ export const routes: RouteObject[] = [
|
|||
{ path: '/playlists/:id', element: <PlaylistPage /> },
|
||||
{ path: '/smart-playlists', element: <SmartPlaylistsPage /> },
|
||||
{ path: '/smart-playlists/new', element: <SmartEditorPage /> },
|
||||
{ path: '/smart-playlists/suggested/:key', element: <SuggestedSmartPage /> },
|
||||
{ path: '/smart-playlists/:id', element: <SmartPlaylistPage /> },
|
||||
{ path: '/smart-playlists/:id/edit', element: <SmartEditorPage /> },
|
||||
{ path: '/settings', element: <SettingsPage /> },
|
||||
|
|
|
|||
Loading…
Reference in a new issue