v4: playlists sort by their last dump, their creation or their size, and /playlists is a grid of covers — every list of playlists came newest first, so one fed every week sank under those made since and left empty. GET /api/playlists and /api/users/:key/playlists take ?sort=updated|new|dumps (PLAYLIST_SORTS, shared/playlist.ts), updated being the default: the last to take a dump first, or its creation while it holds none; a new title, cover or description doesn't bring it back up. A playlist carries that date as lastDumpAt, read with its dumpCount by isMemberVisibleTo's rule (VISIBLE_DUMP_FIGURES, the viewer's id as ?1), so the owner's private dumps date and count their playlists for them alone, in the lists and over the socket: playlist_created, playlist_updated and playlist_dumps_updated carry each socket's own. The /playlists page and a profile's playlists tab show the orders as tabs beside the category menu and keep the one picked in ?sort=, the default being the bare path; a tab takes the current history entry's place, and picking a category keeps the order. Live, usePlaylistListSync takes the list's order: a new playlist goes where it puts it, one that rises moves up to its place, as in the updated order when it takes a dump, and one that falls stays until the list is fetched again, its place being perhaps on a page not loaded. The lists in an order of their own, the followed playlists and the search's, pass none, and take no new playlist as before (noNewEntries goes). comparePlaylists is the order on the client, which a test holds to the API's.
/playlists lays its cards out as tiles, the cover across the top, four to a row and two on a phone, on the wide column: the same PlaylistCard, laid out by its list's class (.playlist-grid), so each theme's card skin carries over. It drops the "public" badge there, every playlist listed being public. On every card, a playlist without a cover shows a tile of its own colour with its initial (ThumbnailPlaceholder) in place of the 📋, and the date is "updated …" of its last dump, or "created …". A middle, ctrl, cmd or shift click anywhere on a playlist card opens it in a new tab — only its title was a link, the rest navigating by a click handler. useCardLink (hooks/shared) is useDumpCardLink's handlers for any card, which the dump cards now get through it. A profile tab's query stays with the tab — going from the playlists to the dumps kept the whole query, so a playlist category, and now ?sort=, landed on the dumps' URL. Only the dump lists pass their category to each other; any other change of tab drops the query. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
99
src/App.css
99
src/App.css
@@ -2289,6 +2289,14 @@ body.has-player .chat-fab {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* A list's order tabs, as the playlists', take a line of their own under the
|
||||
title where the row has no room for both, rather than scroll beside it. */
|
||||
.profile-section-header:has(.playlist-sort-tabs) {
|
||||
flex-wrap: wrap;
|
||||
row-gap: 0.25rem;
|
||||
}
|
||||
|
||||
/* ── Profile (own) page ── */
|
||||
@@ -2761,11 +2769,9 @@ body.has-player .chat-fab {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
/* A list of dump or playlist cards in a group, or right under a page's header
|
||||
as on /playlists, fills the column, its edges in line with the label's rule
|
||||
or the header. */
|
||||
.page-group .dump-feed,
|
||||
.page-content--narrow > .dump-feed {
|
||||
/* A list of dump or playlist cards in a group fills the column, its edges in
|
||||
line with the label's rule. */
|
||||
.page-group .dump-feed {
|
||||
padding: 0;
|
||||
max-width: none;
|
||||
}
|
||||
@@ -4064,9 +4070,8 @@ body.has-player .chat-fab {
|
||||
0.25);
|
||||
}
|
||||
|
||||
/* ── Shared card preview icon ── */
|
||||
.dump-card-preview-icon,
|
||||
.playlist-card-icon {
|
||||
/* ── Dump card preview icon ── */
|
||||
.dump-card-preview-icon {
|
||||
font-size: var(--text-3xl);
|
||||
opacity: 0.7;
|
||||
line-height: 1;
|
||||
@@ -4355,6 +4360,82 @@ body.has-player .chat-fab {
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Playlist grid ──
|
||||
The playlists page shows its cards as tiles, the cover across the tile's
|
||||
top and the text under it: the same card as in a .dump-feed, laid out by
|
||||
the list it is in, so every theme's card skin carries over. */
|
||||
.playlist-grid {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(11.5rem, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.playlist-grid > li {
|
||||
animation: card-enter 0.2s ease both;
|
||||
}
|
||||
|
||||
/* The tiles of a row are as tall as the tallest, each one's text starting at
|
||||
the same height under covers of one size. */
|
||||
.playlist-grid .playlist-card {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.playlist-grid .playlist-card-inner {
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 0.65rem;
|
||||
padding: 0.6rem 0.6rem 0.8rem;
|
||||
}
|
||||
|
||||
.playlist-grid .playlist-card-preview {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
aspect-ratio: 1;
|
||||
}
|
||||
|
||||
/* A cover this size fills the tile: grown as a thumb is, it would spill over
|
||||
the card's edge. */
|
||||
.playlist-grid .playlist-card-inner:hover .playlist-card-preview {
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.playlist-grid .playlist-card-preview .thumb-placeholder-initials {
|
||||
font-size: var(--text-display);
|
||||
}
|
||||
|
||||
.playlist-grid .playlist-card-body {
|
||||
margin-left: 0;
|
||||
padding-inline: 0.15rem;
|
||||
}
|
||||
|
||||
.playlist-grid .playlist-card-title,
|
||||
.playlist-grid .playlist-card-description {
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 2;
|
||||
line-clamp: 2;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Owner, count and date wrap whole rather than run past a narrow tile. */
|
||||
.playlist-grid .playlist-card-meta {
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
gap: 0.1rem 0.6rem;
|
||||
}
|
||||
|
||||
@media (max-width: 512px) {
|
||||
.playlist-grid {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 0.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
.dump-card-vote {
|
||||
flex-shrink: 0;
|
||||
align-self: center;
|
||||
@@ -5723,7 +5804,7 @@ body.has-player .chat-fab {
|
||||
align-self: center;
|
||||
}
|
||||
|
||||
.collections-section .playlist-card-icon {
|
||||
.collections-section .playlist-card-preview .thumb-placeholder-initials {
|
||||
font-size: var(--text-lg);
|
||||
}
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
* - `/community` and `/community/monthly`, the site's week and month
|
||||
* (`Community`), signed in only.
|
||||
* - `/playlists` is every public playlist, and `/playlists/:categorySlug` a
|
||||
* playlist category's (`Playlists`).
|
||||
* playlist category's, in the order `?sort=` names (`Playlists`).
|
||||
* - `/@:username/*` is a user's (`UserRoutes`): their profile and its tabs,
|
||||
* their dumps at `dumps/:slug` (`Dump`) and `dumps/:slug/edit` (`DumpEdit`,
|
||||
* signed in only), and their playlists at `playlists/:slug`
|
||||
|
||||
@@ -17,14 +17,15 @@ export interface PageHeaderProps {
|
||||
title: ReactNode;
|
||||
/**
|
||||
* It goes at the end of the row, such as the notifications' unread count or
|
||||
* the playlists' category menu.
|
||||
* the playlists' category menu and order tabs.
|
||||
*/
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the page's h1 with its icon, then `children`, as the first block of
|
||||
* a narrow `PageShell`; `PageGroup`s follow it.
|
||||
* a `PageShell`: a narrow one's `PageGroup`s follow it, or the playlists
|
||||
* page's grid.
|
||||
*/
|
||||
export function PageHeader(
|
||||
{ icon, title, children }: PageHeaderProps,
|
||||
|
||||
@@ -5,18 +5,20 @@
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { Link, useNavigate } from "react-router";
|
||||
import { Link } from "react-router";
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { Plural, Trans } from "@lingui/react/macro";
|
||||
import type { Playlist } from "../../../shared/playlist.ts";
|
||||
import { type Playlist, playlistActivity } from "../../../shared/playlist.ts";
|
||||
import { relativeTime } from "../../utils/shared/relativeTime.ts";
|
||||
import { playlistImageUrl, playlistUrl } from "../../utils/shared/urls.ts";
|
||||
import { useAuth } from "../../hooks/auth/useAuth.ts";
|
||||
import { useCardLink } from "../../hooks/shared/useCardLink.ts";
|
||||
import {
|
||||
isPlaylistVisited,
|
||||
isRecent,
|
||||
markPlaylistVisited,
|
||||
} from "../../utils/shared/visited.ts";
|
||||
import { ThumbnailPlaceholder } from "../shared/ThumbnailPlaceholder.tsx";
|
||||
import { Tooltip } from "../shared/Tooltip.tsx";
|
||||
import { CategoryChips } from "../category/CategoryChips.tsx";
|
||||
import { userPath } from "../../../shared/paths.ts";
|
||||
@@ -41,16 +43,21 @@ export interface PlaylistCardProps {
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a playlist as a card that opens the playlist when clicked, with the
|
||||
* playlist categories it is filed under. Another user's recent playlist shows
|
||||
* an unread dot until it is opened on this device. The card is an `<li>`, for
|
||||
* a `<ul>`.
|
||||
* Renders a playlist as a card that opens the playlist when clicked, in a new
|
||||
* tab on a middle click (`useCardLink`), with its cover, or a tile of its own
|
||||
* colour without one, the playlist categories it is filed under and when it
|
||||
* last took a dump. Another user's recent playlist shows an unread dot until
|
||||
* it is opened on this device. The card is an `<li>`, for a `<ul>`, whose
|
||||
* class lays it out: a row in a `.dump-feed`, a tile in a `.playlist-grid`.
|
||||
*/
|
||||
export function PlaylistCard(
|
||||
{ playlist, onDelete, isOwner, privateBadgeOnly }: PlaylistCardProps,
|
||||
): React.JSX.Element {
|
||||
const navigate = useNavigate();
|
||||
const { mediaToken } = useAuth();
|
||||
const { cardProps } = useCardLink(
|
||||
playlistUrl(playlist),
|
||||
() => markPlaylistVisited(playlist.id),
|
||||
);
|
||||
const unread = !isOwner && isRecent(playlist.createdAt) &&
|
||||
!isPlaylistVisited(playlist.id);
|
||||
const showBadge = !privateBadgeOnly || (!!isOwner && !playlist.isPublic);
|
||||
@@ -58,18 +65,12 @@ export function PlaylistCard(
|
||||
// room for its text only, and none at all when it is a lone image.
|
||||
const description = playlist.description &&
|
||||
markdownToPlainText(playlist.description, "");
|
||||
|
||||
function handleNavigate() {
|
||||
markPlaylistVisited(playlist.id);
|
||||
navigate(playlistUrl(playlist));
|
||||
}
|
||||
const activity = playlistActivity(playlist);
|
||||
const ago = relativeTime(activity);
|
||||
|
||||
return (
|
||||
<li className="playlist-card">
|
||||
<div
|
||||
className="playlist-card-inner"
|
||||
onClick={handleNavigate}
|
||||
>
|
||||
<div className="playlist-card-inner" {...cardProps}>
|
||||
<div className="playlist-card-preview">
|
||||
{playlist.imageMime
|
||||
? (
|
||||
@@ -81,7 +82,12 @@ export function PlaylistCard(
|
||||
decoding="async"
|
||||
/>
|
||||
)
|
||||
: <span className="playlist-card-icon">📋</span>}
|
||||
: (
|
||||
<ThumbnailPlaceholder
|
||||
seed={playlist.id}
|
||||
siteName={playlist.title}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="playlist-card-body">
|
||||
<Link
|
||||
@@ -129,9 +135,11 @@ export function PlaylistCard(
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
<Tooltip text={playlist.createdAt.toLocaleString()}>
|
||||
<time dateTime={playlist.createdAt.toISOString()}>
|
||||
{relativeTime(playlist.createdAt)}
|
||||
<Tooltip text={activity.toLocaleString()}>
|
||||
<time dateTime={activity.toISOString()}>
|
||||
{playlist.lastDumpAt
|
||||
? <Trans>updated {ago}</Trans>
|
||||
: <Trans>created {ago}</Trans>}
|
||||
</time>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
@@ -15,18 +15,24 @@ export interface PlaylistCardListProps {
|
||||
onDelete?: (playlist: Playlist) => void;
|
||||
/** Passed to each {@link PlaylistCard}. */
|
||||
privateBadgeOnly?: boolean;
|
||||
/**
|
||||
* Lays the cards out as tiles, cover first, several to a row, for a page
|
||||
* that is a list of playlists and nothing else: the playlists page.
|
||||
*/
|
||||
grid?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders `playlists` as a `.dump-feed` of {@link PlaylistCard}, a card being
|
||||
* its owner's when the playlist is the signed-in user's.
|
||||
* Renders `playlists` as a `.dump-feed` of {@link PlaylistCard}, one to a
|
||||
* row, or as a `.playlist-grid` of them, a card being its owner's when the
|
||||
* playlist is the signed-in user's.
|
||||
*/
|
||||
export function PlaylistCardList(
|
||||
{ playlists, onDelete, privateBadgeOnly }: PlaylistCardListProps,
|
||||
{ playlists, onDelete, privateBadgeOnly, grid }: PlaylistCardListProps,
|
||||
): React.JSX.Element {
|
||||
const { user } = useAuth();
|
||||
return (
|
||||
<ul className="dump-feed">
|
||||
<ul className={grid ? "playlist-grid" : "dump-feed"}>
|
||||
{playlists.map((p) => (
|
||||
<PlaylistCard
|
||||
key={p.id}
|
||||
|
||||
43
src/components/playlist/PlaylistSortTabs.tsx
Normal file
43
src/components/playlist/PlaylistSortTabs.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Renders the tabs that put a list of playlists in another order, on the
|
||||
* playlists page and on a profile's playlists tab.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
import { PLAYLIST_SORTS, type PlaylistSort } from "../../../shared/playlist.ts";
|
||||
import { TabBar } from "../shared/TabBar.tsx";
|
||||
|
||||
/**
|
||||
* Passed to {@link PlaylistSortTabs} by `Playlists` and
|
||||
* `ProfilePlaylistsTab`, which keep the order in their URL's `?sort=`.
|
||||
*/
|
||||
export interface PlaylistSortTabsProps {
|
||||
sort: PlaylistSort;
|
||||
onChange: (sort: PlaylistSort) => void;
|
||||
/** Goes before the tabs, as the playlists page's category menu does. */
|
||||
leading?: ReactNode;
|
||||
}
|
||||
|
||||
const LABELS: Record<PlaylistSort, ReactNode> = {
|
||||
updated: <Trans>Updated</Trans>,
|
||||
new: <Trans>New</Trans>,
|
||||
dumps: <Trans>Most dumps</Trans>,
|
||||
};
|
||||
|
||||
/** Renders one tab per order of `PLAYLIST_SORTS`, `sort` being the active one. */
|
||||
export function PlaylistSortTabs(
|
||||
{ sort, onChange, leading }: PlaylistSortTabsProps,
|
||||
): React.JSX.Element {
|
||||
return (
|
||||
<TabBar
|
||||
tabs={PLAYLIST_SORTS.map((key) => ({ key, label: LABELS[key] }))}
|
||||
activeTab={sort}
|
||||
onChange={onChange}
|
||||
leading={leading}
|
||||
className="playlist-sort-tabs"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -106,7 +106,6 @@ function FollowedPlaylists({ userId }: { userId: string }) {
|
||||
usePlaylistListSync(
|
||||
state.status === "loaded" ? state.data.items : [],
|
||||
setItems,
|
||||
{ noNewEntries: true },
|
||||
);
|
||||
return (
|
||||
<ListState
|
||||
|
||||
@@ -11,7 +11,12 @@ import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
import { API_URL } from "../../config/api.ts";
|
||||
import { userApiUrl } from "../../utils/shared/urls.ts";
|
||||
import type { Playlist } from "../../../shared/playlist.ts";
|
||||
import {
|
||||
parsePlaylistSort,
|
||||
type Playlist,
|
||||
type PlaylistSort,
|
||||
} from "../../../shared/playlist.ts";
|
||||
import { playlistSortQuery } from "../../../shared/paths.ts";
|
||||
import type { PublicUser } from "../../../shared/user.ts";
|
||||
import {
|
||||
canLoadMore,
|
||||
@@ -39,6 +44,7 @@ import { useCategoryFilter } from "../../hooks/category/useCategoryFilter.ts";
|
||||
import { CategorySwitcher } from "../category/CategorySwitcher.tsx";
|
||||
import { NewPlaylistButton } from "../playlist/NewPlaylistButton.tsx";
|
||||
import { PlaylistCardList } from "../playlist/PlaylistCardList.tsx";
|
||||
import { PlaylistSortTabs } from "../playlist/PlaylistSortTabs.tsx";
|
||||
import { FeedFooter } from "../feed/FeedFooter.tsx";
|
||||
import { ConfirmModal } from "../shared/ConfirmModal.tsx";
|
||||
import { ErrorCard } from "../shared/ErrorCard.tsx";
|
||||
@@ -53,19 +59,22 @@ export interface ProfilePlaylistsTabProps {
|
||||
|
||||
/**
|
||||
* Renders the tab's list for the playlist category the URL's `?category=`
|
||||
* picks, or every playlist without one. Each category's list is another,
|
||||
* which the tab mounts afresh.
|
||||
* picks, or every playlist without one, in the order its `?sort=` names.
|
||||
* Each category's list in each order is another, which the tab mounts
|
||||
* afresh.
|
||||
*/
|
||||
export function ProfilePlaylistsTab(
|
||||
props: ProfilePlaylistsTabProps,
|
||||
): React.JSX.Element {
|
||||
const [params] = useSearchParams();
|
||||
const categorySlug = params.get("category") || undefined;
|
||||
const sort = parsePlaylistSort(params.get("sort"));
|
||||
return (
|
||||
<PlaylistList
|
||||
key={categorySlug ?? ""}
|
||||
key={`${categorySlug ?? ""}:${sort}`}
|
||||
{...props}
|
||||
categorySlug={categorySlug}
|
||||
sort={sort}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -74,26 +83,28 @@ export function ProfilePlaylistsTab(
|
||||
* Renders the playlists `user` made, from `GET /api/users/:userId/playlists`,
|
||||
* the private ones to their owner only, a page at a time as the list scrolls;
|
||||
* with `categorySlug`, only those in that playlist category, which the menu in
|
||||
* the title row switches. The socket keeps them live, and going back restores
|
||||
* the list and the scroll. The owner can make one, which goes first, and
|
||||
* delete one.
|
||||
* the title row switches, before the tabs that change the order. The socket
|
||||
* keeps them live, and going back restores the list and the scroll. The owner
|
||||
* can make one, which goes first, and delete one.
|
||||
*/
|
||||
function PlaylistList(
|
||||
{ user, isOwnProfile, categorySlug }: ProfilePlaylistsTabProps & {
|
||||
{ user, isOwnProfile, categorySlug, sort }: ProfilePlaylistsTabProps & {
|
||||
categorySlug?: string;
|
||||
sort: PlaylistSort;
|
||||
},
|
||||
): React.JSX.Element {
|
||||
const [, setParams] = useSearchParams();
|
||||
const { user: me, authFetch } = useAuth();
|
||||
const { categories } = useCategories("playlist");
|
||||
const { cached, saveState } = useFeedCache<Playlist>(
|
||||
`feed:profile-playlists:${user.id}${
|
||||
categorySlug ? `:${categorySlug}` : ""
|
||||
}`,
|
||||
`feed:profile-playlists:${user.id}:${categorySlug ?? ""}:${sort}`,
|
||||
hydratePlaylist,
|
||||
);
|
||||
const url = `${userApiUrl(user, "playlists")}${
|
||||
categorySlug ? `?category=${encodeURIComponent(categorySlug)}` : ""
|
||||
playlistSortQuery(
|
||||
sort,
|
||||
new URLSearchParams(categorySlug ? { category: categorySlug } : {}),
|
||||
)
|
||||
}`;
|
||||
const { state, setItems: setAllItems, loadMore, resync } = usePagedList<
|
||||
Playlist
|
||||
@@ -116,6 +127,7 @@ function PlaylistList(
|
||||
usePlaylistListSync(loaded?.items ?? [], setItems, {
|
||||
isOwner: isOwnProfile,
|
||||
ownerId: user.id,
|
||||
sort,
|
||||
});
|
||||
useOnReconnect(resync);
|
||||
|
||||
@@ -149,15 +161,24 @@ function PlaylistList(
|
||||
title={<Trans>Playlists</Trans>}
|
||||
actions={
|
||||
<div className="profile-section-actions">
|
||||
<CategorySwitcher
|
||||
kind="playlist"
|
||||
categorySlug={categorySlug}
|
||||
onSelect={(slug) =>
|
||||
setParams((p) => {
|
||||
if (slug) p.set("category", slug);
|
||||
else p.delete("category");
|
||||
return p;
|
||||
})}
|
||||
<PlaylistSortTabs
|
||||
sort={sort}
|
||||
// Another order of the same list, as a tab is: it takes the
|
||||
// current history entry's place.
|
||||
onChange={(s) =>
|
||||
setParams((p) => playlistSortQuery(s, p), { replace: true })}
|
||||
leading={
|
||||
<CategorySwitcher
|
||||
kind="playlist"
|
||||
categorySlug={categorySlug}
|
||||
onSelect={(slug) =>
|
||||
setParams((p) => {
|
||||
if (slug) p.set("category", slug);
|
||||
else p.delete("category");
|
||||
return p;
|
||||
})}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{isOwnProfile && (
|
||||
<NewPlaylistButton
|
||||
|
||||
@@ -50,6 +50,11 @@ export interface PlaylistEvent {
|
||||
* order.
|
||||
*/
|
||||
dumpIds?: string[];
|
||||
/**
|
||||
* With `dumpIds`, when the latest of them was added; undefined when there
|
||||
* is none.
|
||||
*/
|
||||
lastDumpAt?: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -599,11 +599,12 @@ export function WSProvider({ children }: WSProviderProps): React.JSX.Element {
|
||||
}
|
||||
|
||||
case "playlist_dumps_updated": {
|
||||
const { playlistId, dumpIds } = msg;
|
||||
const { playlistId, dumpIds, lastDumpAt } = msg;
|
||||
events.emit("playlist", {
|
||||
type: "dumps_updated",
|
||||
playlistId,
|
||||
dumpIds,
|
||||
lastDumpAt: lastDumpAt ? new Date(lastDumpAt) : undefined,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1,90 +1,21 @@
|
||||
/**
|
||||
* Gives a dump's card, which is a clickable `<li>` and not a link, a link's
|
||||
* behaviour: a middle or modified click opens the dump in a new tab.
|
||||
* Makes a dump's card open the dump as a link would, and mark it visited.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import type { MouseEvent } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import type { Dump } from "../../../shared/dump.ts";
|
||||
import { dumpUrl } from "../../utils/shared/urls.ts";
|
||||
import { markDumpVisited } from "../../utils/shared/visited.ts";
|
||||
|
||||
/** Checks whether `e` happened over an anchor, which keeps its own target. */
|
||||
function isOverLink(e: MouseEvent) {
|
||||
return (e.target as Element).closest("a") !== null;
|
||||
}
|
||||
|
||||
function wantsNewTab(e: MouseEvent) {
|
||||
return e.ctrlKey || e.metaKey || e.shiftKey;
|
||||
}
|
||||
import { useCardLink, type UseCardLinkResult } from "../shared/useCardLink.ts";
|
||||
|
||||
/**
|
||||
* Returned by {@link useDumpCardLink} to `DumpCard` and `JournalCard`. Every
|
||||
* way it opens the dump marks it visited, which clears its unread dot.
|
||||
*/
|
||||
export interface UseDumpCardLinkResult {
|
||||
/** Opens the dump in this tab, for a handler that would rather not play. */
|
||||
go: () => void;
|
||||
/**
|
||||
* Opens the dump in a new tab and returns true when `e` is a ctrl, cmd or
|
||||
* shift click away from any anchor. A click handler that plays media calls
|
||||
* it first, so that such a click opens the dump instead.
|
||||
*/
|
||||
handledAsNewTab: (e: MouseEvent) => boolean;
|
||||
/** Spread onto the card element. */
|
||||
cardProps: {
|
||||
onClick: (e: MouseEvent) => void;
|
||||
onMouseDown: (e: MouseEvent) => void;
|
||||
onAuxClick: (e: MouseEvent) => void;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the handlers that make the card of `dump` open it: in this tab on a
|
||||
* click, in a new tab on a middle click or a ctrl, cmd or shift click. Anchors
|
||||
* inside the card, such as the title or a category, keep their own target.
|
||||
* Returns `useCardLink`'s handlers for the card of `dump`, for `DumpCard` and
|
||||
* `JournalCard`: every way they open the dump marks it visited, which clears
|
||||
* its unread dot.
|
||||
*/
|
||||
export function useDumpCardLink(
|
||||
dump: Pick<Dump, "id" | "slug" | "ownerUsername">,
|
||||
): UseDumpCardLinkResult {
|
||||
const navigate = useNavigate();
|
||||
|
||||
function openInNewTab() {
|
||||
markDumpVisited(dump.id);
|
||||
globalThis.open(dumpUrl(dump), "_blank", "noopener");
|
||||
}
|
||||
|
||||
function go() {
|
||||
markDumpVisited(dump.id);
|
||||
navigate(dumpUrl(dump));
|
||||
}
|
||||
|
||||
return {
|
||||
go,
|
||||
handledAsNewTab(e: MouseEvent) {
|
||||
if (!wantsNewTab(e) || isOverLink(e)) return false;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
openInNewTab();
|
||||
return true;
|
||||
},
|
||||
cardProps: {
|
||||
onClick(e: MouseEvent) {
|
||||
if (wantsNewTab(e)) openInNewTab();
|
||||
else go();
|
||||
},
|
||||
// Windows and Linux browsers start autoscroll on a middle press, which
|
||||
// eats the auxclick that follows.
|
||||
onMouseDown(e: MouseEvent) {
|
||||
if (e.button === 1 && !isOverLink(e)) e.preventDefault();
|
||||
},
|
||||
onAuxClick(e: MouseEvent) {
|
||||
if (e.button !== 1 || isOverLink(e)) return;
|
||||
e.preventDefault();
|
||||
openInNewTab();
|
||||
},
|
||||
},
|
||||
};
|
||||
): UseCardLinkResult {
|
||||
return useCardLink(dumpUrl(dump), () => markDumpVisited(dump.id));
|
||||
}
|
||||
|
||||
@@ -7,10 +7,14 @@
|
||||
*/
|
||||
|
||||
import { useEffect, useLayoutEffect, useRef } from "react";
|
||||
import type { Playlist } from "../../../shared/playlist.ts";
|
||||
import {
|
||||
comparePlaylists,
|
||||
type Playlist,
|
||||
type PlaylistSort,
|
||||
} from "../../../shared/playlist.ts";
|
||||
import { useWS, useWSEvent } from "../ws/useWS.ts";
|
||||
import { insertAt, usePositionMemory } from "../feed/usePositionMemory.ts";
|
||||
import { withByDate } from "../../utils/feed/pagedList.ts";
|
||||
import { withInOrder } from "../../utils/feed/pagedList.ts";
|
||||
|
||||
/** Passed to {@link usePlaylistListSync} by each page, to fit its list. */
|
||||
export interface PlaylistListSyncOptions {
|
||||
@@ -22,20 +26,27 @@ export interface PlaylistListSyncOptions {
|
||||
*/
|
||||
ownerId?: string;
|
||||
/**
|
||||
* Adds no new playlist, for a list of followed playlists, since the socket
|
||||
* doesn't say what the user follows, or of search results. Playlists
|
||||
* already listed still change, go, and come back where they were.
|
||||
* The order the list is in, for one the API sorts: the playlists page's and
|
||||
* a profile's. A list in an order of its own leaves it out, the followed
|
||||
* playlists being by the date they were followed and a search's results
|
||||
* the search's: it takes no new playlist, since the socket says neither
|
||||
* what the user follows nor what a search matches, and moves none.
|
||||
* Playlists already listed still change, go, and come back where they
|
||||
* were.
|
||||
*/
|
||||
noNewEntries?: boolean;
|
||||
sort?: PlaylistSort;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the socket's playlist events to `items`, the loaded list, newest
|
||||
* first, which `setPlaylists` updates. A created playlist goes where its date
|
||||
* puts it, first when new, an updated one changes in place or leaves when it
|
||||
* turns private (unless `isOwner`), one that left comes back where it was
|
||||
* when it returns, a deleted one leaves, and a playlist's `dumpCount` follows
|
||||
* its dumps. A renamed user's playlists take their new name.
|
||||
* Applies the socket's playlist events to `items`, the loaded list, which
|
||||
* `setPlaylists` updates. A created playlist goes where the list's order puts
|
||||
* it, an updated one changes in place or leaves when it turns private (unless
|
||||
* `isOwner`), one that left comes back where it was when it returns, a
|
||||
* deleted one leaves, and a playlist's `dumpCount` and `lastDumpAt` follow
|
||||
* its dumps. One that a change brings up the order moves up to its place, as
|
||||
* a playlist does in the `updated` order when it takes a dump; one that falls
|
||||
* stays where it is, its place being perhaps on a page not loaded. A renamed
|
||||
* user's playlists take their new name.
|
||||
*/
|
||||
export function usePlaylistListSync(
|
||||
items: Playlist[],
|
||||
@@ -53,7 +64,14 @@ export function usePlaylistListSync(
|
||||
});
|
||||
|
||||
useWSEvent("playlist", (ev) => {
|
||||
const { isOwner, ownerId, noNewEntries } = options ?? {};
|
||||
const { isOwner, ownerId, sort } = options ?? {};
|
||||
const compare = sort && comparePlaylists(sort);
|
||||
// Returns `list` with the playlist at `idx` before the ones it now comes
|
||||
// before, if it rose.
|
||||
const risen = (list: Playlist[], idx: number) =>
|
||||
compare && idx > 0 && compare(list[idx], list[idx - 1]) < 0
|
||||
? withInOrder(list.toSpliced(idx, 1), list[idx], compare)
|
||||
: list;
|
||||
const shown = ev.playlist &&
|
||||
(ev.playlist.isPublic || isOwner) &&
|
||||
(!ownerId || ev.playlist.userId === ownerId);
|
||||
@@ -66,15 +84,13 @@ export function usePlaylistListSync(
|
||||
const idx = prev.findIndex((p) => p.id === playlist.id);
|
||||
if (idx !== -1) {
|
||||
if (!shown) return prev.filter((p) => p.id !== playlist.id);
|
||||
const next = [...prev];
|
||||
next[idx] = playlist;
|
||||
return next;
|
||||
return risen(prev.with(idx, playlist), idx);
|
||||
}
|
||||
if (!shown) return prev;
|
||||
if (oldIdx !== undefined) return insertAt(prev, playlist, oldIdx);
|
||||
// An update never adds a playlist the list doesn't hold.
|
||||
if (ev.type === "updated" || noNewEntries) return prev;
|
||||
return withByDate(prev, playlist);
|
||||
if (ev.type === "updated" || !compare) return prev;
|
||||
return withInOrder(prev, playlist, compare);
|
||||
}
|
||||
|
||||
if (ev.type === "deleted") {
|
||||
@@ -84,10 +100,13 @@ export function usePlaylistListSync(
|
||||
if (ev.type === "dumps_updated" && ev.dumpIds) {
|
||||
const idx = prev.findIndex((p) => p.id === ev.playlistId);
|
||||
if (idx === -1) return prev;
|
||||
const next = [...prev];
|
||||
// The dumps this user may see, which are those the playlist counts.
|
||||
next[idx] = { ...next[idx], dumpCount: ev.dumpIds.length };
|
||||
return next;
|
||||
const playlist = {
|
||||
...prev[idx],
|
||||
dumpCount: ev.dumpIds.length,
|
||||
lastDumpAt: ev.lastDumpAt,
|
||||
};
|
||||
return risen(prev.with(idx, playlist), idx);
|
||||
}
|
||||
|
||||
return prev;
|
||||
|
||||
91
src/hooks/shared/useCardLink.ts
Normal file
91
src/hooks/shared/useCardLink.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* Gives a dump's or a playlist's card, which is a clickable `<li>` and not a
|
||||
* link, a link's behaviour: a middle or modified click opens its page in a
|
||||
* new tab.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import type { MouseEvent } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
|
||||
/** Checks whether `e` happened over an anchor, which keeps its own target. */
|
||||
function isOverLink(e: MouseEvent) {
|
||||
return (e.target as Element).closest("a") !== null;
|
||||
}
|
||||
|
||||
function wantsNewTab(e: MouseEvent) {
|
||||
return e.ctrlKey || e.metaKey || e.shiftKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returned by {@link useCardLink} to `PlaylistCard`, and through
|
||||
* `useDumpCardLink` to `DumpCard` and `JournalCard`.
|
||||
*/
|
||||
export interface UseCardLinkResult {
|
||||
/** Opens the page in this tab, for a handler that would rather not play. */
|
||||
go: () => void;
|
||||
/**
|
||||
* Opens the page in a new tab and returns true when `e` is a ctrl, cmd or
|
||||
* shift click away from any anchor. A click handler that plays media calls
|
||||
* it first, so that such a click opens the page instead.
|
||||
*/
|
||||
handledAsNewTab: (e: MouseEvent) => boolean;
|
||||
/** Spread onto the card element. */
|
||||
cardProps: {
|
||||
onClick: (e: MouseEvent) => void;
|
||||
onMouseDown: (e: MouseEvent) => void;
|
||||
onAuxClick: (e: MouseEvent) => void;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the handlers that make a card open the page at `url`: in this tab
|
||||
* on a click, in a new tab on a middle click or a ctrl, cmd or shift click.
|
||||
* Every way it opens the page calls `onOpen` first, which marks the item
|
||||
* visited. Anchors inside the card, such as the title or a category, keep
|
||||
* their own target.
|
||||
*/
|
||||
export function useCardLink(
|
||||
url: string,
|
||||
onOpen: () => void,
|
||||
): UseCardLinkResult {
|
||||
const navigate = useNavigate();
|
||||
|
||||
function openInNewTab() {
|
||||
onOpen();
|
||||
globalThis.open(url, "_blank", "noopener");
|
||||
}
|
||||
|
||||
function go() {
|
||||
onOpen();
|
||||
navigate(url);
|
||||
}
|
||||
|
||||
return {
|
||||
go,
|
||||
handledAsNewTab(e: MouseEvent) {
|
||||
if (!wantsNewTab(e) || isOverLink(e)) return false;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
openInNewTab();
|
||||
return true;
|
||||
},
|
||||
cardProps: {
|
||||
onClick(e: MouseEvent) {
|
||||
if (wantsNewTab(e)) openInNewTab();
|
||||
else go();
|
||||
},
|
||||
// Windows and Linux browsers start autoscroll on a middle press, which
|
||||
// eats the auxclick that follows.
|
||||
onMouseDown(e: MouseEvent) {
|
||||
if (e.button === 1 && !isOverLink(e)) e.preventDefault();
|
||||
},
|
||||
onAuxClick(e: MouseEvent) {
|
||||
if (e.button !== 1 || isOverLink(e)) return;
|
||||
e.preventDefault();
|
||||
openInNewTab();
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,17 +1,21 @@
|
||||
/**
|
||||
* Renders every public playlist, `/playlists`, and those of one playlist
|
||||
* category, `/playlists/:categorySlug`, newest first.
|
||||
* category, `/playlists/:categorySlug`, in the order `?sort=` names.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { useCallback } from "react";
|
||||
import { useNavigate, useParams } from "react-router";
|
||||
import { useNavigate, useParams, useSearchParams } from "react-router";
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
import { API_URL } from "../config/api.ts";
|
||||
import type { Playlist } from "../../shared/playlist.ts";
|
||||
import { playlistsPath } from "../../shared/paths.ts";
|
||||
import {
|
||||
parsePlaylistSort,
|
||||
type Playlist,
|
||||
type PlaylistSort,
|
||||
} from "../../shared/playlist.ts";
|
||||
import { playlistSortQuery, playlistsPath } from "../../shared/paths.ts";
|
||||
import { canLoadMore, pageUrl, readPage } from "../utils/feed/pagedList.ts";
|
||||
import {
|
||||
deserializePlaylist,
|
||||
@@ -34,18 +38,21 @@ import { PageShell } from "../components/layout/PageShell.tsx";
|
||||
import { PageHeader } from "../components/layout/PageHeader.tsx";
|
||||
import { CategorySwitcher } from "../components/category/CategorySwitcher.tsx";
|
||||
import { PlaylistCardList } from "../components/playlist/PlaylistCardList.tsx";
|
||||
import { PlaylistSortTabs } from "../components/playlist/PlaylistSortTabs.tsx";
|
||||
import { FeedFooter } from "../components/feed/FeedFooter.tsx";
|
||||
import { ListState } from "../components/shared/ListState.tsx";
|
||||
import { NotFound } from "./NotFound.tsx";
|
||||
|
||||
/**
|
||||
* Renders the list for the route's category, or every public playlist
|
||||
* without one. Each category's list is another, which the page mounts
|
||||
* afresh. A slug that names no playlist category, once the categories have
|
||||
* loaded, is a page not found.
|
||||
* without one, in the order of the URL's `?sort=`. Each category's list in
|
||||
* each order is another, which the page mounts afresh. A slug that names no
|
||||
* playlist category, once the categories have loaded, is a page not found.
|
||||
*/
|
||||
export function Playlists(): React.JSX.Element {
|
||||
const { categorySlug } = useParams();
|
||||
const [params] = useSearchParams();
|
||||
const sort = parsePlaylistSort(params.get("sort"));
|
||||
const { categories, isLoaded } = useCategories("playlist");
|
||||
const category = categorySlug
|
||||
? categories.find((c) => c.slug === categorySlug)
|
||||
@@ -55,31 +62,41 @@ export function Playlists(): React.JSX.Element {
|
||||
if (categorySlug && isLoaded && !category) return <NotFound />;
|
||||
return (
|
||||
<PlaylistsList
|
||||
key={categorySlug ?? ""}
|
||||
key={`${categorySlug ?? ""}:${sort}`}
|
||||
categorySlug={categorySlug}
|
||||
categoryId={category?.id}
|
||||
sort={sort}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the public playlists, from `GET /api/playlists`, a page at a time
|
||||
* as the list scrolls; with `categorySlug`, only those in that playlist
|
||||
* category, which the menu in the title row switches. The socket keeps them
|
||||
* live, a reconnection fetches the pages loaded again, and going back
|
||||
* restores the list and the scroll.
|
||||
* Renders the public playlists, from `GET /api/playlists`, as a grid of
|
||||
* covers, a page at a time as the list scrolls; with `categorySlug`, only
|
||||
* those in that playlist category, which the menu before the tabs switches,
|
||||
* keeping the order, while a tab changes the order in place of the current
|
||||
* history entry, as a feed's tabs do. The socket keeps them live, a
|
||||
* reconnection fetches the pages loaded again, and going back restores the
|
||||
* list and the scroll.
|
||||
*/
|
||||
function PlaylistsList(
|
||||
{ categorySlug, categoryId }: { categorySlug?: string; categoryId?: string },
|
||||
{ categorySlug, categoryId, sort }: {
|
||||
categorySlug?: string;
|
||||
categoryId?: string;
|
||||
sort: PlaylistSort;
|
||||
},
|
||||
) {
|
||||
const navigate = useNavigate();
|
||||
const { user, authFetch } = useAuth();
|
||||
const { cached, saveState } = useFeedCache<Playlist>(
|
||||
`feed:playlists:${categorySlug ?? "all"}`,
|
||||
`feed:playlists:${categorySlug ?? "all"}:${sort}`,
|
||||
hydratePlaylist,
|
||||
);
|
||||
const url = `${API_URL}/api/playlists${
|
||||
categorySlug ? `?category=${encodeURIComponent(categorySlug)}` : ""
|
||||
playlistSortQuery(
|
||||
sort,
|
||||
new URLSearchParams(categorySlug ? { category: categorySlug } : {}),
|
||||
)
|
||||
}`;
|
||||
const { state, setItems: setAllItems, loadMore, resync } = usePagedList<
|
||||
Playlist
|
||||
@@ -97,6 +114,7 @@ function PlaylistsList(
|
||||
usePlaylistListSync(
|
||||
loaded?.items ?? [],
|
||||
useCategoryFilter(setAllItems, categoryId),
|
||||
{ sort },
|
||||
);
|
||||
useOnReconnect(resync);
|
||||
|
||||
@@ -110,12 +128,19 @@ function PlaylistsList(
|
||||
useScrollRestore(cached?.scrollY, !!loaded);
|
||||
|
||||
return (
|
||||
<PageShell narrow>
|
||||
<PageShell>
|
||||
<PageHeader icon="📋" title={<Trans>Playlists</Trans>}>
|
||||
<CategorySwitcher
|
||||
kind="playlist"
|
||||
categorySlug={categorySlug}
|
||||
onSelect={(slug) => navigate(playlistsPath(slug))}
|
||||
<PlaylistSortTabs
|
||||
sort={sort}
|
||||
onChange={(s) =>
|
||||
navigate(playlistsPath(categorySlug, s), { replace: true })}
|
||||
leading={
|
||||
<CategorySwitcher
|
||||
kind="playlist"
|
||||
categorySlug={categorySlug}
|
||||
onSelect={(slug) => navigate(playlistsPath(slug, sort))}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</PageHeader>
|
||||
<ListState
|
||||
@@ -129,7 +154,7 @@ function PlaylistsList(
|
||||
>
|
||||
{({ data }) => (
|
||||
<>
|
||||
<PlaylistCardList playlists={data.items} />
|
||||
<PlaylistCardList playlists={data.items} grid privateBadgeOnly />
|
||||
<FeedFooter
|
||||
hasMore={data.hasMore}
|
||||
loadingMore={data.loadingMore}
|
||||
|
||||
@@ -166,7 +166,7 @@ export function Search(): React.JSX.Element {
|
||||
setData((d) => ({ ...d, playlists: fn(d.playlists) })),
|
||||
[setData],
|
||||
),
|
||||
{ isOwner: true, noNewEntries: true },
|
||||
{ isOwner: true },
|
||||
);
|
||||
|
||||
// What changed while the socket was down: every page of dumps loaded is
|
||||
|
||||
@@ -44,8 +44,12 @@ import { NotFound } from "./NotFound.tsx";
|
||||
const OVERVIEW = "overview";
|
||||
type Tab = ProfileTab | typeof OVERVIEW;
|
||||
const TABS: readonly Tab[] = [OVERVIEW, ...PROFILE_TABS];
|
||||
/** The lists of dumps, which `?category=` narrows; the other tabs drop it. */
|
||||
const DUMP_LISTS: readonly Tab[] = ["dumps", "upvoted"];
|
||||
/**
|
||||
* The lists of dumps, which one `?category=` narrows, so it passes from one to
|
||||
* the other. Any other change of tab drops the query: a tab's is its own, as
|
||||
* the playlists' category, of another kind, and their `?sort=`.
|
||||
*/
|
||||
const DUMP_LISTS: readonly (Tab | null)[] = ["dumps", "upvoted"];
|
||||
|
||||
/**
|
||||
* Renders `/@:username` and its tabs, `/@:username/:tab`, and the follow
|
||||
@@ -168,7 +172,12 @@ export function UserPublicProfile(): React.JSX.Element {
|
||||
]}
|
||||
activeTab={tab}
|
||||
onChange={(key) =>
|
||||
setTab(key, DUMP_LISTS.includes(key) ? undefined : "")}
|
||||
setTab(
|
||||
key,
|
||||
DUMP_LISTS.includes(key) && DUMP_LISTS.includes(tab)
|
||||
? undefined
|
||||
: "",
|
||||
)}
|
||||
className="profile-tabs-scroller"
|
||||
innerClassName="profile-tabs"
|
||||
/>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
import { screen } from "@testing-library/react";
|
||||
import { fireEvent, screen } from "@testing-library/react";
|
||||
import { userEvent } from "@testing-library/user-event";
|
||||
import { PlaylistCard } from "../../../components/playlist/PlaylistCard.tsx";
|
||||
import { makePlaylist } from "../../fixtures.ts";
|
||||
@@ -38,6 +38,50 @@ describe("PlaylistCard", () => {
|
||||
expect(currentPath()).toBe("/@ann/playlists/mix");
|
||||
});
|
||||
|
||||
test("a middle click anywhere on the card opens it in a new tab", () => {
|
||||
const opened = vi.spyOn(globalThis, "open").mockReturnValue(null);
|
||||
const p = makePlaylist({ slug: "mix", ownerUsername: "ann" });
|
||||
const { container } = renderWithContexts(
|
||||
<ul>
|
||||
<PlaylistCard playlist={p} />
|
||||
</ul>,
|
||||
);
|
||||
fireEvent(
|
||||
container.querySelector(".playlist-card-preview")!,
|
||||
new MouseEvent("auxclick", { bubbles: true, button: 1 }),
|
||||
);
|
||||
expect(opened).toHaveBeenCalledWith(
|
||||
"/@ann/playlists/mix",
|
||||
"_blank",
|
||||
"noopener",
|
||||
);
|
||||
expect(currentPath()).toBe("/");
|
||||
opened.mockRestore();
|
||||
});
|
||||
|
||||
test("it dates its last dump, or its creation while it holds none", () => {
|
||||
const day = 86_400_000;
|
||||
const createdAt = new Date(Date.now() - 40 * day);
|
||||
const filled = renderWithContexts(
|
||||
<ul>
|
||||
<PlaylistCard
|
||||
playlist={makePlaylist({
|
||||
createdAt,
|
||||
lastDumpAt: new Date(Date.now() - 2 * day),
|
||||
})}
|
||||
/>
|
||||
</ul>,
|
||||
);
|
||||
expect(screen.getByText("updated 2 days ago")).toBeInTheDocument();
|
||||
filled.unmount();
|
||||
renderWithContexts(
|
||||
<ul>
|
||||
<PlaylistCard playlist={makePlaylist({ createdAt })} />
|
||||
</ul>,
|
||||
);
|
||||
expect(screen.getByText("created last month")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("the description shows as text, without its Markdown or its images", () => {
|
||||
const withText = renderWithContexts(
|
||||
<ul>
|
||||
|
||||
@@ -26,7 +26,9 @@ describe("usePlaylistListSync", () => {
|
||||
}
|
||||
|
||||
test("prepends a created playlist once", () => {
|
||||
const { send, items } = setup([makePlaylist({ id: "a" })]);
|
||||
const { send, items } = setup([makePlaylist({ id: "a" })], {
|
||||
sort: "new",
|
||||
});
|
||||
const p = makePlaylist({ id: "b" });
|
||||
send("created", p);
|
||||
send("created", { ...p });
|
||||
@@ -36,28 +38,83 @@ describe("usePlaylistListSync", () => {
|
||||
test("a playlist made public goes where its date puts it", () => {
|
||||
const at = (id: string, day: number) =>
|
||||
makePlaylist({ id, createdAt: new Date(Date.UTC(2026, 0, day)) });
|
||||
const { send, items } = setup([at("c", 30), at("a", 10)]);
|
||||
const { send, items } = setup([at("c", 30), at("a", 10)], {
|
||||
sort: "new",
|
||||
});
|
||||
send("created", at("b", 20));
|
||||
// Older than every one loaded: a later page holds it.
|
||||
send("created", at("old", 1));
|
||||
expect(ids(items())).toEqual(["c", "b", "a"]);
|
||||
});
|
||||
|
||||
test("created: filtered by owner, privacy and noNewEntries", () => {
|
||||
test("created: filtered by owner and privacy, and added to a sorted list only", () => {
|
||||
const p = makePlaylist({ id: "p", userId: "them" });
|
||||
const byOwner = setup([], { ownerId: "me" });
|
||||
const byOwner = setup([], { ownerId: "me", sort: "new" });
|
||||
byOwner.send("created", p);
|
||||
expect(byOwner.items()).toEqual([]);
|
||||
|
||||
const priv = setup([]);
|
||||
const priv = setup([], { sort: "new" });
|
||||
priv.send("created", { ...p, isPublic: false });
|
||||
expect(priv.items()).toEqual([]);
|
||||
|
||||
const followed = setup([], { noNewEntries: true });
|
||||
// A list in an order of its own, as the followed playlists'.
|
||||
const followed = setup([]);
|
||||
followed.send("created", p);
|
||||
expect(followed.items()).toEqual([]);
|
||||
});
|
||||
|
||||
test("a created playlist goes where the list's order puts it", () => {
|
||||
const at = (id: string, day: number, dumpCount: number, added?: number) =>
|
||||
makePlaylist({
|
||||
id,
|
||||
dumpCount,
|
||||
createdAt: new Date(Date.UTC(2026, 0, day)),
|
||||
lastDumpAt: added ? new Date(Date.UTC(2026, 1, added)) : undefined,
|
||||
});
|
||||
const loaded = [at("a", 1, 3, 20), at("b", 2, 2, 10), at("c", 3, 0)];
|
||||
// Made between b and c, it took a dump after b did and before a did.
|
||||
const made = at("new", 2.5, 1, 15);
|
||||
|
||||
const updated = setup(loaded, { sort: "updated" });
|
||||
updated.send("created", made);
|
||||
expect(ids(updated.items())).toEqual(["a", "new", "b", "c"]);
|
||||
|
||||
const dumps = setup(loaded, { sort: "dumps" });
|
||||
dumps.send("created", made);
|
||||
expect(ids(dumps.items())).toEqual(["a", "b", "new", "c"]);
|
||||
});
|
||||
|
||||
test("a playlist that rises in the order moves up, one that falls stays", () => {
|
||||
const at = (id: string, day: number) =>
|
||||
makePlaylist({
|
||||
id,
|
||||
dumpCount: 1,
|
||||
lastDumpAt: new Date(Date.UTC(2026, 0, day)),
|
||||
});
|
||||
const loaded = [at("a", 30), at("b", 20), at("c", 10)];
|
||||
const dumped = (playlistId: string, day?: number) => ({
|
||||
type: "dumps_updated" as const,
|
||||
playlistId,
|
||||
dumpIds: day ? ["x", "y"] : [],
|
||||
lastDumpAt: day ? new Date(Date.UTC(2026, 0, day)) : undefined,
|
||||
});
|
||||
|
||||
const sorted = setup(loaded, { sort: "updated" });
|
||||
sorted.emit("playlist", dumped("c", 25));
|
||||
expect(ids(sorted.items())).toEqual(["a", "c", "b"]);
|
||||
expect(sorted.items()[1].dumpCount).toBe(2);
|
||||
sorted.send("updated", { ...at("b", 31), title: "Risen" });
|
||||
expect(ids(sorted.items())).toEqual(["b", "a", "c"]);
|
||||
// Emptied, it comes after every other, perhaps on a page not loaded.
|
||||
sorted.emit("playlist", dumped("b"));
|
||||
expect(ids(sorted.items())).toEqual(["b", "a", "c"]);
|
||||
expect(sorted.items()[0].lastDumpAt).toBeUndefined();
|
||||
|
||||
const unsorted = setup(loaded);
|
||||
unsorted.emit("playlist", dumped("c", 25));
|
||||
expect(ids(unsorted.items())).toEqual(["a", "b", "c"]);
|
||||
});
|
||||
|
||||
test("updated: in place, removed when private, never added by itself", () => {
|
||||
const p = makePlaylist({ id: "p", title: "one" });
|
||||
const other = makePlaylist({ id: "q" });
|
||||
@@ -72,7 +129,7 @@ describe("usePlaylistListSync", () => {
|
||||
|
||||
test("one that left comes back where it was, even to a followed list", () => {
|
||||
const initial = ["a", "b", "c"].map((id) => makePlaylist({ id }));
|
||||
const { set, send, items } = setup(initial, { noNewEntries: true });
|
||||
const { set, send, items } = setup(initial);
|
||||
// Gone private for others, as a deletion.
|
||||
set({ deletedPlaylistIds: new Set(["b"]) });
|
||||
expect(ids(items())).toEqual(["a", "c"]);
|
||||
|
||||
@@ -85,6 +85,61 @@ describe("Playlists", () => {
|
||||
expect(screen.queryByText("Filed")).toBeNull();
|
||||
});
|
||||
|
||||
test("the tabs change the order, in the URL, which picking a category keeps", async () => {
|
||||
route(
|
||||
"GET /api/playlists",
|
||||
(req) =>
|
||||
page([
|
||||
makePlaylist({
|
||||
title: `By ${req.url.searchParams.get("sort") ?? "default"}`,
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const { user } = open("/playlists");
|
||||
expect(await screen.findByText("By default")).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Most dumps" }));
|
||||
expect(currentPath()).toBe("/playlists?sort=dumps");
|
||||
expect(await screen.findByText("By dumps")).toBeInTheDocument();
|
||||
await user.click(screen.getByRole("button", { name: "All" }));
|
||||
await user.click(screen.getByRole("option", { name: "Mixes" }));
|
||||
expect(currentPath()).toBe("/playlists/mixes?sort=dumps");
|
||||
const asked = calls("GET /api/playlists").at(-1)!.url.searchParams;
|
||||
expect([asked.get("category"), asked.get("sort")]).toEqual([
|
||||
"mixes",
|
||||
"dumps",
|
||||
]);
|
||||
// The default order is the bare path, and so is one the URL misnames.
|
||||
await user.click(screen.getByRole("button", { name: "Updated" }));
|
||||
expect(currentPath()).toBe("/playlists/mixes");
|
||||
});
|
||||
|
||||
test("a playlist that takes a dump goes first in the updated order", async () => {
|
||||
const at = (id: string, day: number) =>
|
||||
makePlaylist({
|
||||
id,
|
||||
title: `Playlist ${id}`,
|
||||
dumpCount: 1,
|
||||
lastDumpAt: new Date(Date.UTC(2026, 0, day)),
|
||||
});
|
||||
route("GET /api/playlists", () => page([at("a", 20), at("b", 10)]));
|
||||
const { socket } = open("/playlists");
|
||||
await screen.findByText("Playlist a");
|
||||
socket.welcome();
|
||||
socket.receive({
|
||||
type: "playlist_dumps_updated",
|
||||
playlistId: "b",
|
||||
dumpIds: ["x", "y"],
|
||||
lastDumpAt: "2026-01-25T00:00:00.000Z",
|
||||
});
|
||||
expect(
|
||||
screen.getAllByRole("link", { name: /^Playlist \w$/ }).map((a) =>
|
||||
a.textContent
|
||||
),
|
||||
).toEqual(["Playlist b", "Playlist a"]);
|
||||
expect(screen.getByText("2 dumps")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("a slug that names no playlist category is not found", async () => {
|
||||
route("GET /api/playlists", () => page([]));
|
||||
open("/playlists/music");
|
||||
|
||||
@@ -292,6 +292,42 @@ describe("UserPublicProfile", () => {
|
||||
expect(screen.queryByText("Filed mix")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("the playlists tab's order is in its URL, beside the category, and no other tab's", async () => {
|
||||
const mixes = makeCategory({
|
||||
id: "pc1",
|
||||
kind: "playlist",
|
||||
slug: "mixes",
|
||||
name: "Mixes",
|
||||
});
|
||||
const { user } = open({ url: "/@ann/playlists", categories: [mixes] });
|
||||
route(
|
||||
"GET /api/users/:u/playlists",
|
||||
() => page([makePlaylist({ title: "Mix", userId: "ann" })]),
|
||||
);
|
||||
const asked = () =>
|
||||
calls("GET /api/users/:u/playlists").at(-1)!.url.searchParams;
|
||||
await screen.findByText("Mix");
|
||||
expect(asked().get("sort")).toBeNull();
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "New" }));
|
||||
expect(currentPath()).toBe("/@ann/playlists?sort=new");
|
||||
await waitFor(() => expect(asked().get("sort")).toBe("new"));
|
||||
await user.click(screen.getByRole("button", { name: "All" }));
|
||||
await user.click(screen.getByRole("option", { name: "Mixes" }));
|
||||
expect(currentPath()).toBe("/@ann/playlists?sort=new&category=mixes");
|
||||
await waitFor(() => expect(asked().get("category")).toBe("mixes"));
|
||||
expect(asked().get("sort")).toBe("new");
|
||||
// The default order is the bare tab's.
|
||||
await user.click(screen.getByRole("button", { name: "Updated" }));
|
||||
expect(currentPath()).toBe("/@ann/playlists?category=mixes");
|
||||
|
||||
// Neither the order nor a playlist category means anything to the dumps.
|
||||
await user.click(screen.getByRole("button", { name: "Most dumps" }));
|
||||
expect(currentPath()).toBe("/@ann/playlists?category=mixes&sort=dumps");
|
||||
await user.click(screen.getByRole("button", { name: "Dumps" }));
|
||||
expect(currentPath()).toBe("/@ann/dumps");
|
||||
});
|
||||
|
||||
test("the dumps tab loads more as its end scrolls into view", async () => {
|
||||
open({ url: "/@ann/dumps" });
|
||||
// After open's, so that it wins.
|
||||
|
||||
@@ -478,7 +478,6 @@
|
||||
[data-style="nyt"] .notifications-empty-icon,
|
||||
[data-style="nyt"] .page-title-icon,
|
||||
[data-style="nyt"] .dump-card-preview-icon,
|
||||
[data-style="nyt"] .playlist-card-icon,
|
||||
[data-style="nyt"] .rich-content-compact-icon,
|
||||
[data-style="nyt"] .journal-card-glyph,
|
||||
[data-style="nyt"] .fdz__file-icon,
|
||||
|
||||
@@ -105,22 +105,39 @@ export function withFirst<T extends { id: string }>(items: T[], item: T): T[] {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `items`, newest first as the API pages them, with `item` where its
|
||||
* `createdAt` puts it: before the first item no newer than it. An item older
|
||||
* than every one loaded is left to a later page, and `items` returned as they
|
||||
* are, as they are when `item` is already there. The list sync hooks put a
|
||||
* new or newly visible dump or playlist in a list with it.
|
||||
* Returns `items`, in the order of `compare` as the API pages them, with
|
||||
* `item` where that order puts it: before the first item that doesn't come
|
||||
* before it. An item that comes after every one loaded is left to a later
|
||||
* page, and `items` returned as they are, as they are when `item` is already
|
||||
* there. `usePlaylistListSync` puts a new, newly visible or risen playlist in
|
||||
* a list with it, whatever its order.
|
||||
*/
|
||||
export function withInOrder<T extends { id: string }>(
|
||||
items: T[],
|
||||
item: T,
|
||||
compare: (a: T, b: T) => number,
|
||||
): T[] {
|
||||
if (items.some((i) => i.id === item.id)) return items;
|
||||
if (items.length === 0) return [item];
|
||||
const idx = items.findIndex((i) => compare(i, item) >= 0);
|
||||
if (idx === -1) return items;
|
||||
return [...items.slice(0, idx), item, ...items.slice(idx)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `items`, newest first, with `item` where its `createdAt` puts it,
|
||||
* as {@link withInOrder} does. `useDumpListSync` puts a new or newly visible
|
||||
* dump in a list with it.
|
||||
*/
|
||||
export function withByDate<T extends { id: string; createdAt: Date }>(
|
||||
items: T[],
|
||||
item: T,
|
||||
): T[] {
|
||||
if (items.some((i) => i.id === item.id)) return items;
|
||||
if (items.length === 0) return [item];
|
||||
const time = item.createdAt.getTime();
|
||||
const idx = items.findIndex((i) => i.createdAt.getTime() <= time);
|
||||
if (idx === -1) return items;
|
||||
return [...items.slice(0, idx), item, ...items.slice(idx)];
|
||||
return withInOrder(
|
||||
items,
|
||||
item,
|
||||
(a, b) => b.createdAt.getTime() - a.createdAt.getTime(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -95,7 +95,10 @@ export function deserializeChatMessage(raw: Wire<ChatMessage>): ChatMessage {
|
||||
|
||||
/** Returns `raw` as a {@link Playlist}. */
|
||||
export function deserializePlaylist(raw: Wire<Playlist>): Playlist {
|
||||
return dates(raw);
|
||||
return {
|
||||
...dates(raw),
|
||||
lastDumpAt: raw.lastDumpAt ? new Date(raw.lastDumpAt) : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -110,7 +113,10 @@ export function hydratePlaylist(raw: unknown): Playlist {
|
||||
export function deserializePlaylistWithDumps(
|
||||
raw: Wire<PlaylistWithDumps>,
|
||||
): PlaylistWithDumps {
|
||||
return { ...dates(raw), dumps: raw.dumps.map(deserializeDump) };
|
||||
return {
|
||||
...deserializePlaylist(raw),
|
||||
dumps: raw.dumps.map(deserializeDump),
|
||||
};
|
||||
}
|
||||
|
||||
/** Returns `raw` as a {@link PlaylistMembership}. */
|
||||
|
||||
Reference in New Issue
Block a user