diff --git a/README.md b/README.md index 3795eb0..60a0037 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,10 @@ A fast, responsive browser for Barry Prendergast's curated playlists on [TIDAL]( - Browse every public playlist, artwork first, on any screen size. - Search titles, artist/genre tags and descriptions as you type (accents ignored: "bjork" finds "Björk"). -- Filter by artist or genre, taken from the playlist title — "Night drive (rock)" is tagged *rock*. +- Filter by artist or genre, taken from the playlist title — "Night drive (rock)" is tagged *rock*. Every trailing bracket is its own tag, so "Night drive (rock) (jazz)" is tagged both. +- Sort by when a playlist was created, when it was last updated, or by title, in either direction. - Open a playlist to play it in TIDAL's embedded player, open it in TIDAL, or copy its link. -- Every view has its own URL (`?q=`, `?tag=`, `?sort=`, `?p=`), so it can be shared, bookmarked, and the Back button closes an open playlist. +- Every view has its own URL (`?q=`, `?tag=`, `?sort=created|updated|title`, `?order=asc|desc`, `?p=`), so it can be shared, bookmarked, and the Back button closes an open playlist. ## Quick start diff --git a/public/css/app.css b/public/css/app.css index 9b623ae..2f53f52 100644 --- a/public/css/app.css +++ b/public/css/app.css @@ -400,6 +400,7 @@ main:focus { } .sort { + position: relative; display: flex; align-items: center; gap: 0.625rem; @@ -407,118 +408,159 @@ main:focus { font-size: 0.875rem; } -/* A dropdown that matches the chips: 10% grey, 16% on hover, a chevron. */ -.select { - --chevron: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23fff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E"); +/* The button that opens the menu: 10% grey, 16% on hover and while open, like the chips. */ +.sort-button { + display: inline-flex; + align-items: center; + gap: 0.5rem; min-height: var(--tap); - padding: 0.5rem 2.5rem 0.5rem 1rem; - background: var(--grey-10) var(--chevron) no-repeat right 0.75rem center / 1.125rem; + padding: 0.5rem 0.875rem 0.5rem 1rem; + background: var(--grey-10); border: 1px solid transparent; border-radius: var(--radius-m); color: var(--text); font-size: 0.9375rem; font-weight: 500; + white-space: nowrap; cursor: pointer; - appearance: none; transition: background-color var(--fast) ease-out; } -.select:hover { - background-color: var(--grey-16); +.sort-button:hover, +.sort-button[aria-expanded='true'] { + background: var(--grey-16); } -/* Chrome and Safari can also style the open list (customisable select). */ -@supports (appearance: base-select) { - .select, - .select::picker(select) { - appearance: base-select; - } +.sort-glyph, +.sort-chevron { + color: var(--text-2); +} - .select { - background-image: none; - display: inline-flex; - align-items: center; - justify-content: space-between; - gap: 0.75rem; - padding-right: 0.875rem; - } +/* The arrow shows which way round the list currently runs. */ +.sort-button[data-order='asc'] .sort-glyph-desc, +.sort-button:not([data-order='asc']) .sort-glyph-asc { + display: none; +} - /* Lucide chevron in place of the browser's default triangle. */ - .select::picker-icon { - content: ''; - width: 1.125rem; - height: 1.125rem; - background: var(--text-2); - -webkit-mask: var(--chevron) center / contain no-repeat; - mask: var(--chevron) center / contain no-repeat; - transition: rotate var(--base) var(--ease-out); - } +.sort-chevron { + transition: rotate var(--base) var(--ease-out); +} + +.sort-button[aria-expanded='true'] .sort-chevron { + rotate: 180deg; +} + +/* The menu: frosted glass, with what to sort by above a line and which way round below it. */ +.sort-menu { + --tick: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M20 6 9 17l-5-5'/%3E%3C/svg%3E"); + position: absolute; + top: calc(100% + 0.375rem); + right: 0; + z-index: 1; + min-width: 14.5rem; + padding: 0.375rem; + background: hsl(0 0% 11% / 0.96); + border: 1px solid var(--line); + border-radius: var(--radius-m); + box-shadow: 0 24px 48px -12px hsl(0 0% 0% / 0.8); + transition: opacity var(--fast) ease-out, translate var(--base) var(--ease-out); - .select:open::picker-icon { - rotate: 180deg; + @starting-style { + opacity: 0; + translate: 0 -0.25rem; } +} - .select::picker(select) { - margin-top: 0.375rem; - padding: 0.375rem; +@supports (backdrop-filter: blur(1px)) or (-webkit-backdrop-filter: blur(1px)) { + .sort-menu { background: hsl(0 0% 11% / 0.9); -webkit-backdrop-filter: var(--glass-blur); backdrop-filter: var(--glass-blur); - border: 1px solid var(--line); - border-radius: var(--radius-m); - box-shadow: 0 24px 48px -12px hsl(0 0% 0% / 0.8); } +} - .select option { - display: flex; - align-items: center; - gap: 0.5rem; - min-height: 2.5rem; - padding: 0.5rem 0.75rem; - border-radius: calc(var(--radius-m) - 0.25rem); - font-weight: 500; - cursor: pointer; - } +.sort-group { + min-inline-size: 0; + margin: 0; + padding: 0; + border: 0; +} - .select option:hover, - .select option:focus-visible { - background: var(--grey-16); - outline: none; - } +.sort-group + .sort-group { + margin-top: 0.375rem; + padding-top: 0.375rem; + border-top: 1px solid var(--line); +} - .select option:checked { - background: var(--cyan-wash); - } +.sort-option { + position: relative; + display: flex; + align-items: center; + gap: 0.5rem; + min-height: 2.5rem; + padding: 0.5rem 0.75rem; + border-radius: calc(var(--radius-m) - 0.25rem); + color: var(--text); + font-size: 0.9375rem; + font-weight: 500; + white-space: nowrap; + cursor: pointer; +} - .select option::checkmark { - color: var(--cyan); - } +/* A cyan tick marks the choice in force; the radio itself is invisible but covers the row. */ +.sort-option::before { + content: ''; + flex: none; + width: 1.125rem; + height: 1.125rem; + background: var(--cyan); + -webkit-mask: var(--tick) center / contain no-repeat; + mask: var(--tick) center / contain no-repeat; + opacity: 0; +} + +.sort-option input { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + margin: 0; + opacity: 0; + cursor: pointer; + appearance: none; +} + +.sort-option:hover { + background: var(--grey-16); +} + +.sort-option:has(:checked) { + background: var(--cyan-wash); +} + +.sort-option:has(:checked)::before { + opacity: 1; +} + +.sort-option:has(:focus-visible) { + outline: 2px solid var(--cyan); + outline-offset: -2px; } @media (max-width: 30rem) { - /* Keep the search field wide enough for its placeholder. */ + /* Keep the search field wide enough for its placeholder: the arrow stays, the chevron goes. */ .filters { gap: 0.5rem; } - .select { - padding-left: 0.625rem; - padding-right: 1.75rem; + .sort-button { + gap: 0.375rem; + padding-inline: 0.625rem; font-size: 0.875rem; - background-position: right 0.5rem center; - background-size: 1rem; } - @supports (appearance: base-select) { - .select { - padding-right: 0.5rem; - gap: 0.25rem; - } - - .select::picker-icon { - width: 1rem; - height: 1rem; - } + .sort-chevron { + display: none; } .search-field .icon { @@ -650,18 +692,19 @@ main:focus { } } +/* Every card has the same four rows, top to bottom: artwork, title, tags, stats. */ .card { position: relative; display: flex; flex-direction: column; - gap: 0.25rem; + gap: 0.375rem; min-width: 0; } .card-art { position: relative; aspect-ratio: 1; - margin-bottom: 0.5rem; + margin-bottom: 0.25rem; overflow: hidden; border-radius: var(--radius-s); background: var(--art, var(--grey-10)); @@ -723,16 +766,14 @@ main:focus { text-transform: uppercase; } +/* One line, so titles line up across a row; the full title is in the link's tooltip. */ .card-title { + overflow: hidden; font-size: 1rem; font-weight: 600; line-height: 1.3; - overflow-wrap: anywhere; - display: -webkit-box; - -webkit-box-orient: vertical; - -webkit-line-clamp: 2; - line-clamp: 2; - overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .card-link { @@ -740,7 +781,7 @@ main:focus { text-decoration: none; } -/* The whole card is clickable; the tag chip sits above this overlay. */ +/* The whole card is clickable; the tag chips sit above this overlay. */ .card-link::after { content: ''; position: absolute; @@ -757,52 +798,35 @@ main:focus { outline-offset: 2px; } -.card-meta { +/* One chip per tag. The row keeps its height when there are none, so the rows below stay level. */ +.card-tags { display: flex; flex-wrap: wrap; - align-items: center; - gap: 0.375rem 0.625rem; - color: var(--text-2); + align-content: flex-start; + gap: 0.375rem; + min-height: 1.625rem; } -.card-meta .tag-chip { +/* Block rather than inline-flex, so a tag too long for the card ends in an ellipsis. */ +.card-tags .tag-chip { position: relative; z-index: 1; + display: block; min-height: 1.625rem; max-width: 100%; padding: 0 0.625rem; overflow: hidden; - text-overflow: ellipsis; font-size: 0.75rem; + line-height: 1.5rem; + text-overflow: ellipsis; } +/* Pinned to the bottom, so stats line up even when a neighbour's tags wrap onto a second line. */ .card-stats { - font-size: 0.6875rem; - font-weight: 500; - letter-spacing: 0.08em; - text-transform: uppercase; -} - -.card-description { + margin-top: auto; color: var(--text-2); font-size: 0.8125rem; - line-height: 1.45; - display: -webkit-box; - -webkit-box-orient: vertical; - -webkit-line-clamp: 2; - line-clamp: 2; - overflow: hidden; -} - -.card-description:empty { - display: none; -} - -/* Only the two-column phone layout (400-480px) is too tight for descriptions. */ -@media (min-width: 25rem) and (max-width: 30rem) { - .card-description { - display: none; - } + font-variant-numeric: tabular-nums; } /* Loading skeleton ----------------------------------------------------------- */ @@ -886,9 +910,12 @@ main:focus { .sheet { width: min(100% - 2rem, 66rem); max-width: none; - max-height: min(100% - 2rem, 50rem); + /* A set height, so the player always fits inside the padding whatever the playlist; the + details beside it scroll when they need to. */ + height: min(100% - 2rem, 50rem); + max-height: none; padding: 0; - overflow: auto; + overflow: hidden; overscroll-behavior: contain; background: radial-gradient(110% 70% at 0% 0%, color-mix(in srgb, var(--art, var(--cyan)) 30%, transparent), transparent 65%), @@ -918,18 +945,26 @@ main:focus { .sheet-layout { position: relative; display: grid; + height: 100%; grid-template-columns: minmax(0, 19rem) minmax(0, 1fr); - grid-template-rows: auto auto auto 1fr; - grid-template-areas: - 'art player' - 'head player' - 'desc player' - 'body player'; - gap: 1rem 2rem; + grid-template-rows: minmax(0, 1fr); + grid-template-areas: 'info player'; + gap: 2rem; /* The top padding leaves room for the close button, clear of TIDAL's player. */ padding: 3.5rem 2rem 2rem; } +/* Artwork, details and actions: one column that scrolls beside the player if it is too tall. */ +.sheet-info { + grid-area: info; + display: flex; + flex-direction: column; + gap: 1rem; + min-height: 0; + overflow-y: auto; + overscroll-behavior: contain; +} + .sheet-close { position: absolute; top: 0.5rem; @@ -952,7 +987,7 @@ main:focus { } .sheet-art { - grid-area: art; + flex: none; position: relative; aspect-ratio: 1; overflow: hidden; @@ -962,7 +997,7 @@ main:focus { } .sheet-head { - grid-area: head; + flex: none; display: grid; gap: 0.25rem; } @@ -990,14 +1025,13 @@ main:focus { } .sheet-body { - grid-area: body; + flex: none; display: grid; align-content: start; gap: 1rem; } .sheet-description { - grid-area: desc; color: var(--text-2); white-space: pre-line; text-wrap: pretty; @@ -1026,7 +1060,7 @@ main:focus { .sheet-player { grid-area: player; position: relative; - min-height: 30rem; + min-height: 0; overflow: hidden; border-radius: var(--radius-m); background: var(--grey-10); @@ -1084,12 +1118,15 @@ main:focus { max-height: 100%; height: 100%; margin: 0; + overflow: auto; border: 0; border-radius: 0; } - /* Actions before the player: on a phone, "Open in TIDAL" is the main event. */ + /* Actions before the player: on a phone, "Open in TIDAL" is the main event. The sheet scrolls + as a whole, so the details join the layout's own grid. */ .sheet-layout { + height: auto; min-height: 100%; grid-template-columns: 5.5rem minmax(0, 1fr); grid-template-rows: auto auto auto auto; @@ -1098,16 +1135,34 @@ main:focus { 'body body' 'player player' 'desc desc'; + gap: 1rem; align-items: center; padding: 1rem var(--gutter) max(1.5rem, env(safe-area-inset-bottom)); } + .sheet-info { + display: contents; + } + + .sheet-art { + grid-area: art; + } + .sheet-head { + grid-area: head; padding-right: 3rem; } + .sheet-body { + grid-area: body; + } + + .sheet-description { + grid-area: desc; + } + .sheet-player { - min-height: 0; + grid-area: player; height: min(62dvh, 32rem); } } diff --git a/public/js/constants.js b/public/js/constants.js index e5c6bec..014fa31 100644 --- a/public/js/constants.js +++ b/public/js/constants.js @@ -2,8 +2,10 @@ // the first artwork). Keep this file free of DOM access. /** localStorage keys. Bump the version when the cached record shape changes. */ -export const CACHE_KEY = 'selections:v1'; -export const CACHE_ETAG_KEY = 'selections:v1:etag'; +export const CACHE_KEY = 'selections:v2'; +export const CACHE_ETAG_KEY = 'selections:v2:etag'; +/** Keys from earlier record shapes (v1 had a single `tag`); removed so they don't linger in storage. */ +export const LEGACY_CACHE_KEYS = ['selections:v1', 'selections:v1:etag']; /** Approximate rendered width of a grid card's artwork; mirrors the grid in app.css. */ export const CARD_IMAGE_SIZES = '(min-width: 80rem) 14rem, (min-width: 40rem) 30vw, (min-width: 25rem) 50vw, 100vw'; diff --git a/public/js/dialog.js b/public/js/dialog.js index 532dd3a..0fa4224 100644 --- a/public/js/dialog.js +++ b/public/js/dialog.js @@ -71,6 +71,7 @@ async function writeClipboard(text, container) { export function createPlaylistDialog({ dialog, onClose }) { const $ = (selector) => dialog.querySelector(selector); const ui = { + info: $('.sheet-info'), img: $('.sheet-art img'), tag: $('.sheet-tag'), title: $('.sheet-title'), @@ -122,8 +123,8 @@ export function createPlaylistDialog({ dialog, onClose }) { dialog.classList.toggle('no-art', !record.art); dialog.style.setProperty('--art', record.art?.color ?? ''); setArtwork(ui.img, record.art, { sizes: DIALOG_ART_SIZES, loading: 'eager' }); - ui.tag.textContent = record.tag ?? ''; - ui.tag.hidden = !record.tag; + ui.tag.textContent = record.tags.join(' · '); + ui.tag.hidden = !record.tags.length; ui.title.textContent = record.title; ui.stats.textContent = joinStats( formatTracks(record.tracks), @@ -197,7 +198,9 @@ export function createPlaylistDialog({ dialog, onClose }) { current = record; fill(record); if (!dialog.open) dialog.showModal(); - dialog.scrollTop = 0; + dialog.scrollTop = 0; // The full-screen sheet on phones scrolls as a whole... + ui.info.scrollTop = 0; // ...while on larger screens the details scroll beside the player. + ui.description.scrollTop = 0; loadPlayer(record); }, close, diff --git a/public/js/filter.js b/public/js/filter.js index fed1ac4..dd2a542 100644 --- a/public/js/filter.js +++ b/public/js/filter.js @@ -11,34 +11,62 @@ export const fold = (text) => export const tagKey = (tag) => (tag ? fold(tag).trim() : ''); -/** Text searched for a record: its title, artist/genre tag and description. */ -export const searchText = (record) => fold([record.title, record.tag, record.description].filter(Boolean).join('\n')); +/** Text searched for a record: its title, artist/genre tags and description. */ +export const searchText = (record) => fold([record.title, ...record.tags, record.description].filter(Boolean).join('\n')); export const parseQuery = (query) => fold(query).split(/\s+/).filter(Boolean); /** Every word of the query must appear somewhere in the record. */ export const matches = (text, terms) => terms.every((term) => text.includes(term)); +// ISO 8601 dates sort chronologically as plain text. +const compareDates = (a, b) => (a < b ? -1 : a > b ? 1 : 0); + +/** What each sort looks at, and the direction people expect first: newest dates first, titles A–Z. */ export const SORTS = { - newest: (a, b) => (b.createdAt ?? '').localeCompare(a.createdAt ?? '') || collator.compare(a.title, b.title), - updated: (a, b) => (b.updatedAt ?? '').localeCompare(a.updatedAt ?? '') || collator.compare(a.title, b.title), - az: (a, b) => collator.compare(a.title, b.title) || collator.compare(a.tag ?? '', b.tag ?? ''), + created: { natural: 'desc', value: (record) => record.createdAt, compare: compareDates }, + updated: { natural: 'desc', value: (record) => record.updatedAt, compare: compareDates }, + title: { natural: 'asc', value: (record) => record.title, compare: collator.compare }, }; -export const DEFAULT_SORT = 'newest'; -export const isSort = (value) => Object.hasOwn(SORTS, value); +export const DEFAULT_SORT = 'created'; +export const ORDERS = ['asc', 'desc']; + +// Links shared before the sort menu had a direction. +const LEGACY_SORTS = new Map([ + ['newest', 'created'], + ['az', 'title'], +]); + +/** A known sort name, with old names translated; anything else is the default. */ +export const parseSort = (value) => (Object.hasOwn(SORTS, value) ? value : (LEGACY_SORTS.get(value) ?? DEFAULT_SORT)); + +/** A known direction, or the one people expect for this sort. */ +export const parseOrder = (value, sort) => (ORDERS.includes(value) ? value : SORTS[parseSort(sort)].natural); + +function comparator(sort, order) { + const { value, compare } = SORTS[sort]; + const sign = order === 'asc' ? 1 : -1; + return (a, b) => { + const x = value(a) ?? ''; + const y = value(b) ?? ''; + if (!x !== !y) return x ? -1 : 1; // A playlist missing the value (say, an unknown date) goes last either way. + return (x && sign * compare(x, y)) || collator.compare(a.title, b.title) || collator.compare(a.tags.join(), b.tags.join()); + }; +} /** * Applies a view to `entries` ({ record, text }) and returns the visible * records in order. */ -export function applyView(entries, { query = '', tag = '', sort = DEFAULT_SORT } = {}) { +export function applyView(entries, { query = '', tag = '', sort = DEFAULT_SORT, order } = {}) { const terms = parseQuery(query); const key = tagKey(tag); + const field = parseSort(sort); return entries - .filter((entry) => (!key || tagKey(entry.record.tag) === key) && matches(entry.text, terms)) + .filter((entry) => (!key || entry.record.tags.some((t) => tagKey(t) === key)) && matches(entry.text, terms)) .map((entry) => entry.record) - .sort(SORTS[isSort(sort) ? sort : DEFAULT_SORT]); + .sort(comparator(field, parseOrder(order, field))); } /** @@ -47,12 +75,16 @@ export function applyView(entries, { query = '', tag = '', sort = DEFAULT_SORT } */ export function popularTags(records, { min = 2, limit = 24 } = {}) { const byKey = new Map(); - for (const { tag } of records) { - const key = tagKey(tag); - if (!key) continue; - const entry = byKey.get(key) ?? { key, label: tag, count: 0 }; - entry.count++; - byKey.set(key, entry); + for (const { tags } of records) { + const seen = new Set(); // A playlist counts once towards a tag, however it is capitalised. + for (const tag of tags) { + const key = tagKey(tag); + if (!key || seen.has(key)) continue; + seen.add(key); + const entry = byKey.get(key) ?? { key, label: tag, count: 0 }; + entry.count++; + byKey.set(key, entry); + } } return [...byKey.values()] .filter((entry) => entry.count >= min) diff --git a/public/js/grid.js b/public/js/grid.js index d118482..e3a60bb 100644 --- a/public/js/grid.js +++ b/public/js/grid.js @@ -44,6 +44,17 @@ export function setArtwork(img, art, { sizes, loading = 'lazy', priority = false img.src = fallbackSrc(art); } +/** A clickable tag; the grid's delegated click handler turns it into a filter. */ +function makeTagChip(tag) { + const chip = document.createElement('button'); + chip.type = 'button'; + chip.className = 'tag-chip'; + chip.dataset.tag = tag; + chip.textContent = tag; + chip.setAttribute('aria-label', `Show all “${tag}” playlists`); + return chip; +} + export function createGrid({ list, template, onOpen, onTag }) { const cards = new Map(); // id → { el, rev } let order = null; // null until the first render, so the loading skeletons are always replaced @@ -65,15 +76,10 @@ export function createGrid({ list, template, onOpen, onTag }) { const link = el.querySelector('.card-link'); link.href = `?p=${encodeURIComponent(record.id)}`; link.textContent = record.title; + link.title = record.title; // The card shows one line, so long titles are cut short. - const tag = el.querySelector('.tag-chip'); - tag.hidden = !record.tag; - tag.textContent = record.tag ?? ''; - tag.dataset.tag = record.tag ?? ''; - tag.setAttribute('aria-label', record.tag ? `Show all “${record.tag}” playlists` : ''); - + el.querySelector('.card-tags').replaceChildren(...record.tags.map(makeTagChip)); el.querySelector('.card-stats').textContent = joinStats(formatTracks(record.tracks), formatDuration(record.duration)); - el.querySelector('.card-description').textContent = record.description ?? ''; el.querySelector('.badge').hidden = !isNew(record); } diff --git a/public/js/main.js b/public/js/main.js index a6ce4f9..07a8710 100644 --- a/public/js/main.js +++ b/public/js/main.js @@ -1,10 +1,11 @@ import './error-handlers.js'; import { ApiError } from './api.js'; import { createPlaylistDialog } from './dialog.js'; -import { DEFAULT_SORT, applyView, isSort, popularTags, searchText, tagKey } from './filter.js'; +import { DEFAULT_SORT, SORTS, applyView, parseOrder, parseSort, popularTags, searchText, tagKey } from './filter.js'; import { formatDate } from './format.js'; import { createGrid } from './grid.js'; import { reportError } from './report.js'; +import { createSortMenu } from './sort-menu.js'; import { loadCache, saveCache } from './store.js'; import { syncPlaylists } from './sync.js'; import { showToast } from './toast.js'; @@ -17,7 +18,6 @@ const els = { main: $('playlists'), form: $('filters'), search: $('search'), - sort: $('sort'), count: $('result-count'), announcer: $('announcer'), clear: $('clear-filters'), @@ -43,12 +43,12 @@ const state = { const plural = (n, word) => `${n.toLocaleString('en-GB')} ${word}${n === 1 ? '' : 's'}`; // --- URL state --------------------------------------------------------------------- -// ?q= search, ?tag= artist/genre, ?sort=, ?p= open playlist. Shareable and bookmarkable. +// ?q= search, ?tag= artist/genre, ?sort= and ?order=, ?p= open playlist. Shareable and bookmarkable. function readViewFromUrl() { const params = new URL(location.href).searchParams; - const sort = params.get('sort'); - return { query: params.get('q') ?? '', tag: params.get('tag') ?? '', sort: isSort(sort) ? sort : DEFAULT_SORT }; + const sort = parseSort(params.get('sort')); + return { query: params.get('q') ?? '', tag: params.get('tag') ?? '', sort, order: parseOrder(params.get('order'), sort) }; } let urlTimer; @@ -60,6 +60,7 @@ function flushViewToUrl() { set('q', state.view.query.trim()); set('tag', state.view.tag); set('sort', state.view.sort === DEFAULT_SORT ? '' : state.view.sort); + set('order', state.view.order === SORTS[state.view.sort].natural ? '' : state.view.order); if (url.href !== location.href) history.replaceState(history.state, '', url); } @@ -83,6 +84,8 @@ const grid = createGrid({ const sheet = createPlaylistDialog({ dialog: $('playlist-dialog'), onClose: handleDialogClosed }); +const sortMenu = createSortMenu({ root: $('sort'), onChange: ({ sort, order }) => setView({ sort, order }) }); + function makeTagChip({ label, count, key }) { const chip = document.createElement('button'); chip.type = 'button'; @@ -162,7 +165,7 @@ function setView(changes) { function syncControls() { if (els.search.value !== state.view.query) els.search.value = state.view.query; - els.sort.value = state.view.sort; + sortMenu.sync(state.view); } /** "Latest added 23 Oct 2026" in the masthead, from the newest playlist. */ @@ -316,7 +319,6 @@ async function refresh({ boot } = {}) { // --- Controls -------------------------------------------------------------------------------- els.search.addEventListener('input', () => setView({ query: els.search.value })); -els.sort.addEventListener('change', () => setView({ sort: els.sort.value })); els.form.addEventListener('submit', (event) => { event.preventDefault(); els.search.blur(); // Closes the on-screen keyboard on phones. diff --git a/public/js/sort-menu.js b/public/js/sort-menu.js new file mode 100644 index 0000000..eff729c --- /dev/null +++ b/public/js/sort-menu.js @@ -0,0 +1,90 @@ +// The sort menu: one button that opens two groups of choices, what to sort by and +// which way round. Built from plain radio buttons, so arrow keys, Tab and screen +// readers behave as they do in any form. + +import { SORTS } from './filter.js'; + +const DATES = { desc: 'Newest first', asc: 'Oldest first' }; +const ALPHABETICAL = { asc: 'A–Z', desc: 'Z–A' }; +/** The two directions read differently for dates and for titles. */ +const ORDER_LABELS = { created: DATES, updated: DATES, title: ALPHABETICAL }; + +/** Pointer picks close the menu once the new choice has been seen to take. */ +const CLOSE_AFTER_PICK_MS = 150; + +export function createSortMenu({ root, onChange }) { + const button = root.querySelector('.sort-button'); + const menu = root.querySelector('.sort-menu'); + const current = root.querySelector('.sort-current'); + const orderGroup = root.querySelector('.sort-orders'); + const input = (name, value) => menu.querySelector(`input[name="${name}"][value="${value}"]`); + const orderOptions = { asc: input('order', 'asc').closest('.sort-option'), desc: input('order', 'desc').closest('.sort-option') }; + + const isOpen = () => !menu.hidden; + + function open() { + menu.hidden = false; + button.setAttribute('aria-expanded', 'true'); + menu.querySelector('input[name="sort"]:checked')?.focus({ preventScroll: true }); + } + + function close({ restoreFocus = false } = {}) { + if (!isOpen()) return; + const hadFocus = menu.contains(document.activeElement); + menu.hidden = true; + button.setAttribute('aria-expanded', 'false'); + if (restoreFocus || hadFocus) button.focus({ preventScroll: true }); + } + + /** Shows `{ sort, order }`: ticks, the direction labels for this sort, and the button's summary. */ + function sync({ sort, order }) { + const sortInput = input('sort', sort); + sortInput.checked = true; + + const labels = ORDER_LABELS[sort]; + for (const key of Object.keys(orderOptions)) orderOptions[key].querySelector('span').textContent = labels[key]; + // The expected direction goes first, so arrow keys move the way the list reads. + const [first, second] = SORTS[sort].natural === 'desc' ? [orderOptions.desc, orderOptions.asc] : [orderOptions.asc, orderOptions.desc]; + if (orderGroup.querySelector('.sort-option') !== first) orderGroup.append(first, second); + input('order', order).checked = true; + + const name = sortInput.nextElementSibling.textContent; + current.textContent = name; + button.dataset.order = order; + button.setAttribute('aria-label', `Sort: ${name}, ${labels[order]}`); + } + + button.addEventListener('click', () => (isOpen() ? close() : open())); + + button.addEventListener('keydown', (event) => { + if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return; + event.preventDefault(); + if (!isOpen()) open(); + }); + + menu.addEventListener('change', (event) => { + const sort = event.target.name === 'sort' ? event.target.value : menu.querySelector('input[name="sort"]:checked').value; + // Choosing a different sort starts from the direction people expect for it. + onChange({ sort, order: event.target.name === 'order' ? event.target.value : SORTS[sort].natural }); + }); + + menu.addEventListener('pointerup', (event) => { + if (event.target.closest('.sort-option')) setTimeout(() => close({ restoreFocus: true }), CLOSE_AFTER_PICK_MS); + }); + + root.addEventListener('keydown', (event) => { + if (event.key !== 'Escape' || !isOpen()) return; + event.preventDefault(); + close({ restoreFocus: true }); + }); + + root.addEventListener('focusout', (event) => { + if (event.relatedTarget && !root.contains(event.relatedTarget)) close(); + }); + + document.addEventListener('pointerdown', (event) => { + if (!root.contains(event.target)) close(); + }); + + return { sync }; +} diff --git a/public/js/store.js b/public/js/store.js index 7c3a161..d4a31ce 100644 --- a/public/js/store.js +++ b/public/js/store.js @@ -1,7 +1,7 @@ // The browser's copy of the playlists, kept in localStorage so repeat visits // render instantly and only download what changed. ~100 KB for 150 playlists. -import { CACHE_ETAG_KEY, CACHE_KEY } from './constants.js'; +import { CACHE_ETAG_KEY, CACHE_KEY, LEGACY_CACHE_KEYS } from './constants.js'; import { reportError } from './report.js'; export const isRecord = (record) => @@ -29,6 +29,7 @@ export function loadCache() { const store = storage(); if (!store) return null; try { + for (const key of LEGACY_CACHE_KEYS) store.removeItem(key); const raw = store.getItem(CACHE_KEY); if (!raw) return null; const data = JSON.parse(raw); diff --git a/src/http/icons.js b/src/http/icons.js index 78ad74b..a45b17c 100644 --- a/src/http/icons.js +++ b/src/http/icons.js @@ -13,6 +13,9 @@ const PATHS = { 'external-link': '', copy: '', check: '', + 'chevron-down': '', + 'arrow-down-wide-narrow': '', + 'arrow-up-narrow-wide': '', }; /** Decorative inline SVG for a Lucide icon (hidden from screen readers; label the control instead). */ diff --git a/src/tidal/mock.js b/src/tidal/mock.js index 1b7c3b2..3bb654a 100644 --- a/src/tidal/mock.js +++ b/src/tidal/mock.js @@ -13,8 +13,10 @@ const uuid = (i) => `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`; function buildPlaylists(count, now) { return Array.from({ length: count }, (_, i) => { const single = i % 3 === 0; - const tag = single ? pick(ARTISTS, i) : pick(GENRES, i * 7); - const name = `${pick(WORDS, i * 5)} ${pick(WORDS, i * 11 + 3)} (${tag})`; + // Mixes sometimes carry a second genre, and one title is long enough to be truncated. + const tags = single ? [pick(ARTISTS, i)] : [pick(GENRES, i * 7), ...(i % 4 === 1 ? [pick(GENRES, i * 3 + 1)] : [])]; + const title = i === 7 ? 'A Very Long Playlist Title That Keeps Going and Going' : `${pick(WORDS, i * 5)} ${pick(WORDS, i * 11 + 3)}`; + const name = `${title} ${tags.map((tag) => `(${tag})`).join(' ')}`; const tracks = 12 + ((i * 37) % 80); return { id: uuid(i + 1), @@ -22,8 +24,8 @@ function buildPlaylists(count, now) { attributes: { name: i === 4 ? 'Untitled mix without a tag' : name, description: single - ? `A deep dive through the back catalogue of ${tag}, from the hits to the B-sides.` - : `Weekly selection of ${tag} — new finds & old favourites, sequenced for start-to-finish listening.`, + ? `A deep dive through the back catalogue of ${tags[0]}, from the hits to the B-sides.` + : `Weekly selection of ${tags.join(' and ')} — new finds & old favourites, sequenced for start-to-finish listening.`, accessType: i % 25 === 24 ? 'PRIVATE' : 'PUBLIC', bounded: true, createdAt: new Date(now - (i * 9 + 2) * DAY).toISOString(), diff --git a/src/tidal/normalise.js b/src/tidal/normalise.js index 4ea83a6..df00902 100644 --- a/src/tidal/normalise.js +++ b/src/tidal/normalise.js @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto'; -// Trailing "(…)" holds the artist (single-artist playlists) or genre (mixes). -const TITLE_WITH_TAG = /^(.*\S)\s*\(\s*([^()]*?)\s*\)\s*$/; +// Each trailing "(…)" holds a tag: the artist (single-artist playlists) or genre (mixes). +const TRAILING_TAG = /^(.*\S)\s*\(\s*([^()]*?)\s*\)\s*$/; const ISO_DURATION = /^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/; const HEX_COLOUR = /^#?([0-9a-f]{6}|[0-9a-f]{3})$/i; const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", '#39': "'", nbsp: ' ' }; @@ -9,11 +9,15 @@ const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", '#39': "'", const MIN_ART_WIDTH = 100; const MAX_ART_WIDTH = 1280; +/** "Night drive (rock) (jazz)" → { title: "Night drive", tags: ["rock", "jazz"] }. Brackets mid-title stay in the title. */ export function parseTitle(name) { - const clean = String(name ?? '').replace(/\s+/g, ' ').trim(); - const match = clean.match(TITLE_WITH_TAG); - if (!match || !match[2]) return { title: clean, tag: null }; - return { title: match[1], tag: match[2] }; + let title = String(name ?? '').replace(/\s+/g, ' ').trim(); + const tags = []; + for (let match = title.match(TRAILING_TAG); match?.[2]; match = title.match(TRAILING_TAG)) { + tags.unshift(match[2]); + title = match[1]; + } + return { title, tags }; } /** "PT1H2M3S" → 3723 (seconds), or null when missing/invalid. */ @@ -87,7 +91,7 @@ export function normalisePlaylist(resource, artworksById = new Map()) { if (typeof resource?.id !== 'string' || !attributes) return null; if (attributes.accessType !== 'PUBLIC') return null; - const { title, tag } = parseTitle(attributes.name); + const { title, tags } = parseTitle(attributes.name); if (!title) return null; const share = attributes.externalLinks?.find((link) => link?.meta?.type === 'TIDAL_SHARING')?.href; @@ -97,7 +101,7 @@ export function normalisePlaylist(resource, artworksById = new Map()) { const record = { id: resource.id, title, - tag, + tags, description: cleanText(attributes.description), tracks: count(attributes.numberOfTrackItems) ?? count(attributes.numberOfItems), duration: parseDuration(attributes.duration), diff --git a/test/browser-logic.test.js b/test/browser-logic.test.js index 8b9d48e..2691ec9 100644 --- a/test/browser-logic.test.js +++ b/test/browser-logic.test.js @@ -1,18 +1,18 @@ // The browser modules' pure logic, run in Node. import assert from 'node:assert/strict'; import { afterEach, describe, it } from 'node:test'; -import { DEFAULT_SORT, applyView, fold, popularTags, searchText } from '../public/js/filter.js'; +import { DEFAULT_SORT, applyView, fold, parseOrder, parseSort, popularTags, searchText } from '../public/js/filter.js'; import { formatDuration, formatFollowers, formatTracks, isNew, joinStats } from '../public/js/format.js'; import { diffManifest, mergePlaylists, syncPlaylists } from '../public/js/sync.js'; import { jsonResponse } from './helpers.js'; -const record = (id, extra = {}) => ({ id, rev: `${id}-1`, title: `Title ${id}`, tag: null, description: '', createdAt: '2024-01-01T00:00:00Z', updatedAt: '2024-01-01T00:00:00Z', ...extra }); +const record = (id, extra = {}) => ({ id, rev: `${id}-1`, title: `Title ${id}`, tags: [], description: '', createdAt: '2024-01-01T00:00:00Z', updatedAt: '2024-01-01T00:00:00Z', ...extra }); describe('search and filters', () => { const records = [ - record('a', { title: 'Night Bloom', tag: 'Björk', description: 'Icelandic deep dive', createdAt: '2024-03-01T00:00:00Z' }), - record('b', { title: 'Static Drive', tag: 'rock', description: 'Guitars & motorways', createdAt: '2024-05-01T00:00:00Z', updatedAt: '2024-01-02T00:00:00Z' }), - record('c', { title: 'after Dark', tag: 'Rock', description: 'Late night rock', createdAt: '2024-04-01T00:00:00Z', updatedAt: '2024-09-01T00:00:00Z' }), + record('a', { title: 'Night Bloom', tags: ['Björk'], description: 'Icelandic deep dive', createdAt: '2024-03-01T00:00:00Z' }), + record('b', { title: 'Static Drive', tags: ['rock'], description: 'Guitars & motorways', createdAt: '2024-05-01T00:00:00Z', updatedAt: '2024-01-02T00:00:00Z' }), + record('c', { title: 'after Dark', tags: ['Rock', 'Jazz'], description: 'Late night rock', createdAt: '2024-04-01T00:00:00Z', updatedAt: '2024-09-01T00:00:00Z' }), ]; const entries = records.map((r) => ({ record: r, text: searchText(r) })); const ids = (view) => applyView(entries, view).map((r) => r.id); @@ -26,24 +26,74 @@ describe('search and filters', () => { assert.deepEqual(ids({ query: 'motorways' }), ['b']); assert.deepEqual(ids({ query: 'night' }).sort(), ['a', 'c']); assert.deepEqual(ids({ query: 'night rock' }), ['c']); + assert.deepEqual(ids({ query: 'jazz' }), ['c']); assert.deepEqual(ids({ query: ' ' }).length, 3); }); - it('filters by tag, case-insensitively', () => { + it('filters by tag, case-insensitively, whichever of a playlist\'s tags it is', () => { assert.deepEqual(ids({ tag: 'ROCK' }), ['b', 'c']); + assert.deepEqual(ids({ tag: 'jazz' }), ['c']); }); - it('sorts newest first by default, or by update, or A–Z', () => { - assert.equal(DEFAULT_SORT, 'newest'); + it('lists tags shared by several playlists, most common first, counting each playlist once', () => { + assert.deepEqual(popularTags(records), [{ key: 'rock', label: 'rock', count: 2 }]); + assert.equal(popularTags(records, { min: 1 }).length, 3); + assert.deepEqual(popularTags([record('x', { tags: ['Rock', 'rock'] })], { min: 1 }), [{ key: 'rock', label: 'Rock', count: 1 }]); + }); +}); + +describe('sorting', () => { + const records = [ + record('a', { title: 'Night Bloom', createdAt: '2024-03-01T00:00:00Z', updatedAt: '2024-06-01T00:00:00Z' }), + record('b', { title: 'Static Drive', createdAt: '2024-05-01T00:00:00Z', updatedAt: '2024-01-02T00:00:00Z' }), + record('c', { title: 'after Dark', createdAt: '2024-04-01T00:00:00Z', updatedAt: '2024-09-01T00:00:00Z' }), + ]; + const entries = records.map((r) => ({ record: r, text: searchText(r) })); + const ids = (view) => applyView(entries, view).map((r) => r.id); + + it('shows the newest created first by default', () => { + assert.equal(DEFAULT_SORT, 'created'); assert.deepEqual(ids({}), ['b', 'c', 'a']); - assert.deepEqual(ids({ sort: 'updated' }), ['c', 'b', 'a']); - assert.deepEqual(ids({ sort: 'az' }), ['c', 'a', 'b']); + }); + + it('sorts by created, updated or title, each in the order people expect first', () => { + assert.deepEqual(ids({ sort: 'created' }), ['b', 'c', 'a']); + assert.deepEqual(ids({ sort: 'updated' }), ['c', 'a', 'b']); + assert.deepEqual(ids({ sort: 'title' }), ['c', 'a', 'b']); + }); + + it('can reverse every sort', () => { + assert.deepEqual(ids({ sort: 'created', order: 'asc' }), ['a', 'c', 'b']); + assert.deepEqual(ids({ sort: 'updated', order: 'asc' }), ['b', 'a', 'c']); + assert.deepEqual(ids({ sort: 'title', order: 'desc' }), ['b', 'a', 'c']); + assert.deepEqual(ids({ sort: 'created', order: 'desc' }), ids({ sort: 'created' })); + }); + + it('breaks ties by title, whichever way the sort runs', () => { + const tied = [record('x', { title: 'Zebra' }), record('y', { title: 'Apple' })].map((r) => ({ record: r, text: '' })); + assert.deepEqual(applyView(tied, { sort: 'created' }).map((r) => r.id), ['y', 'x']); + assert.deepEqual(applyView(tied, { sort: 'created', order: 'asc' }).map((r) => r.id), ['y', 'x']); + }); + + it('keeps playlists without a date at the end, either way round', () => { + const undated = [...entries, { record: record('u', { title: 'Undated', createdAt: null }), text: '' }]; + assert.equal(applyView(undated, { sort: 'created' }).at(-1).id, 'u'); + assert.equal(applyView(undated, { sort: 'created', order: 'asc' }).at(-1).id, 'u'); + }); + + it('falls back to the defaults for anything unknown', () => { assert.deepEqual(ids({ sort: 'nonsense' }), ['b', 'c', 'a']); + assert.deepEqual(ids({ sort: 'title', order: 'sideways' }), ['c', 'a', 'b']); + assert.equal(parseSort('constructor'), 'created'); + assert.equal(parseOrder('sideways', 'title'), 'asc'); + assert.equal(parseOrder(undefined, 'updated'), 'desc'); }); - it('lists tags shared by several playlists, most common first', () => { - assert.deepEqual(popularTags(records), [{ key: 'rock', label: 'rock', count: 2 }]); - assert.equal(popularTags(records, { min: 1 }).length, 2); + it('still understands the names used by links shared before directions existed', () => { + assert.equal(parseSort('newest'), 'created'); + assert.equal(parseSort('az'), 'title'); + assert.deepEqual(ids({ sort: 'az' }), ids({ sort: 'title' })); + assert.deepEqual(ids({ sort: 'newest' }), ids({ sort: 'created' })); }); }); diff --git a/test/http.test.js b/test/http.test.js index 7a7bbc9..f0c42e1 100644 --- a/test/http.test.js +++ b/test/http.test.js @@ -11,8 +11,8 @@ import { fakeReporter } from './helpers.js'; const silentLogger = createLogger({ level: 'silent' }); const records = [ - { id: 'aaaa-1', rev: 'r1', title: 'One', tag: 'rock', art: { color: '#112233', sources: [['https://resources.tidal.com/images/1/320x320.jpg', 320]] } }, - { id: 'bbbb-2', rev: 'r2', title: 'Two', tag: null, art: null }, + { id: 'aaaa-1', rev: 'r1', title: 'One', tags: ['rock'], art: { color: '#112233', sources: [['https://resources.tidal.com/images/1/320x320.jpg', 320]] } }, + { id: 'bbbb-2', rev: 'r2', title: 'Two', tags: [], art: null }, ]; const snapshot = { records, diff --git a/test/normalise.test.js b/test/normalise.test.js index 9fa72c4..c4737a1 100644 --- a/test/normalise.test.js +++ b/test/normalise.test.js @@ -5,19 +5,24 @@ import { artworkResource, playlistResource } from './helpers.js'; describe('parseTitle', () => { const cases = [ - ['the name of the playlist (rock)', 'the name of the playlist', 'rock'], - ['Deep cuts (Talking Heads)', 'Deep cuts', 'Talking Heads'], - ['Songs (for) rainy days (jazz)', 'Songs (for) rainy days', 'jazz'], - ['Spaced out ( ambient )', 'Spaced out', 'ambient'], - [' Extra spaces (soul) ', 'Extra spaces', 'soul'], - ['Thunderstruck (AC/DC)', 'Thunderstruck', 'AC/DC'], - ['No tag here', 'No tag here', null], - ['Empty tag ()', 'Empty tag ()', null], - ['(only a tag)', '(only a tag)', null], - ['', '', null], + ['the name of the playlist (rock)', 'the name of the playlist', ['rock']], + ['Deep cuts (Talking Heads)', 'Deep cuts', ['Talking Heads']], + ['Songs (for) rainy days (jazz)', 'Songs (for) rainy days', ['jazz']], + ['Spaced out ( ambient )', 'Spaced out', ['ambient']], + [' Extra spaces (soul) ', 'Extra spaces', ['soul']], + ['Thunderstruck (AC/DC)', 'Thunderstruck', ['AC/DC']], + ['Two tags (rock) (jazz)', 'Two tags', ['rock', 'jazz']], + ['Touching tags (rock)(jazz)', 'Touching tags', ['rock', 'jazz']], + ['Three (a) (b) (c)', 'Three', ['a', 'b', 'c']], + ['Brackets (mid) title (rock) (jazz)', 'Brackets (mid) title', ['rock', 'jazz']], + ['Stops at an empty pair (rock) ()', 'Stops at an empty pair (rock) ()', []], + ['No tag here', 'No tag here', []], + ['Empty tag ()', 'Empty tag ()', []], + ['(only a tag)', '(only a tag)', []], + ['', '', []], ]; - for (const [name, title, tag] of cases) { - it(`"${name}"`, () => assert.deepEqual(parseTitle(name), { title, tag })); + for (const [name, title, tags] of cases) { + it(`"${name}"`, () => assert.deepEqual(parseTitle(name), { title, tags })); } }); @@ -71,7 +76,7 @@ describe('normalisePlaylist', () => { it('builds a compact record', () => { const record = normalisePlaylist(playlistResource('1'), artworks); assert.equal(record.title, 'Playlist 1'); - assert.equal(record.tag, 'rock'); + assert.deepEqual(record.tags, ['rock']); assert.equal(record.tracks, 10); assert.equal(record.duration, 3723); assert.equal(record.followers, 3); diff --git a/test/playlists.test.js b/test/playlists.test.js index 7eb9ffe..a72090d 100644 --- a/test/playlists.test.js +++ b/test/playlists.test.js @@ -89,7 +89,8 @@ describe('fetchPublicPlaylists', () => { const client = createTidalClient({ baseUrl: 'https://openapi.tidal.com/v2', tokens, fetch, logger: silentLogger }); const records = await fetchPublicPlaylists({ client, ...options }); assert.equal(records.length, 29); // One of the 30 mock playlists is private. - assert.ok(records.some((r) => r.tag === 'Björk')); - assert.ok(records.some((r) => r.tag === null)); + assert.ok(records.some((r) => r.tags.includes('Björk'))); + assert.ok(records.some((r) => r.tags.length === 0)); + assert.ok(records.some((r) => r.tags.length === 2)); }); }); diff --git a/views/index.ejs b/views/index.ejs index 00e46b4..3b9c9ed 100644 --- a/views/index.ejs +++ b/views/index.ejs @@ -67,14 +67,27 @@ <%- icon('search') %> - +
+ + + +
@@ -123,8 +136,8 @@

-

-

+
+

@@ -132,24 +145,26 @@
-
- -
-

-

-

-
+
+
-

+
+

+

+

+
-
-
- - Open in TIDAL (opens in a new tab)<%- icon('external-link', { size: 18 }) %> - - +
+
+ + Open in TIDAL (opens in a new tab)<%- icon('external-link', { size: 18 }) %> + + +
+

-

+ +