feat: a statistics page
- GET /stats/library: the songs that can be played with their artists, albums, length and size, the files by format, the share of each genre and decade - GET /stats/listening: listens, time listened, songs and artists, listens by year, hour and weekday in the listener's time zone, top artists and songs, the share of each genre, for all time or a period - a song with several genres is split between them, so the shares add up - web: a Statistics page in the Your listening group, with bars made of CSS and four periods - the MP3 files, which the scanner calls mpeg, are shown as MP3 - README: the two endpoints
This commit is contained in:
parent
0742ee88a9
commit
d51f155a4d
16 changed files with 2336 additions and 11 deletions
181
web/src/api/schema.d.ts
vendored
181
web/src/api/schema.d.ts
vendored
|
|
@ -2191,6 +2191,52 @@ export interface paths {
|
|||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/stats/library": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
/**
|
||||
* What the library holds
|
||||
* @description The songs that can be played (a song whose file is missing is not counted), with their artists, albums, total
|
||||
* length and the space their files take, the files by format, the share of each genre and of each decade. The
|
||||
* genre shares count a song with several genres once, split between them, so `top`, `other` and
|
||||
* `untagged_share` add up to 1. The genres are the tags of the files, read offline.
|
||||
*/
|
||||
get: operations["getLibraryStats"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/stats/listening": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
/**
|
||||
* What you listened to
|
||||
* @description Your listens that count (see `POST /listens`), for all time or for a period: how many, how long, how many
|
||||
* songs and artists, the listens of each year (a year with none between the first and the last is 0), of each
|
||||
* hour of the day and of each weekday (Monday first), your most listened artists and songs, and the share of each
|
||||
* genre. Years, hours and weekdays are counted in the time zone `tz`. Nobody else's listens are visible.
|
||||
*/
|
||||
get: operations["getListeningStats"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/listens/months": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
|
@ -3433,6 +3479,91 @@ export interface components {
|
|||
score: number;
|
||||
}[];
|
||||
};
|
||||
/** @description The share of each genre. `top`, `other` and `untagged_share` add up to 1. */
|
||||
GenreShares: {
|
||||
/** @description The ten biggest, biggest first. */
|
||||
top: {
|
||||
name: string;
|
||||
/** @description How many songs (or listens) have this genre. */
|
||||
count: number;
|
||||
share: number;
|
||||
}[];
|
||||
/** @description What the smaller genres add up to. */
|
||||
other: number;
|
||||
/** @description How many songs (or listens) have no genre. */
|
||||
untagged: number;
|
||||
untagged_share: number;
|
||||
};
|
||||
LibraryStats: {
|
||||
artists: number;
|
||||
albums: number;
|
||||
songs: number;
|
||||
/**
|
||||
* Format: int64
|
||||
* @description The length of all the songs together.
|
||||
*/
|
||||
duration_ms: number;
|
||||
/**
|
||||
* Format: int64
|
||||
* @description The space of all the files that are not missing.
|
||||
*/
|
||||
size_bytes: number;
|
||||
formats: {
|
||||
/** @example flac */
|
||||
format: string;
|
||||
files: number;
|
||||
/** Format: int64 */
|
||||
bytes: number;
|
||||
}[];
|
||||
genres: components["schemas"]["GenreShares"];
|
||||
/** @description How many songs came out in each decade, oldest first. 1990 is the nineties. */
|
||||
decades: {
|
||||
/** @example 1990 */
|
||||
decade: number;
|
||||
songs: number;
|
||||
}[];
|
||||
/** @description Songs whose file has no year. */
|
||||
no_year: number;
|
||||
};
|
||||
ListeningStats: {
|
||||
listens: number;
|
||||
/** @description How many different songs. */
|
||||
songs: number;
|
||||
/** @description How many different artists. */
|
||||
artists: number;
|
||||
/**
|
||||
* Format: int64
|
||||
* @description The time listened to.
|
||||
*/
|
||||
played_ms: number;
|
||||
/**
|
||||
* Format: date-time
|
||||
* @description The first listen of the period. Left out when there is none.
|
||||
*/
|
||||
first?: string;
|
||||
years: {
|
||||
year: number;
|
||||
listens: number;
|
||||
}[];
|
||||
/** @description Listens in each hour of the day, from midnight. */
|
||||
hours: number[];
|
||||
/** @description Listens on each weekday, from Monday. */
|
||||
weekdays: number[];
|
||||
top_artists: {
|
||||
/** Format: int64 */
|
||||
id: number;
|
||||
name: string;
|
||||
listens: number;
|
||||
}[];
|
||||
top_songs: {
|
||||
/** Format: int64 */
|
||||
id: number;
|
||||
title: string;
|
||||
artists: string[];
|
||||
listens: number;
|
||||
}[];
|
||||
genres: components["schemas"]["GenreShares"];
|
||||
};
|
||||
ListeningSuggestions: {
|
||||
library: components["schemas"]["ListeningSuggestion"][];
|
||||
missing: components["schemas"]["ListeningSuggestion"][];
|
||||
|
|
@ -8048,6 +8179,56 @@ export interface operations {
|
|||
};
|
||||
};
|
||||
};
|
||||
getLibraryStats: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description The numbers. */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["LibraryStats"];
|
||||
};
|
||||
};
|
||||
401: components["responses"]["Unauthorized"];
|
||||
};
|
||||
};
|
||||
getListeningStats: {
|
||||
parameters: {
|
||||
query?: {
|
||||
/** @description The start of the period, included, as a date and time with an offset. */
|
||||
from?: string;
|
||||
/** @description The end of the period, excluded. It must not be before `from`. */
|
||||
until?: string;
|
||||
/** @description An IANA time zone name, like `Europe/Rome`. Anything else is `invalid_input`. */
|
||||
tz?: string;
|
||||
};
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description The numbers. */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["ListeningStats"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["InvalidInput"];
|
||||
401: components["responses"]["Unauthorized"];
|
||||
};
|
||||
};
|
||||
listListenMonths: {
|
||||
parameters: {
|
||||
query?: {
|
||||
|
|
|
|||
42
web/src/api/stats.ts
Normal file
42
web/src/api/stats.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import { useQuery } from '@tanstack/react-query'
|
||||
import { api } from '@/api/client'
|
||||
import type { components } from '@/api/schema'
|
||||
import { browserZone } from '@/api/history'
|
||||
|
||||
export type LibraryStats = components['schemas']['LibraryStats']
|
||||
export type ListeningStats = components['schemas']['ListeningStats']
|
||||
export type GenreShares = components['schemas']['GenreShares']
|
||||
|
||||
/** The periods the listening can be cut to. */
|
||||
export const PERIODS = ['all', 'year', 'months12', 'days30'] as const
|
||||
export type Period = (typeof PERIODS)[number]
|
||||
|
||||
/**
|
||||
* The start of a period, at midnight of the local day, so that a period starts where the listener's own days do. The
|
||||
* period always runs up to now, so it has no end.
|
||||
*/
|
||||
export function periodStart(period: Period, now = new Date()): Date | null {
|
||||
switch (period) {
|
||||
case 'year':
|
||||
return new Date(now.getFullYear(), 0, 1)
|
||||
case 'months12':
|
||||
return new Date(now.getFullYear() - 1, now.getMonth(), now.getDate())
|
||||
case 'days30':
|
||||
return new Date(now.getFullYear(), now.getMonth(), now.getDate() - 30)
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** What the library holds. */
|
||||
export function useLibraryStats() {
|
||||
return useQuery({ queryKey: ['/stats/library'], queryFn: () => api.get<LibraryStats>('/stats/library') })
|
||||
}
|
||||
|
||||
/** What the signed-in person listened to in a period, in the time zone of this browser. */
|
||||
export function useListeningStats(period: Period) {
|
||||
return useQuery({
|
||||
queryKey: ['/stats/listening', period, browserZone()],
|
||||
queryFn: () => api.get<ListeningStats>('/stats/listening', { from: periodStart(period)?.toISOString(), tz: browserZone() }),
|
||||
})
|
||||
}
|
||||
60
web/src/components/StatBars.tsx
Normal file
60
web/src/components/StatBars.tsx
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import type { ReactNode } from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export interface Bar {
|
||||
key: string
|
||||
/** What is shown at the side of the bar. */
|
||||
label: ReactNode
|
||||
/** From 0 to 1: how much of the track the bar fills. */
|
||||
value: number
|
||||
/** What is shown after the bar. */
|
||||
text: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Horizontal bars, one a line: a name, a bar as long as its share, and the figure. They are a list, so a screen reader
|
||||
* reads each line (name and figure) and skips the drawing.
|
||||
*/
|
||||
export function ShareBars({ label, bars, wide = false }: { label: string; bars: Bar[]; wide?: boolean }) {
|
||||
return (
|
||||
<ul aria-label={label} className="flex flex-col gap-2">
|
||||
{bars.map((b) => (
|
||||
<li key={b.key} className={cn('grid items-center gap-3', wide ? 'grid-cols-[minmax(9rem,20rem)_1fr_3.5rem]' : 'grid-cols-[minmax(6rem,10rem)_1fr_3.5rem]')}>
|
||||
<span className="min-w-0 truncate font-medium first-letter:uppercase">{b.label}</span>
|
||||
<span aria-hidden="true" className="h-2 overflow-hidden rounded-full bg-card">
|
||||
<span className="block h-full rounded-full bg-primary" style={{ width: `${Math.min(1, Math.max(0, b.value)) * 100}%` }} />
|
||||
</span>
|
||||
<span className="text-right text-sm tabular-nums text-muted-foreground">{b.text}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
export interface Column {
|
||||
key: string
|
||||
/** What is shown under the column; the others can be left out when there are many. */
|
||||
label: string
|
||||
value: number
|
||||
/** What a screen reader reads for the column, which has no text of its own. */
|
||||
name: string
|
||||
}
|
||||
|
||||
const HEIGHT = 96
|
||||
|
||||
/** Vertical columns as high as their value, the highest filling the track: a year by year, or hour by hour chart. */
|
||||
export function Columns({ label, columns, className }: { label: string; columns: Column[]; className?: string }) {
|
||||
const biggest = Math.max(1, ...columns.map((c) => c.value))
|
||||
return (
|
||||
<ul aria-label={label} className={cn('flex items-end gap-1', className)}>
|
||||
{columns.map((c) => (
|
||||
<li key={c.key} aria-label={c.name} title={c.name} className="flex min-w-0 flex-1 flex-col items-center justify-end gap-1">
|
||||
<span aria-hidden="true" className="w-full rounded-sm bg-primary" style={{ height: `${Math.max(c.value > 0 ? 3 : 0, (c.value / biggest) * HEIGHT)}px` }} />
|
||||
<span aria-hidden="true" className="h-4 text-[13px] leading-4 tabular-nums text-muted-foreground">
|
||||
{c.label}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
|
@ -47,7 +47,7 @@ test('the tab of the page that is open is the current one', () => {
|
|||
expect(within(nav).getByRole('link', { name: 'Home' })).not.toHaveAttribute('aria-current')
|
||||
})
|
||||
|
||||
test.each(['/library', '/artists', '/albums/4', '/songs', '/mixes', '/playlists/2', '/smart-playlists', '/history', '/import'])(
|
||||
test.each(['/library', '/artists', '/albums/4', '/songs', '/mixes', '/playlists/2', '/smart-playlists', '/history', '/stats', '/import'])(
|
||||
'Library is the current tab on %s, one of the pages it leads to',
|
||||
(path) => {
|
||||
const nav = renderTabs(path)
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import { cn } from '@/lib/utils'
|
|||
/** The pages the Home tab leads to (Home itself ends the list of them with links to Discover and, for an admin, Requests). */
|
||||
const HOME = ['/discover', '/requests']
|
||||
/** The pages the Library tab leads to: it is the current tab on all of them. */
|
||||
const LIBRARY = ['/library', '/artists', '/albums', '/songs', '/playlists', '/smart-playlists', '/mixes', '/history', '/import']
|
||||
const LIBRARY = ['/library', '/artists', '/albums', '/songs', '/playlists', '/smart-playlists', '/mixes', '/history', '/stats', '/import']
|
||||
const MORE = ['/more', '/settings', '/admin']
|
||||
|
||||
const under = (path: string, prefixes: string[]) => prefixes.some((p) => path === p || path.startsWith(`${p}/`))
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ function renderSidebar(friends: { id: number; name: string }[] = [], path = '/al
|
|||
|
||||
test('the menu has a link for each page, and the page that is open is the current one', () => {
|
||||
const nav = renderSidebar()
|
||||
for (const name of ['Home', 'Search', 'Discover', 'Artists', 'Albums', 'Songs', 'Mixes', 'Playlists', 'Smart playlists', 'History', 'Import', 'Admin', 'Settings']) {
|
||||
for (const name of ['Home', 'Search', 'Discover', 'Artists', 'Albums', 'Songs', 'Mixes', 'Playlists', 'Smart playlists', 'History', 'Statistics', 'Import', 'Admin', 'Settings']) {
|
||||
expect(within(nav).getByRole('link', { name })).toBeInTheDocument()
|
||||
}
|
||||
expect(within(nav).getByRole('link', { name: 'Albums' })).toHaveAttribute('aria-current', 'page')
|
||||
|
|
@ -158,7 +158,7 @@ test('the links are in groups, in the order of what you do: find, the library, y
|
|||
expect(names(nav)).toEqual([
|
||||
'Home', 'Search', 'Discover', 'Requests',
|
||||
'Artists', 'Albums', 'Songs', 'Playlists', 'Smart playlists', 'Mixes',
|
||||
'History', 'Import',
|
||||
'History', 'Statistics', 'Import',
|
||||
'Friends',
|
||||
'Settings', 'Admin',
|
||||
])
|
||||
|
|
@ -169,7 +169,7 @@ test('the library and the listening have a quiet heading, and the groups that ex
|
|||
const library = within(nav).getByRole('list', { name: 'Library' })
|
||||
expect(within(library).getAllByRole('link').map((a) => a.textContent)).toEqual(['Artists', 'Albums', 'Songs', 'Playlists', 'Smart playlists', 'Mixes'])
|
||||
const listening = within(nav).getByRole('list', { name: 'Your listening' })
|
||||
expect(within(listening).getAllByRole('link').map((a) => a.textContent)).toEqual(['History', 'Import'])
|
||||
expect(within(listening).getAllByRole('link').map((a) => a.textContent)).toEqual(['History', 'Statistics', 'Import'])
|
||||
// The headings are words, not links, and not headings of the page.
|
||||
expect(within(nav).queryByRole('heading')).not.toBeInTheDocument()
|
||||
expect(within(nav).queryByRole('link', { name: 'Your listening' })).not.toBeInTheDocument()
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { useState } from 'react'
|
||||
import { Blend, Compass, Disc3, History, House, Inbox, ListMusic, MicVocal, Music, PanelLeftClose, PanelLeftOpen, Search, Settings, ShieldCheck, Upload, Users, WandSparkles } from 'lucide-react'
|
||||
import { Blend, ChartNoAxesColumn, Compass, Disc3, History, House, Inbox, ListMusic, MicVocal, Music, PanelLeftClose, PanelLeftOpen, Search, Settings, ShieldCheck, Upload, Users, WandSparkles } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { NavLink } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
|
@ -52,6 +52,7 @@ const GROUPS: Group[] = [
|
|||
heading: 'nav.listening',
|
||||
items: [
|
||||
{ to: '/history', key: 'nav.history', icon: History },
|
||||
{ to: '/stats', key: 'nav.stats', icon: ChartNoAxesColumn },
|
||||
{ to: '/import', key: 'nav.import', icon: Upload },
|
||||
],
|
||||
},
|
||||
|
|
|
|||
|
|
@ -26,7 +26,8 @@
|
|||
"more": "More",
|
||||
"collapse": "Collapse menu",
|
||||
"expand": "Expand menu",
|
||||
"tabs": "Tabs"
|
||||
"tabs": "Tabs",
|
||||
"stats": "Statistics"
|
||||
},
|
||||
"common": {
|
||||
"loading": "Loading",
|
||||
|
|
@ -1087,5 +1088,45 @@
|
|||
"plain": "Version {{version}}",
|
||||
"commit": "Version {{version}} · {{revision}}",
|
||||
"changed": "Version {{version}} · {{revision}} (changed)"
|
||||
},
|
||||
"stats": {
|
||||
"library": "Your library",
|
||||
"listening": "Your listening",
|
||||
"songs": "Songs",
|
||||
"albums": "Albums",
|
||||
"artists": "Artists",
|
||||
"length": "Length",
|
||||
"size": "Size on disk",
|
||||
"genres": "Genres",
|
||||
"formats": "Formats",
|
||||
"decades": "Decades",
|
||||
"other": "Smaller genres",
|
||||
"noGenre": "No genre",
|
||||
"noYear_one": "{{n}} song has no year in its tags.",
|
||||
"noYear_other": "{{n}} songs have no year in their tags.",
|
||||
"emptyLibrary": "There is no music in the library yet.",
|
||||
"period": "Period",
|
||||
"periods": {
|
||||
"all": "All time",
|
||||
"year": "This year",
|
||||
"months12": "Last 12 months",
|
||||
"days30": "Last 30 days"
|
||||
},
|
||||
"listens": "Listens",
|
||||
"timeListened": "Time listened",
|
||||
"first": "First listen",
|
||||
"byYear": "Listens by year",
|
||||
"byHour": "Listens by hour of the day",
|
||||
"byWeekday": "Listens by day of the week",
|
||||
"topArtists": "Top artists",
|
||||
"topSongs": "Top songs",
|
||||
"yourGenres": "Genres you listen to",
|
||||
"none": "No listens in this period.",
|
||||
"decade": "{{decade}}s",
|
||||
"songsIn_one": "{{label}}: {{n}} song",
|
||||
"songsIn_other": "{{label}}: {{n}} songs",
|
||||
"listensIn_one": "{{label}}: {{n}} listen",
|
||||
"listensIn_other": "{{label}}: {{n}} listens",
|
||||
"decadeShort": "{{short}}s"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,7 +26,8 @@
|
|||
"more": "Altro",
|
||||
"collapse": "Comprimi il menu",
|
||||
"expand": "Espandi il menu",
|
||||
"tabs": "Schede"
|
||||
"tabs": "Schede",
|
||||
"stats": "Statistiche"
|
||||
},
|
||||
"common": {
|
||||
"loading": "Caricamento",
|
||||
|
|
@ -1087,5 +1088,45 @@
|
|||
"plain": "Versione {{version}}",
|
||||
"commit": "Versione {{version}} · {{revision}}",
|
||||
"changed": "Versione {{version}} · {{revision}} (modificata)"
|
||||
},
|
||||
"stats": {
|
||||
"library": "La tua libreria",
|
||||
"listening": "I tuoi ascolti",
|
||||
"songs": "Brani",
|
||||
"albums": "Album",
|
||||
"artists": "Artisti",
|
||||
"length": "Durata",
|
||||
"size": "Spazio su disco",
|
||||
"genres": "Generi",
|
||||
"formats": "Formati",
|
||||
"decades": "Decenni",
|
||||
"other": "Generi minori",
|
||||
"noGenre": "Senza genere",
|
||||
"noYear_one": "{{n}} brano non ha l'anno nei tag.",
|
||||
"noYear_other": "{{n}} brani non hanno l'anno nei tag.",
|
||||
"emptyLibrary": "Non c'è ancora musica nella libreria.",
|
||||
"period": "Periodo",
|
||||
"periods": {
|
||||
"all": "Sempre",
|
||||
"year": "Quest'anno",
|
||||
"months12": "Ultimi 12 mesi",
|
||||
"days30": "Ultimi 30 giorni"
|
||||
},
|
||||
"listens": "Ascolti",
|
||||
"timeListened": "Tempo ascoltato",
|
||||
"first": "Primo ascolto",
|
||||
"byYear": "Ascolti per anno",
|
||||
"byHour": "Ascolti per ora del giorno",
|
||||
"byWeekday": "Ascolti per giorno della settimana",
|
||||
"topArtists": "Artisti più ascoltati",
|
||||
"topSongs": "Brani più ascoltati",
|
||||
"yourGenres": "Generi che ascolti",
|
||||
"none": "Nessun ascolto in questo periodo.",
|
||||
"decade": "Anni {{short}}",
|
||||
"songsIn_one": "{{label}}: {{n}} brano",
|
||||
"songsIn_other": "{{label}}: {{n}} brani",
|
||||
"listensIn_one": "{{label}}: {{n}} ascolto",
|
||||
"listensIn_other": "{{label}}: {{n}} ascolti",
|
||||
"decadeShort": "{{short}}"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { expect, test } from 'vitest'
|
||||
import { formatTime } from './time'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import { formatLength, formatTime } from './time'
|
||||
|
||||
test.each([
|
||||
[0, '0:00'],
|
||||
|
|
@ -20,3 +20,21 @@ test('a negative or unknown time is written as zero', () => {
|
|||
expect(formatTime(Number.NaN)).toBe('0:00')
|
||||
expect(formatTime(Number.POSITIVE_INFINITY)).toBe('0:00')
|
||||
})
|
||||
|
||||
describe('formatLength', () => {
|
||||
const h = 3600_000
|
||||
test('tells days and hours, hours and minutes, or minutes, in the language of the reader', () => {
|
||||
expect(formatLength((38 * 24 + 4) * h + 120_000, 'en')).toBe('38 days 4 hours')
|
||||
expect(formatLength(25 * h, 'en')).toBe('1 day 1 hour')
|
||||
expect(formatLength(2 * h + 5 * 60_000, 'en')).toBe('2 hours 5 minutes')
|
||||
expect(formatLength(7 * 60_000 + 59_000, 'en')).toBe('7 minutes')
|
||||
expect(formatLength(2 * 24 * h, 'it')).toBe('2 giorni')
|
||||
})
|
||||
test('leaves out a second unit that is zero, and is 0 minutes for nothing or a bad number', () => {
|
||||
expect(formatLength(3 * 24 * h + 10 * 60_000, 'en')).toBe('3 days')
|
||||
expect(formatLength(4 * h, 'en')).toBe('4 hours')
|
||||
expect(formatLength(0, 'en')).toBe('0 minutes')
|
||||
expect(formatLength(Number.NaN, 'en')).toBe('0 minutes')
|
||||
expect(formatLength(-5, 'en')).toBe('0 minutes')
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -7,3 +7,17 @@ export function formatTime(ms: number): string {
|
|||
const seconds = String(total % 60).padStart(2, '0')
|
||||
return hours > 0 ? `${hours}:${String(minutes).padStart(2, '0')}:${seconds}` : `${minutes}:${seconds}`
|
||||
}
|
||||
|
||||
/**
|
||||
* A long time in words, in the language of the reader: "38 days 4 hours", "2 hours 5 minutes", "7 minutes". Only the
|
||||
* two biggest units are told, and a zero second unit is left out.
|
||||
*/
|
||||
export function formatLength(ms: number, lang: string): string {
|
||||
const unit = (n: number, u: 'day' | 'hour' | 'minute') => new Intl.NumberFormat(lang, { style: 'unit', unit: u, unitDisplay: 'long' }).format(n)
|
||||
const minutes = Math.floor(Math.max(0, Number.isFinite(ms) ? ms : 0) / 60000)
|
||||
const hours = Math.floor(minutes / 60)
|
||||
const days = Math.floor(hours / 24)
|
||||
if (days >= 1) return hours % 24 > 0 ? `${unit(days, 'day')} ${unit(hours % 24, 'hour')}` : unit(days, 'day')
|
||||
if (hours >= 1) return minutes % 60 > 0 ? `${unit(hours, 'hour')} ${unit(minutes % 60, 'minute')}` : unit(hours, 'hour')
|
||||
return unit(minutes, 'minute')
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,9 +28,10 @@ test('Library is a list of the places of the music, each a row that leads there'
|
|||
['Smart playlists', '/smart-playlists'],
|
||||
['Mixes', '/mixes'],
|
||||
['History', '/history'],
|
||||
['Statistics', '/stats'],
|
||||
['Import', '/import'],
|
||||
])
|
||||
expect(within(screen.getByRole('region', { name: 'Your listening' })).getAllByRole('link')).toHaveLength(2)
|
||||
expect(within(screen.getByRole('region', { name: 'Your listening' })).getAllByRole('link')).toHaveLength(3)
|
||||
expect(screen.queryByRole('link', { name: 'Discover' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ export default function LibraryPage() {
|
|||
<LinkRows
|
||||
links={[
|
||||
{ to: '/history', label: t('nav.history') },
|
||||
{ to: '/stats', label: t('nav.stats') },
|
||||
{ to: '/import', label: t('nav.import') },
|
||||
]}
|
||||
/>
|
||||
|
|
|
|||
239
web/src/pages/StatsPage.test.tsx
Normal file
239
web/src/pages/StatsPage.test.tsx
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { afterEach, beforeEach, expect, test, vi } from 'vitest'
|
||||
import { initI18n } from '@/i18n'
|
||||
import { apiError, mockFetch, type MockRoutes } from '@/test/mockFetch'
|
||||
import StatsPage from './StatsPage'
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
|
||||
await initI18n()
|
||||
})
|
||||
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
const library = {
|
||||
artists: 640,
|
||||
albums: 1204,
|
||||
songs: 12138,
|
||||
duration_ms: ((38 * 24 + 4) * 3600 + 120) * 1000, // 38 days and 4 hours
|
||||
size_bytes: 215 * 1024 ** 3,
|
||||
formats: [
|
||||
{ format: 'flac', files: 9000, bytes: 200 * 1024 ** 3 },
|
||||
{ format: 'mpeg', files: 3000, bytes: 15 * 1024 ** 3 },
|
||||
],
|
||||
genres: {
|
||||
top: [
|
||||
{ name: 'rock', count: 6000, share: 0.5 },
|
||||
{ name: 'jazz', count: 1800, share: 0.15 },
|
||||
],
|
||||
other: 0.1,
|
||||
untagged: 3000,
|
||||
untagged_share: 0.25,
|
||||
},
|
||||
decades: [
|
||||
{ decade: 1960, songs: 1000 },
|
||||
{ decade: 1990, songs: 4000 },
|
||||
{ decade: 2000, songs: 3000 },
|
||||
],
|
||||
no_year: 4138,
|
||||
}
|
||||
|
||||
const hours = Array.from({ length: 24 }, (_, h) => (h === 21 ? 30 : h === 8 ? 10 : 0))
|
||||
const listening = {
|
||||
listens: 1234,
|
||||
songs: 800,
|
||||
artists: 150,
|
||||
played_ms: ((2 * 24 + 3) * 3600 + 5 * 60) * 1000, // 2 days and 3 hours
|
||||
first: '2019-03-05T10:00:00Z',
|
||||
years: [
|
||||
{ year: 2019, listens: 100 },
|
||||
{ year: 2020, listens: 0 },
|
||||
{ year: 2021, listens: 400 },
|
||||
],
|
||||
hours,
|
||||
weekdays: [10, 20, 30, 40, 50, 60, 70],
|
||||
top_artists: [
|
||||
{ id: 11, name: 'Radiohead', listens: 90 },
|
||||
{ id: 12, name: 'Blur', listens: 60 },
|
||||
],
|
||||
top_songs: [{ id: 5, title: 'Karma Police', artists: ['Radiohead'], listens: 33 }],
|
||||
genres: { top: [{ name: 'rock', count: 700, share: 0.7 }], other: 0.1, untagged: 200, untagged_share: 0.2 },
|
||||
}
|
||||
|
||||
const none = {
|
||||
listens: 0,
|
||||
songs: 0,
|
||||
artists: 0,
|
||||
played_ms: 0,
|
||||
years: [],
|
||||
hours: Array(24).fill(0),
|
||||
weekdays: Array(7).fill(0),
|
||||
top_artists: [],
|
||||
top_songs: [],
|
||||
genres: { top: [], other: 0, untagged: 0, untagged_share: 0 },
|
||||
}
|
||||
|
||||
function setup(routes: MockRoutes = {}) {
|
||||
const mocked = mockFetch({
|
||||
'GET /api/v1/stats/library': () => library,
|
||||
'GET /api/v1/stats/listening': () => listening,
|
||||
...routes,
|
||||
})
|
||||
render(
|
||||
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
|
||||
<MemoryRouter>
|
||||
<StatsPage />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
return mocked
|
||||
}
|
||||
|
||||
/** A section, once what it asked for has come (or failed). */
|
||||
async function section(name: string) {
|
||||
const region = await screen.findByRole('region', { name })
|
||||
await waitFor(() => expect(within(region).queryByRole('status')).not.toBeInTheDocument())
|
||||
return region
|
||||
}
|
||||
|
||||
test('the library says how much music there is: songs, albums, artists, length and space', async () => {
|
||||
setup()
|
||||
const lib = await section('Your library')
|
||||
expect(within(lib).getByText('12,138')).toBeInTheDocument()
|
||||
expect(within(lib).getByText('1,204')).toBeInTheDocument()
|
||||
expect(within(lib).getByText('640')).toBeInTheDocument()
|
||||
expect(within(lib).getByText('38 days 4 hours')).toBeInTheDocument()
|
||||
expect(within(lib).getByText('215.0 GB')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('the genres of the library are shares of the whole, with what has no genre and the smaller ones', async () => {
|
||||
setup()
|
||||
const lib = await section('Your library')
|
||||
const genres = within(lib).getByRole('list', { name: 'Genres' })
|
||||
const rows = within(genres).getAllByRole('listitem').map((li) => li.textContent)
|
||||
expect(rows).toEqual(['rock50%', 'jazz15%', 'Smaller genres10%', 'No genre25%'])
|
||||
})
|
||||
|
||||
test('the formats and the decades are shown too', async () => {
|
||||
setup()
|
||||
const lib = await section('Your library')
|
||||
const formats = within(lib).getByRole('list', { name: 'Formats' })
|
||||
expect(within(formats).getAllByRole('listitem').map((li) => li.textContent)).toEqual(['FLAC75%', 'MP325%'])
|
||||
const decades = within(lib).getByRole('list', { name: 'Decades' })
|
||||
expect(within(decades).getAllByRole('listitem').map((li) => li.getAttribute('aria-label'))).toEqual(['1960s: 1,000 songs', '1990s: 4,000 songs', '2000s: 3,000 songs'])
|
||||
})
|
||||
|
||||
test('with many decades the labels under the columns are short, and the names stay whole', async () => {
|
||||
const decades = [1940, 1950, 1960, 1970, 1980, 1990, 2000].map((decade) => ({ decade, songs: 10 }))
|
||||
setup({ 'GET /api/v1/stats/library': () => ({ ...library, decades }) })
|
||||
const lib = await section('Your library')
|
||||
const list = within(lib).getByRole('list', { name: 'Decades' })
|
||||
const items = within(list).getAllByRole('listitem')
|
||||
expect(items.map((li) => li.textContent)).toEqual(['40s', '50s', '60s', '70s', '80s', '90s', '00s'])
|
||||
expect(items[5]).toHaveAttribute('aria-label', '1990s: 10 songs')
|
||||
})
|
||||
|
||||
test('listening says how many listens, the time, the songs and artists, and since when', async () => {
|
||||
setup()
|
||||
const l = await section('Your listening')
|
||||
expect(within(l).getByText('1,234')).toBeInTheDocument()
|
||||
expect(within(l).getByText('2 days 3 hours')).toBeInTheDocument()
|
||||
expect(within(l).getByText('800')).toBeInTheDocument()
|
||||
expect(within(l).getByText('150')).toBeInTheDocument()
|
||||
expect(within(l).getByText(/March 5, 2019/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('listens are shown by year (a year with none too), by hour and by weekday', async () => {
|
||||
setup()
|
||||
const l = await section('Your listening')
|
||||
const years = within(l).getByRole('list', { name: 'Listens by year' })
|
||||
expect(within(years).getAllByRole('listitem').map((li) => li.getAttribute('aria-label'))).toEqual(['2019: 100 listens', '2020: 0 listens', '2021: 400 listens'])
|
||||
const hoursList = within(l).getByRole('list', { name: 'Listens by hour of the day' })
|
||||
const items = within(hoursList).getAllByRole('listitem')
|
||||
expect(items).toHaveLength(24)
|
||||
expect(items[21]).toHaveAttribute('aria-label', '21:00: 30 listens')
|
||||
const days = within(l).getByRole('list', { name: 'Listens by day of the week' })
|
||||
const week = within(days).getAllByRole('listitem')
|
||||
expect(week).toHaveLength(7)
|
||||
expect(week[0]).toHaveAttribute('aria-label', 'Mon: 10 listens')
|
||||
expect(week[6]).toHaveAttribute('aria-label', 'Sun: 70 listens')
|
||||
})
|
||||
|
||||
test('one year has no chart by year: there is nothing to compare', async () => {
|
||||
setup({ 'GET /api/v1/stats/listening': () => ({ ...listening, years: [{ year: 2021, listens: 400 }] }) })
|
||||
const l = await section('Your listening')
|
||||
expect(within(l).queryByRole('list', { name: 'Listens by year' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('the most listened artists link to their page, and the songs name their artists', async () => {
|
||||
setup()
|
||||
const l = await section('Your listening')
|
||||
const artists = within(l).getByRole('list', { name: 'Top artists' })
|
||||
const first = within(artists).getAllByRole('listitem')[0]
|
||||
expect(within(first).getByRole('link', { name: 'Radiohead' })).toHaveAttribute('href', '/artists/11')
|
||||
expect(first).toHaveTextContent('90')
|
||||
const songs = within(l).getByRole('list', { name: 'Top songs' })
|
||||
expect(within(songs).getByText('Karma Police')).toBeInTheDocument()
|
||||
expect(within(songs).getByText('Radiohead')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('the genres of the listening are shares too', async () => {
|
||||
setup()
|
||||
const l = await section('Your listening')
|
||||
const genres = within(l).getByRole('list', { name: 'Genres you listen to' })
|
||||
expect(within(genres).getAllByRole('listitem').map((li) => li.textContent)).toEqual(['rock70%', 'Smaller genres10%', 'No genre20%'])
|
||||
})
|
||||
|
||||
test('it asks for all time at first, in the time zone of this browser', async () => {
|
||||
const { calls } = setup()
|
||||
await section('Your listening')
|
||||
const asked = calls.find((c) => c.key === 'GET /api/v1/stats/listening')!
|
||||
expect(asked.url.searchParams.get('from')).toBeNull()
|
||||
expect(asked.url.searchParams.get('until')).toBeNull()
|
||||
expect(asked.url.searchParams.get('tz')).toBe(Intl.DateTimeFormat().resolvedOptions().timeZone)
|
||||
const group = screen.getByRole('group', { name: 'Period' })
|
||||
expect(within(group).getByRole('button', { name: 'All time' })).toHaveAttribute('aria-pressed', 'true')
|
||||
})
|
||||
|
||||
test.each([
|
||||
['This year', () => new Date(2026, 0, 1)],
|
||||
['Last 12 months', () => new Date(2025, 10, 15)],
|
||||
['Last 30 days', () => new Date(2026, 9, 16)],
|
||||
])('choosing %s asks for that period, counted in local days', async (label, from) => {
|
||||
vi.useFakeTimers({ toFake: ['Date'], now: new Date(2026, 10, 15, 14, 30) })
|
||||
const { calls } = setup()
|
||||
await section('Your listening')
|
||||
await userEvent.click(within(screen.getByRole('group', { name: 'Period' })).getByRole('button', { name: label }))
|
||||
await vi.waitFor(() => expect(calls.filter((c) => c.key === 'GET /api/v1/stats/listening')).toHaveLength(2))
|
||||
const asked = calls.filter((c) => c.key === 'GET /api/v1/stats/listening')[1]
|
||||
expect(asked.url.searchParams.get('from')).toBe(from().toISOString())
|
||||
expect(asked.url.searchParams.get('until')).toBeNull()
|
||||
expect(within(screen.getByRole('group', { name: 'Period' })).getByRole('button', { name: label })).toHaveAttribute('aria-pressed', 'true')
|
||||
})
|
||||
|
||||
test('with no listens in the period it says so, and the library is still there', async () => {
|
||||
setup({ 'GET /api/v1/stats/listening': () => none })
|
||||
const l = await section('Your listening')
|
||||
expect(within(l).getByText('No listens in this period.')).toBeInTheDocument()
|
||||
expect(within(l).queryByRole('list', { name: 'Top artists' })).not.toBeInTheDocument()
|
||||
expect(within(await section('Your library')).getByText('12,138')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('an empty library says so and shows no charts', async () => {
|
||||
setup({
|
||||
'GET /api/v1/stats/library': () => ({ ...library, artists: 0, albums: 0, songs: 0, duration_ms: 0, size_bytes: 0, formats: [], decades: [], no_year: 0, genres: { top: [], other: 0, untagged: 0, untagged_share: 0 } }),
|
||||
})
|
||||
const lib = await section('Your library')
|
||||
expect(within(lib).getByText('There is no music in the library yet.')).toBeInTheDocument()
|
||||
expect(within(lib).queryByRole('list', { name: 'Genres' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('a failure to read one part does not hide the other', async () => {
|
||||
setup({ 'GET /api/v1/stats/listening': () => apiError(500, 'internal') })
|
||||
expect(within(await section('Your library')).getByText('12,138')).toBeInTheDocument()
|
||||
const l = await section('Your listening')
|
||||
expect(await within(l).findByRole('alert')).toBeInTheDocument()
|
||||
})
|
||||
237
web/src/pages/StatsPage.tsx
Normal file
237
web/src/pages/StatsPage.tsx
Normal file
|
|
@ -0,0 +1,237 @@
|
|||
import { useTranslation } from 'react-i18next'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { PERIODS, useLibraryStats, useListeningStats, type GenreShares, type Period } from '@/api/stats'
|
||||
import { Columns, ShareBars, type Bar } from '@/components/StatBars'
|
||||
import PageTitle from '@/components/PageTitle'
|
||||
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { formatBytes } from '@/lib/bytes'
|
||||
import { formatLength } from '@/lib/time'
|
||||
import { useState, type ReactNode } from 'react'
|
||||
|
||||
/** The title of a block of figures and the figures under it. */
|
||||
function Block({ title, children }: { title: string; children: ReactNode }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<h3 className="text-lg font-bold">{title}</h3>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Figures with their names, side by side: a big number, then what it counts. */
|
||||
function Facts({ facts }: { facts: { name: string; value: string }[] }) {
|
||||
return (
|
||||
<dl className="flex flex-wrap gap-x-10 gap-y-4">
|
||||
{facts.map((f) => (
|
||||
<div key={f.name} className="flex flex-col-reverse">
|
||||
<dt className="text-sm text-muted-foreground">{f.name}</dt>
|
||||
<dd className="text-3xl leading-tight font-extrabold tabular-nums">{f.value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
)
|
||||
}
|
||||
|
||||
/** What a file format is called: the scanner says `mpeg` for the files that are MP3. */
|
||||
const formatName = (format: string) => (format === 'mpeg' ? 'MP3' : format.toUpperCase())
|
||||
|
||||
function useFormat() {
|
||||
const { i18n } = useTranslation()
|
||||
const count = new Intl.NumberFormat(i18n.language)
|
||||
const percent = new Intl.NumberFormat(i18n.language, { style: 'percent', maximumFractionDigits: 0 })
|
||||
return {
|
||||
count: (n: number) => count.format(n),
|
||||
// A share that is there but under a half percent is not "0%".
|
||||
percent: (share: number) => (share > 0 && share < 0.005 ? `<${percent.format(0.01)}` : percent.format(share)),
|
||||
lang: i18n.language,
|
||||
}
|
||||
}
|
||||
|
||||
/** The genres as bars: the biggest, what the smaller ones add up to, and what has no genre. */
|
||||
function GenreBars({ label, genres }: { label: string; genres: GenreShares }) {
|
||||
const { t } = useTranslation()
|
||||
const f = useFormat()
|
||||
const bars: Bar[] = genres.top.map((g) => ({ key: `g:${g.name}`, label: g.name, value: g.share, text: f.percent(g.share) }))
|
||||
if (genres.other > 0) bars.push({ key: 'other', label: t('stats.other'), value: genres.other, text: f.percent(genres.other) })
|
||||
if (genres.untagged > 0) bars.push({ key: 'none', label: t('stats.noGenre'), value: genres.untagged_share, text: f.percent(genres.untagged_share) })
|
||||
if (genres.top.length === 0) return null
|
||||
return <ShareBars label={label} bars={bars} />
|
||||
}
|
||||
|
||||
function LibrarySection() {
|
||||
const { t } = useTranslation()
|
||||
const f = useFormat()
|
||||
const stats = useLibraryStats()
|
||||
const body = () => {
|
||||
if (stats.isError) return <ErrorMessage error={stats.error} onRetry={() => void stats.refetch()} />
|
||||
if (stats.isPending) return <Loading />
|
||||
const lib = stats.data
|
||||
if (lib.songs === 0) return <EmptyMessage>{t('stats.emptyLibrary')}</EmptyMessage>
|
||||
const files = lib.formats.reduce((sum, x) => sum + x.files, 0)
|
||||
const decade = (d: number) => t('stats.decade', { decade: d, short: d >= 2000 ? d : d % 100 })
|
||||
return (
|
||||
<>
|
||||
<Facts
|
||||
facts={[
|
||||
{ name: t('stats.songs'), value: f.count(lib.songs) },
|
||||
{ name: t('stats.albums'), value: f.count(lib.albums) },
|
||||
{ name: t('stats.artists'), value: f.count(lib.artists) },
|
||||
{ name: t('stats.length'), value: formatLength(lib.duration_ms, f.lang) },
|
||||
{ name: t('stats.size'), value: formatBytes(lib.size_bytes) },
|
||||
]}
|
||||
/>
|
||||
{lib.genres.top.length > 0 && (
|
||||
<Block title={t('stats.genres')}>
|
||||
<GenreBars label={t('stats.genres')} genres={lib.genres} />
|
||||
</Block>
|
||||
)}
|
||||
{files > 0 && (
|
||||
<Block title={t('stats.formats')}>
|
||||
<ShareBars
|
||||
label={t('stats.formats')}
|
||||
bars={lib.formats.map((x) => ({ key: x.format, label: formatName(x.format), value: x.files / files, text: f.percent(x.files / files) }))}
|
||||
/>
|
||||
</Block>
|
||||
)}
|
||||
{lib.decades.length > 0 && (
|
||||
<Block title={t('stats.decades')}>
|
||||
<Columns
|
||||
label={t('stats.decades')}
|
||||
columns={lib.decades.map((d) => ({
|
||||
key: String(d.decade),
|
||||
label: lib.decades.length > 6 ? t('stats.decadeShort', { short: String(d.decade % 100).padStart(2, '0') }) : decade(d.decade),
|
||||
value: d.songs,
|
||||
name: t('stats.songsIn', { count: d.songs, label: decade(d.decade), n: f.count(d.songs) }),
|
||||
}))}
|
||||
/>
|
||||
{lib.no_year > 0 && <p className="text-sm text-muted-foreground">{t('stats.noYear', { count: lib.no_year, n: f.count(lib.no_year) })}</p>}
|
||||
</Block>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<section aria-labelledby="stats-library" className="flex max-w-3xl flex-col gap-6">
|
||||
<h2 id="stats-library" className="text-2xl font-bold">
|
||||
{t('stats.library')}
|
||||
</h2>
|
||||
{body()}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function ListeningSection() {
|
||||
const { t } = useTranslation()
|
||||
const f = useFormat()
|
||||
const [period, setPeriod] = useState<Period>('all')
|
||||
const stats = useListeningStats(period)
|
||||
const body = () => {
|
||||
if (stats.isError) return <ErrorMessage error={stats.error} onRetry={() => void stats.refetch()} />
|
||||
if (stats.isPending) return <Loading />
|
||||
const l = stats.data
|
||||
if (l.listens === 0) return <EmptyMessage>{t('stats.none')}</EmptyMessage>
|
||||
const listens = (label: string, n: number) => t('stats.listensIn', { count: n, label, n: f.count(n) })
|
||||
const weekday = new Intl.DateTimeFormat(f.lang, { weekday: 'short' })
|
||||
const day = (i: number) => weekday.format(new Date(2024, 0, 1 + i)) // 1 January 2024 is a Monday
|
||||
const shortYears = l.years.length > 8
|
||||
const rank = (value: number, list: { listens: number }[]) => value / Math.max(1, list[0]?.listens ?? 1)
|
||||
return (
|
||||
<>
|
||||
<Facts
|
||||
facts={[
|
||||
{ name: t('stats.listens'), value: f.count(l.listens) },
|
||||
{ name: t('stats.timeListened'), value: formatLength(l.played_ms, f.lang) },
|
||||
{ name: t('stats.songs'), value: f.count(l.songs) },
|
||||
{ name: t('stats.artists'), value: f.count(l.artists) },
|
||||
...(l.first ? [{ name: t('stats.first'), value: new Intl.DateTimeFormat(f.lang, { dateStyle: 'long' }).format(new Date(l.first)) }] : []),
|
||||
]}
|
||||
/>
|
||||
{l.years.length > 1 && (
|
||||
<Block title={t('stats.byYear')}>
|
||||
<Columns
|
||||
label={t('stats.byYear')}
|
||||
columns={l.years.map((y) => ({ key: String(y.year), label: shortYears ? String(y.year).slice(2) : String(y.year), value: y.listens, name: listens(String(y.year), y.listens) }))}
|
||||
/>
|
||||
</Block>
|
||||
)}
|
||||
<Block title={t('stats.byHour')}>
|
||||
<Columns
|
||||
label={t('stats.byHour')}
|
||||
columns={l.hours.map((n, h) => ({ key: String(h), label: h % 3 === 0 ? String(h) : '', value: n, name: listens(`${h}:00`, n) }))}
|
||||
/>
|
||||
</Block>
|
||||
<Block title={t('stats.byWeekday')}>
|
||||
<Columns
|
||||
label={t('stats.byWeekday')}
|
||||
columns={l.weekdays.map((n, i) => ({ key: String(i), label: day(i), value: n, name: listens(day(i), n) }))}
|
||||
/>
|
||||
</Block>
|
||||
<Block title={t('stats.topArtists')}>
|
||||
<ShareBars
|
||||
label={t('stats.topArtists')}
|
||||
bars={l.top_artists.map((a) => ({
|
||||
key: String(a.id),
|
||||
label: (
|
||||
<Link to={`/artists/${a.id}`} className="hover:underline">
|
||||
{a.name}
|
||||
</Link>
|
||||
),
|
||||
value: rank(a.listens, l.top_artists),
|
||||
text: f.count(a.listens),
|
||||
}))}
|
||||
/>
|
||||
</Block>
|
||||
<Block title={t('stats.topSongs')}>
|
||||
<ShareBars
|
||||
wide
|
||||
label={t('stats.topSongs')}
|
||||
bars={l.top_songs.map((s) => ({
|
||||
key: String(s.id),
|
||||
label: (
|
||||
<span className="flex flex-col">
|
||||
<span className="truncate">{s.title}</span>
|
||||
<span className="truncate text-sm font-normal text-muted-foreground">{s.artists.join(', ')}</span>
|
||||
</span>
|
||||
),
|
||||
value: rank(s.listens, l.top_songs),
|
||||
text: f.count(s.listens),
|
||||
}))}
|
||||
/>
|
||||
</Block>
|
||||
{l.genres.top.length > 0 && (
|
||||
<Block title={t('stats.yourGenres')}>
|
||||
<GenreBars label={t('stats.yourGenres')} genres={l.genres} />
|
||||
</Block>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<section aria-labelledby="stats-listening" className="flex max-w-3xl flex-col gap-6">
|
||||
<h2 id="stats-listening" className="text-2xl font-bold">
|
||||
{t('stats.listening')}
|
||||
</h2>
|
||||
<div role="group" aria-label={t('stats.period')} className="flex flex-wrap gap-2">
|
||||
{PERIODS.map((p) => (
|
||||
<Button key={p} variant={p === period ? 'default' : 'outline'} aria-pressed={p === period} onClick={() => setPeriod(p)}>
|
||||
{t(`stats.periods.${p}`)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
{body()}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/** The statistics: what the library holds, and what the signed-in person listened to, for all time or a period. */
|
||||
export default function StatsPage() {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<div className="flex flex-col gap-10">
|
||||
<PageTitle>{t('nav.stats')}</PageTitle>
|
||||
<LibrarySection />
|
||||
<ListeningSection />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -36,6 +36,7 @@ export const routes: RouteObject[] = [
|
|||
{ path: '/smart-playlists/:id/edit', lazy: page(() => import('@/pages/SmartEditorPage')) },
|
||||
{ path: '/requests', lazy: page(() => import('@/pages/RequestsPage')) },
|
||||
{ path: '/history', lazy: page(() => import('@/pages/HistoryPage')) },
|
||||
{ path: '/stats', lazy: page(() => import('@/pages/StatsPage')) },
|
||||
{ path: '/import', lazy: page(() => import('@/pages/ImportPage')) },
|
||||
{ path: '/settings', lazy: page(() => import('@/pages/SettingsPage')) },
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue