v4: every page and API URL follows one of two rules, written down in API.md — pages are a hierarchy where @name is a user and any other root word a category or an app page, tabs and views are plain segments and a default view is the bare path; API resources are /api/<plural>/<key>, a user's key being an id or @name, the caller's things under /api/me, media a sub-resource, lookups by another key a query filter. ~ is gone: the feed is /, /hot, /new, /journal, /follow and /music/hot, a profile /@bob with its overview and the tabs dumps, upvoted, playlists (her own only), follow (users, and /follow/playlists), invitees and manage (role and name, for user:manage), which replace the separate UserDumps, UserUpvoted and UserPlaylists pages; /settings holds the account (now with the username) and /manage the category manager, both linked from the user menu and one's profile. Dumps and playlists live under their owner, /@bob/dumps/<slug> and /@bob/playlists/<slug>, named by slug alone: migration 0021 re-slugs them to the bare slugify(title), unique per owner and kind (the oldest keeps it, clashes get -2), renames the categories whose slug v4 reserves (hot, follow, settings…), and rewrites this site's v3 links in dump notes, comments, chat, and playlist and profile descriptions. A slug changes only when edited, through the edit forms' new link field, which proposes slugify(title) as the title changes; a username changes from /settings or, for user:manage, from /@name/manage. Every slug or name left behind stays an alias of its item or user for good (dump_slug_aliases, playlist_slug_aliases, user_aliases), so old links redirect without chaining and nobody else can take one; slugs change 3 times a day per item, names once in 30 days, moderators exempt. An alias, or a name in another case, answers the item with its current path: the pages put it in their URL (useCanonicalPath, without fetching again), and the OG middleware answers a 301. shared/paths.ts builds and parses every page path, for the client's links, the emails' (digest-service lost its own builders and its id fallbacks, and links /follow and /settings) and the server's matchers (OG tags, self previews, backlinks, self-url); shared/slug.ts holds slugify and the format categories share. Dumps and playlists carry ownerUsername and a required slug, and notifications join their users' current names and their items' paths each time they are sent or read, so renames reach them and a deleted item's has no link. The API was renamed per the plan's table: POST /api/users and /api/sessions, /api/password-resets, /api/me (with settings, password, avatar, media-token, playlists?contains=, follow, feed?from=, notifications), /api/users/:key/{dumps,upvoted,playlists,follow/users,follow/playlists,invitees,avatar} and by path /api/users/:key/{dumps,playlists}/:slug, /api/dumps?url= and ?category=, /api/dumps/:id/{file,thumbnail,metadata}, /api/playlists/:id/cover, /api/remote/{preview,image,bandcamp,youtube} (one router), and /api/unsubscribe, the v3 POST /api/users/unsubscribe staying for the digests already sent. A stored default feed tab "followed" reads as "follow" once. dumps.slug and playlists.slug stay nullable, since SQLite can't add NOT NULL without rebuilding tables others reference; every writer sets them and unique (user_id, slug) indexes hold them. 254 backend tests (new: migration 0021 on a v3 fixture, slug aliases, swaps and rate limits, username renames, aliases and limits, reads by path and their privacy, the OG 301s, both unsubscribe paths, v4-shaped digest links with no ids, notification joins, shared paths and slugs) and 668 frontend tests (new: the profile's tabs and follow views, Settings, Manage, the link field, canonical URLs on the dump, playlist and profile pages, bare default feed paths) pass, and tsc, eslint, deno check, deno lint, deno fmt and doc:lint are clean; the migration was also run on a copy of the development database.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,11 +5,11 @@
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Link, useLocation, useNavigate, useParams } from "react-router";
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
import { dumpThumbnailUrl, dumpUrl } from "../utils/shared/urls.ts";
|
||||
import { dumpThumbnailUrl, dumpUrl, isAt } from "../utils/shared/urls.ts";
|
||||
import { can } from "../utils/auth/permissions.ts";
|
||||
import { AddToPlaylistModal } from "../components/playlist/AddToPlaylistModal.tsx";
|
||||
|
||||
@@ -46,6 +46,8 @@ import { PageError } from "../components/layout/PageError.tsx";
|
||||
import { Markdown } from "../components/editor/Markdown.tsx";
|
||||
import { CommentThread } from "../components/comment/CommentThread.tsx";
|
||||
import { Tooltip } from "../components/shared/Tooltip.tsx";
|
||||
import { userPath } from "../../shared/paths.ts";
|
||||
import { useCanonicalPath } from "../hooks/shared/useCanonicalPath.ts";
|
||||
|
||||
type DumpState =
|
||||
| { status: "loading" }
|
||||
@@ -53,16 +55,18 @@ type DumpState =
|
||||
| { status: "loaded"; dump: Dump };
|
||||
|
||||
/**
|
||||
* Renders `/dumps/:selectedDump`, for anyone who may see the dump: a private
|
||||
* dump answers 404 to anyone but its poster. The dump comes from
|
||||
* `GET /api/dumps/:dumpId`, or from the navigation's state when `DumpEdit` or
|
||||
* a title edit here just saved it. Its comments, related dumps and playlists
|
||||
* come from their own endpoints, and `WSContext`'s events keep them current.
|
||||
* The poster and moderators can edit the title in place, and get a link to
|
||||
* `DumpEdit`.
|
||||
* Renders `/@:username/dumps/:slug`, for anyone who may see the dump: a
|
||||
* private dump answers 404 to anyone but its poster. The dump comes from
|
||||
* `GET /api/users/@:username/dumps/:slug`, or from the navigation's state when
|
||||
* `DumpEdit` or a title edit here just saved it. Reached by a former name or
|
||||
* slug, the URL takes the current ones. Its comments, related dumps and
|
||||
* playlists come from their own endpoints once it is loaded, and
|
||||
* `WSContext`'s events keep them current. The poster and moderators can edit
|
||||
* the title in place, and get a link to `DumpEdit`.
|
||||
*/
|
||||
export function Dump(): React.JSX.Element {
|
||||
const { selectedDump } = useParams();
|
||||
const { handle, slug } = useParams();
|
||||
const username = handle?.slice(1);
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
// Taken once, since it stays in the history entry, where a reload or Back
|
||||
@@ -70,10 +74,7 @@ export function Dump(): React.JSX.Element {
|
||||
const [handedOver] = useState(
|
||||
() => (location.state as { dump?: Dump } | null)?.dump ?? null,
|
||||
);
|
||||
const preloaded = handedOver &&
|
||||
(handedOver.id === selectedDump || handedOver.slug === selectedDump)
|
||||
? handedOver
|
||||
: null;
|
||||
const preloaded = isAt(handedOver, username, slug) ? handedOver : null;
|
||||
useEffect(() => {
|
||||
if (!(location.state as { dump?: Dump } | null)?.dump) return;
|
||||
navigate(`${location.pathname}${location.search}${location.hash}`, {
|
||||
@@ -85,6 +86,14 @@ export function Dump(): React.JSX.Element {
|
||||
const [dumpState, setDumpState] = useState<DumpState>(
|
||||
preloaded ? { status: "loaded", dump: preloaded } : { status: "loading" },
|
||||
);
|
||||
const loadedDump = dumpState.status === "loaded" ? dumpState.dump : null;
|
||||
useCanonicalPath(loadedDump && dumpUrl(loadedDump));
|
||||
// The dump on screen, which a path it was just given, by useCanonicalPath or
|
||||
// a slug edited elsewhere, needn't fetch again.
|
||||
const shownRef = useRef<Dump | null>(loadedDump);
|
||||
useEffect(() => {
|
||||
shownRef.current = loadedDump;
|
||||
}, [loadedDump]);
|
||||
const [op, setOp] = useState<PublicUser | null>(null);
|
||||
const [playlistModalOpen, setPlaylistModalOpen] = useState(false);
|
||||
|
||||
@@ -120,11 +129,11 @@ export function Dump(): React.JSX.Element {
|
||||
} = useWS();
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedDump) return;
|
||||
if (!username || !slug) return;
|
||||
const controller = new AbortController();
|
||||
|
||||
if (preloaded) {
|
||||
fetch(`${API_URL}/api/users/by-id/${preloaded.userId}`, {
|
||||
fetch(`${API_URL}/api/users/${preloaded.userId}`, {
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then((r) => r.json())
|
||||
@@ -133,14 +142,16 @@ export function Dump(): React.JSX.Element {
|
||||
return () => controller.abort();
|
||||
}
|
||||
|
||||
if (isAt(shownRef.current, username, slug)) return;
|
||||
|
||||
(async () => {
|
||||
setDumpState({ status: "loading" });
|
||||
setOp(null);
|
||||
try {
|
||||
const res = await authFetch(`${API_URL}/api/dumps/${selectedDump}`, {
|
||||
cache: "no-store",
|
||||
signal: controller.signal,
|
||||
});
|
||||
const res = await authFetch(
|
||||
`${API_URL}/api/users/@${username}/dumps/${slug}`,
|
||||
{ cache: "no-store", signal: controller.signal },
|
||||
);
|
||||
const apiResponse = parseAPIResponse<Wire<Dump>>(await res.json());
|
||||
if (!apiResponse.success) {
|
||||
throw new Error(apiResponse.error.message);
|
||||
@@ -148,7 +159,7 @@ export function Dump(): React.JSX.Element {
|
||||
const dump: Dump = deserializeDump(apiResponse.data);
|
||||
setDumpState({ status: "loaded", dump });
|
||||
|
||||
fetch(`${API_URL}/api/users/by-id/${dump.userId}`, {
|
||||
fetch(`${API_URL}/api/users/${dump.userId}`, {
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then((r) => r.json())
|
||||
@@ -160,7 +171,7 @@ export function Dump(): React.JSX.Element {
|
||||
}
|
||||
})();
|
||||
return () => controller.abort();
|
||||
}, [selectedDump, preloaded, authFetch]);
|
||||
}, [username, slug, preloaded, authFetch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!lastDumpEvent) return;
|
||||
@@ -174,10 +185,12 @@ export function Dump(): React.JSX.Element {
|
||||
});
|
||||
}, [lastDumpEvent]);
|
||||
|
||||
const loadedDumpId = loadedDump?.id ?? null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedDump) return;
|
||||
if (!loadedDumpId) return;
|
||||
const controller = new AbortController();
|
||||
authFetch(`${API_URL}/api/dumps/${selectedDump}/comments`, {
|
||||
authFetch(`${API_URL}/api/dumps/${loadedDumpId}/comments`, {
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then((r) => r.json())
|
||||
@@ -190,13 +203,13 @@ export function Dump(): React.JSX.Element {
|
||||
return () => controller.abort();
|
||||
// connectionEpoch refetches on reconnect, for the comments missed while the
|
||||
// socket was down.
|
||||
}, [selectedDump, authFetch, connectionEpoch]);
|
||||
}, [loadedDumpId, authFetch, connectionEpoch]);
|
||||
|
||||
// The dumps that link to this one, or that it links to.
|
||||
useEffect(() => {
|
||||
if (!selectedDump) return;
|
||||
if (!loadedDumpId) return;
|
||||
const controller = new AbortController();
|
||||
authFetch(`${API_URL}/api/dumps/${selectedDump}/related`, {
|
||||
authFetch(`${API_URL}/api/dumps/${loadedDumpId}/related`, {
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then((r) => r.json())
|
||||
@@ -207,13 +220,13 @@ export function Dump(): React.JSX.Element {
|
||||
})
|
||||
.catch(() => {});
|
||||
return () => controller.abort();
|
||||
}, [selectedDump, authFetch]);
|
||||
}, [loadedDumpId, authFetch]);
|
||||
|
||||
// The server leaves out the private playlists of others.
|
||||
useEffect(() => {
|
||||
if (!selectedDump) return;
|
||||
if (!loadedDumpId) return;
|
||||
const controller = new AbortController();
|
||||
authFetch(`${API_URL}/api/dumps/${selectedDump}/playlists`, {
|
||||
authFetch(`${API_URL}/api/dumps/${loadedDumpId}/playlists`, {
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then((r) => r.json())
|
||||
@@ -228,7 +241,7 @@ export function Dump(): React.JSX.Element {
|
||||
return () => controller.abort();
|
||||
// Any playlist event may change the list, and they are rare enough to
|
||||
// refetch on each.
|
||||
}, [selectedDump, authFetch, lastPlaylistEvent]);
|
||||
}, [loadedDumpId, authFetch, lastPlaylistEvent]);
|
||||
|
||||
// A notification links to `#comment-<id>`. Rerun when the comments arrive,
|
||||
// since the element doesn't exist before.
|
||||
@@ -246,7 +259,6 @@ export function Dump(): React.JSX.Element {
|
||||
return () => clearTimeout(timer);
|
||||
}, [comments, location.hash]);
|
||||
|
||||
const loadedDumpId = dumpState.status === "loaded" ? dumpState.dump.id : null;
|
||||
useEffect(() => {
|
||||
if (
|
||||
!lastCommentEvent || !loadedDumpId ||
|
||||
@@ -472,7 +484,7 @@ export function Dump(): React.JSX.Element {
|
||||
/>
|
||||
{op
|
||||
? (
|
||||
<Link to={`/users/${op.username}`} className="dump-op-link">
|
||||
<Link to={userPath(op.username)} className="dump-op-link">
|
||||
{op.username}
|
||||
</Link>
|
||||
)
|
||||
|
||||
@@ -47,6 +47,9 @@ import { SubmitButton } from "../components/form/SubmitButton.tsx";
|
||||
import { TextField } from "../components/form/TextField.tsx";
|
||||
import { useApiForm } from "../hooks/form/useApiForm.ts";
|
||||
import { VisibilityToggle } from "../components/form/SegmentedField.tsx";
|
||||
import { SlugField } from "../components/form/SlugField.tsx";
|
||||
import { useCanonicalPath } from "../hooks/shared/useCanonicalPath.ts";
|
||||
import { userPath } from "../../shared/paths.ts";
|
||||
|
||||
type DumpEditState =
|
||||
| { status: "loading" }
|
||||
@@ -54,14 +57,18 @@ type DumpEditState =
|
||||
| { status: "loaded"; dump: Dump };
|
||||
|
||||
/**
|
||||
* Renders `/dumps/:selectedDump/edit`, for the dump's poster and moderators;
|
||||
* anyone else signed in gets an error rather than a form the API would refuse
|
||||
* to save. The dump comes from `GET /api/dumps/:dumpId`. The thumbnail, the
|
||||
* preview refresh and the deletion apply at once, and the form's other fields
|
||||
* on "Save", which goes back to the dump's page. A deletion goes to the index.
|
||||
* Renders `/@:username/dumps/:slug/edit`, for the dump's poster and
|
||||
* moderators; anyone else signed in gets an error rather than a form the API
|
||||
* would refuse to save. The dump comes from
|
||||
* `GET /api/users/@:username/dumps/:slug`, which answers a former slug too,
|
||||
* and the URL then takes the current one. The thumbnail, the preview refresh
|
||||
* and the deletion apply at once, and the form's other fields on "Save",
|
||||
* which goes back to the dump's page, at its new path if the slug changed. A
|
||||
* deletion goes to the index.
|
||||
*/
|
||||
export function DumpEdit(): React.JSX.Element {
|
||||
const { selectedDump } = useParams();
|
||||
const { handle, slug } = useParams();
|
||||
const username = handle?.slice(1);
|
||||
const navigate = useNavigate();
|
||||
const { authFetch, token, mediaToken, user } = useRequiredAuth();
|
||||
|
||||
@@ -82,16 +89,23 @@ export function DumpEdit(): React.JSX.Element {
|
||||
const [thumbError, setThumbError] = useState<string | null>(null);
|
||||
const [deleteError, setDeleteError] = useState<string | null>(null);
|
||||
|
||||
useCanonicalPath(
|
||||
state.status === "loaded" ? `${dumpUrl(state.dump)}/edit` : null,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedDump) return;
|
||||
if (!username || !slug) return;
|
||||
|
||||
(async () => {
|
||||
setState({ status: "loading" });
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/api/dumps/${selectedDump}`, {
|
||||
cache: "no-store",
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
});
|
||||
const res = await fetch(
|
||||
`${API_URL}/api/users/@${username}/dumps/${slug}`,
|
||||
{
|
||||
cache: "no-store",
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
},
|
||||
);
|
||||
const apiResponse = parseAPIResponse<Wire<Dump>>(await res.json());
|
||||
|
||||
if (apiResponse.success) {
|
||||
@@ -112,7 +126,7 @@ export function DumpEdit(): React.JSX.Element {
|
||||
setState({ status: "error", error: friendlyFetchError(err) });
|
||||
}
|
||||
})();
|
||||
}, [selectedDump, token, user]);
|
||||
}, [username, slug, token, user]);
|
||||
|
||||
const handleRefreshMetadata = async () => {
|
||||
if (state.status !== "loaded" || state.dump.kind !== "url") return;
|
||||
@@ -121,7 +135,7 @@ export function DumpEdit(): React.JSX.Element {
|
||||
setRefreshError(null);
|
||||
try {
|
||||
const res = await authFetch(
|
||||
`${API_URL}/api/dumps/${state.dump.id}/refresh-metadata`,
|
||||
`${API_URL}/api/dumps/${state.dump.id}/metadata`,
|
||||
{ method: "POST" },
|
||||
);
|
||||
const apiResponse = parseAPIResponse<Wire<Dump>>(await res.json());
|
||||
@@ -322,6 +336,7 @@ interface DumpEditFormProps {
|
||||
|
||||
interface EditValues {
|
||||
title: string;
|
||||
slug: string;
|
||||
url: string;
|
||||
comment: string;
|
||||
isPublic: boolean;
|
||||
@@ -359,6 +374,7 @@ function DumpEditForm({
|
||||
const form = useApiForm<EditValues>({
|
||||
defaultValues: {
|
||||
title: dump.title,
|
||||
slug: dump.slug,
|
||||
url: dump.url ?? "",
|
||||
comment: dump.comment ?? "",
|
||||
isPublic: !dump.isPrivate,
|
||||
@@ -371,9 +387,11 @@ function DumpEditForm({
|
||||
const currentTitle = form.watch("title");
|
||||
|
||||
const onSubmit = form.submit(
|
||||
async ({ title, url, comment, isPublic, newFile }) => {
|
||||
async ({ title, slug, url, comment, isPublic, newFile }) => {
|
||||
const trimmedTitle = title.trim();
|
||||
const isPrivate = !isPublic;
|
||||
// Sent only when changed, since each change counts against its limit.
|
||||
const newSlug = slug !== dump.slug ? slug : undefined;
|
||||
let res: Response;
|
||||
|
||||
const categoryIds = [...selectedCategoryIds];
|
||||
@@ -382,6 +400,7 @@ function DumpEditForm({
|
||||
const formData = new FormData();
|
||||
formData.append("file", newFile);
|
||||
formData.append("title", trimmedTitle);
|
||||
if (newSlug) formData.append("slug", newSlug);
|
||||
if (comment.trim()) formData.append("comment", comment.trim());
|
||||
formData.append("categoryIds", JSON.stringify(categoryIds));
|
||||
// In the same request, so the new file never goes out under the old
|
||||
@@ -398,12 +417,14 @@ function DumpEditForm({
|
||||
? {
|
||||
url: url.trim() || undefined,
|
||||
title: trimmedTitle,
|
||||
slug: newSlug,
|
||||
comment: comment.trim() || null,
|
||||
isPrivate,
|
||||
categoryIds,
|
||||
}
|
||||
: {
|
||||
title: trimmedTitle,
|
||||
slug: newSlug,
|
||||
comment: comment.trim() || null,
|
||||
isPrivate,
|
||||
categoryIds,
|
||||
@@ -509,6 +530,13 @@ function DumpEditForm({
|
||||
rules={{ required: true }}
|
||||
/>
|
||||
|
||||
<SlugField<EditValues>
|
||||
name="slug"
|
||||
titleName="title"
|
||||
prefix={`${userPath(dump.ownerUsername, "dumps")}/`}
|
||||
saved={dump}
|
||||
/>
|
||||
|
||||
<RichTextField<EditValues>
|
||||
name="comment"
|
||||
label={t`Why?`}
|
||||
|
||||
@@ -1,22 +1,18 @@
|
||||
/**
|
||||
* Renders the home page, which shows every dump, or one category's, in the
|
||||
* "hot", "new", "journal" and "followed" tabs.
|
||||
* "hot", "new", "journal" and "follow" tabs.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import { useLocation, useParams } from "react-router";
|
||||
import { useLocation } from "react-router";
|
||||
|
||||
import { AppHeader } from "../components/layout/AppHeader.tsx";
|
||||
import { PresenceRow } from "../components/feed/PresenceRow.tsx";
|
||||
import { FeedTabBar } from "../components/feed/FeedTabBar.tsx";
|
||||
import {
|
||||
DEFAULT_FEED_TAB,
|
||||
FEED_TABS,
|
||||
type FeedTab,
|
||||
} from "../config/feedTabs.ts";
|
||||
import { useDefaultFeedTab } from "../hooks/feed/useDefaultFeedTab.ts";
|
||||
import { type FeedTab } from "../../shared/paths.ts";
|
||||
import { useViewerDefaultFeedTab } from "../hooks/feed/useDefaultFeedTab.ts";
|
||||
|
||||
import { API_URL } from "../config/api.ts";
|
||||
|
||||
@@ -41,18 +37,18 @@ import { JournalFeed } from "../components/feed/JournalFeed.tsx";
|
||||
import { FollowedFeed } from "../components/feed/FollowedFeed.tsx";
|
||||
import { NotFound } from "./NotFound.tsx";
|
||||
|
||||
/**
|
||||
* Passed to {@link Index} by the router, from the `:categorySlug` of the URL.
|
||||
*/
|
||||
/** Passed to {@link Index} by the router, from the path. */
|
||||
export interface IndexProps {
|
||||
/** Without it, the feed holds every dump. An unknown slug renders 404. */
|
||||
categorySlug?: string;
|
||||
/** The tab the path names, or none for the viewer's default one. */
|
||||
feedTab?: FeedTab;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders `/~/:feedTab` and `/:categorySlug/:feedTab`, for anyone, the
|
||||
* "followed" tab for a signed-in user only. The feed comes from
|
||||
* `GET /api/dumps/`, or `GET /api/categories/:slug/dumps`, a page at a time,
|
||||
* Renders `/`, `/:feedTab`, `/:categorySlug` and `/:categorySlug/:feedTab`,
|
||||
* for anyone, the "follow" tab for a signed-in user only. The feed comes from
|
||||
* `GET /api/dumps`, or `GET /api/dumps?category=`, a page at a time,
|
||||
* and the "hot", "new" and "journal" tabs share it. `WSContext` adds the dumps
|
||||
* posted since, the live vote counts, and who's online. The router keys the
|
||||
* page by category, so switching tabs keeps the feed and switching categories
|
||||
@@ -60,7 +56,7 @@ export interface IndexProps {
|
||||
* Android (`?share_url=`).
|
||||
*/
|
||||
export function Index(
|
||||
{ categorySlug }: IndexProps,
|
||||
{ categorySlug, feedTab }: IndexProps,
|
||||
): React.JSX.Element {
|
||||
const location = useLocation();
|
||||
const justDeletedId = (location.state as { deletedDumpId?: string } | null)
|
||||
@@ -79,22 +75,16 @@ export function Index(
|
||||
categorySlug ? (category ? category.name : undefined) : null,
|
||||
);
|
||||
|
||||
const { feedTab: rawTab } = useParams();
|
||||
const [preferredTab] = useDefaultFeedTab();
|
||||
const defaultTab: FeedTab = preferredTab === "followed" && !user
|
||||
? DEFAULT_FEED_TAB
|
||||
: preferredTab;
|
||||
// A guest on "followed", from a shared link or after signing out, gets the
|
||||
const defaultTab = useViewerDefaultFeedTab();
|
||||
// A guest on "follow", from a shared link or after signing out, gets the
|
||||
// default tab rather than an empty page.
|
||||
const tab: FeedTab =
|
||||
(FEED_TABS as readonly string[]).includes(rawTab ?? "") &&
|
||||
(rawTab !== "followed" || !!user)
|
||||
? (rawTab as FeedTab)
|
||||
: defaultTab;
|
||||
const tab: FeedTab = feedTab && (feedTab !== "follow" || !!user)
|
||||
? feedTab
|
||||
: defaultTab;
|
||||
|
||||
const feedUrl = categorySlug
|
||||
? `${API_URL}/api/categories/${encodeURIComponent(categorySlug)}/dumps`
|
||||
: `${API_URL}/api/dumps/`;
|
||||
? `${API_URL}/api/dumps?category=${encodeURIComponent(categorySlug)}`
|
||||
: `${API_URL}/api/dumps`;
|
||||
const fetchPage = useCallback(
|
||||
(page: number, signal?: AbortSignal) =>
|
||||
authFetch(pageUrl(feedUrl, page), { signal })
|
||||
@@ -113,9 +103,9 @@ export function Index(
|
||||
);
|
||||
useDumpListSync(setItems);
|
||||
|
||||
// The Web Share Target: Android's share sheet opens `/?share_url=…`, which
|
||||
// the redirect from `/` keeps. The query is dropped from the URL at once, so
|
||||
// a reload doesn't share the link a second time.
|
||||
// The Web Share Target: Android's share sheet opens `/?share_url=…`. The
|
||||
// query is dropped from the URL at once, so a reload doesn't share the link
|
||||
// a second time.
|
||||
const searchParams = new URLSearchParams(location.search);
|
||||
const shareUrl = searchParams.get("share_url") ??
|
||||
searchParams.get("share_text") ?? "";
|
||||
@@ -201,7 +191,7 @@ export function Index(
|
||||
fitWithin=".app-header-center"
|
||||
fitBeside=".feed-sort"
|
||||
/>
|
||||
<FeedTabBar />
|
||||
<FeedTabBar categorySlug={categorySlug} tab={tab} />
|
||||
</div>
|
||||
}
|
||||
disableNew={dumpsState.status === "error"}
|
||||
@@ -209,7 +199,7 @@ export function Index(
|
||||
/>
|
||||
|
||||
<div className="index-below-header">
|
||||
<FeedTabBar />
|
||||
<FeedTabBar categorySlug={categorySlug} tab={tab} />
|
||||
<PresenceRow fitWithin=".index-below-header" fitBeside=".feed-sort" />
|
||||
</div>
|
||||
|
||||
@@ -217,9 +207,7 @@ export function Index(
|
||||
<DumpFeed order={tab} {...mainFeedProps} />
|
||||
)}
|
||||
{tab === "journal" && <JournalFeed {...mainFeedProps} />}
|
||||
{tab === "followed" && user && (
|
||||
<FollowedFeed categorySlug={categorySlug} />
|
||||
)}
|
||||
{tab === "follow" && user && <FollowedFeed categorySlug={categorySlug} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
38
src/pages/Manage.tsx
Normal file
38
src/pages/Manage.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Renders the site's tools, `/manage`, for those who hold `category:manage`.
|
||||
* Another user's role and name are managed on their profile's "manage" tab.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
import { can } from "../utils/auth/permissions.ts";
|
||||
import { useRequiredAuth } from "../hooks/auth/useAuth.ts";
|
||||
import { useDocumentTitle } from "../hooks/shared/useDocumentTitle.ts";
|
||||
import { PageShell } from "../components/layout/PageShell.tsx";
|
||||
import { ProfileSection } from "../components/profile/ProfileSection.tsx";
|
||||
import { CategoryManager } from "../components/category/CategoryManager.tsx";
|
||||
import { NotFound } from "./NotFound.tsx";
|
||||
|
||||
/**
|
||||
* Renders the category manager, signed in only; without `category:manage`,
|
||||
* which the API checks again, the page isn't found.
|
||||
*/
|
||||
export function Manage(): React.JSX.Element {
|
||||
useDocumentTitle(t`Manage`);
|
||||
const { user } = useRequiredAuth();
|
||||
if (!can(user, "category:manage")) return <NotFound />;
|
||||
return (
|
||||
<PageShell>
|
||||
<div className="form-page-header">
|
||||
<h1 className="form-page-title">
|
||||
<Trans>Manage</Trans>
|
||||
</h1>
|
||||
</div>
|
||||
<ProfileSection title={<Trans>Categories</Trans>}>
|
||||
<CategoryManager />
|
||||
</ProfileSection>
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Renders the notifications page, `/notifications`, for a signed-in user. It
|
||||
* reads them from `GET /api/notifications` and adds the ones `WSContext`
|
||||
* reads them from `GET /api/me/notifications` and adds the ones `WSContext`
|
||||
* receives while it is open.
|
||||
*
|
||||
* @module
|
||||
@@ -22,11 +22,13 @@ import { useWS } from "../hooks/ws/useWS.ts";
|
||||
import type {
|
||||
CommentLikedData,
|
||||
DumpCommentedData,
|
||||
DumpRef,
|
||||
DumpUpvotedData,
|
||||
Notification,
|
||||
NotificationData,
|
||||
PlaylistDumpAddedData,
|
||||
PlaylistFollowedData,
|
||||
PlaylistRef,
|
||||
UserDumpPostedData,
|
||||
UserFollowedData,
|
||||
UserMentionedData,
|
||||
@@ -35,6 +37,7 @@ import { deserializeNotification } from "../utils/shared/deserialize.ts";
|
||||
import { pageUrl, readPage } from "../utils/feed/pagedList.ts";
|
||||
import { usePagedList } from "../hooks/feed/usePagedList.ts";
|
||||
import { PageShell } from "../components/layout/PageShell.tsx";
|
||||
import { dumpPath, playlistPath, userPath } from "../../shared/paths.ts";
|
||||
|
||||
type NotifIconKind =
|
||||
| "upvote"
|
||||
@@ -103,40 +106,63 @@ function NotifIcon({ type }: { type: Notification["type"] }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns where notification `n` leads. A notification about a comment links
|
||||
* to its `#comment-<id>` anchor on the dump's page.
|
||||
* Returns the path of a notification's dump, from the ref the server joined,
|
||||
* with `hash` after it; null once the dump is deleted.
|
||||
*/
|
||||
function notificationLink(n: Notification): string {
|
||||
function dumpLink(ref: DumpRef, hash = ""): string | null {
|
||||
return ref.dumpSlug && ref.dumpOwnerUsername
|
||||
? `${
|
||||
dumpPath({ ownerUsername: ref.dumpOwnerUsername, slug: ref.dumpSlug })
|
||||
}${hash}`
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Returns the path of a notification's playlist, as {@link dumpLink} does. */
|
||||
function playlistLink(ref: PlaylistRef): string | null {
|
||||
return ref.playlistSlug && ref.playlistOwnerUsername
|
||||
? playlistPath({
|
||||
ownerUsername: ref.playlistOwnerUsername,
|
||||
slug: ref.playlistSlug,
|
||||
})
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns where notification `n` leads, or null when what it is about is
|
||||
* gone. A notification about a comment links to its `#comment-<id>` anchor on
|
||||
* the dump's page.
|
||||
*/
|
||||
function notificationLink(n: Notification): string | null {
|
||||
const data = n.data as NotificationData;
|
||||
switch (n.type) {
|
||||
case "user_followed":
|
||||
return `/users/${(data as UserFollowedData).followerUsername}`;
|
||||
return userPath((data as UserFollowedData).followerUsername);
|
||||
case "playlist_followed":
|
||||
return `/playlists/${(data as PlaylistFollowedData).playlistId}`;
|
||||
return playlistLink(data as PlaylistFollowedData);
|
||||
case "user_dump_posted":
|
||||
return `/dumps/${(data as UserDumpPostedData).dumpId}`;
|
||||
case "playlist_dump_added":
|
||||
return `/dumps/${(data as PlaylistDumpAddedData).dumpId}`;
|
||||
case "dump_upvoted":
|
||||
return `/dumps/${(data as DumpUpvotedData).dumpId}`;
|
||||
return dumpLink(data as DumpRef);
|
||||
case "dump_commented":
|
||||
return `/dumps/${(data as DumpCommentedData).dumpId}#comment-${
|
||||
(data as DumpCommentedData).commentId
|
||||
}`;
|
||||
return dumpLink(
|
||||
data as DumpCommentedData,
|
||||
`#comment-${(data as DumpCommentedData).commentId}`,
|
||||
);
|
||||
case "comment_liked":
|
||||
return `/dumps/${(data as CommentLikedData).dumpId}#comment-${
|
||||
(data as CommentLikedData).commentId
|
||||
}`;
|
||||
return dumpLink(
|
||||
data as CommentLikedData,
|
||||
`#comment-${(data as CommentLikedData).commentId}`,
|
||||
);
|
||||
case "user_mentioned": {
|
||||
const d = data as UserMentionedData;
|
||||
if (d.contextType === "comment") {
|
||||
return `/dumps/${d.dumpId}#comment-${d.contextId}`;
|
||||
return dumpLink(d, `#comment-${d.contextId}`);
|
||||
}
|
||||
if (d.contextType === "dump") return `/dumps/${d.contextId}`;
|
||||
if (d.contextType === "dump") return dumpLink(d);
|
||||
// A query string alone keeps this page, and `ChatProvider` opens the
|
||||
// chat over it.
|
||||
if (d.contextType === "chat") return `?chat=open`;
|
||||
return `/playlists/${d.contextId}`;
|
||||
return playlistLink(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -286,7 +312,11 @@ export function Notifications(): React.JSX.Element {
|
||||
user?.id,
|
||||
(page, signal) =>
|
||||
authFetch(
|
||||
pageUrl(`${API_URL}/api/notifications`, page, NOTIFICATIONS_PAGE_SIZE),
|
||||
pageUrl(
|
||||
`${API_URL}/api/me/notifications`,
|
||||
page,
|
||||
NOTIFICATIONS_PAGE_SIZE,
|
||||
),
|
||||
{ signal },
|
||||
).then((res) => readPage(res, deserializeNotification)),
|
||||
);
|
||||
@@ -316,7 +346,7 @@ export function Notifications(): React.JSX.Element {
|
||||
useEffect(() => {
|
||||
if (!loaded || markedReadRef.current === lastNotification) return;
|
||||
markedReadRef.current = lastNotification;
|
||||
authFetch(`${API_URL}/api/notifications/read-all`, { method: "POST" })
|
||||
authFetch(`${API_URL}/api/me/notifications/read`, { method: "POST" })
|
||||
.then((res) => {
|
||||
if (res.ok) clearUnreadNotifications();
|
||||
})
|
||||
@@ -375,17 +405,10 @@ export function Notifications(): React.JSX.Element {
|
||||
: t`Earlier`}
|
||||
</h2>
|
||||
<ul className="notification-list">
|
||||
{items.map((n) => (
|
||||
<li
|
||||
key={n.id}
|
||||
className={`notification-item${
|
||||
!n.read ? " notification-item--unread" : ""
|
||||
}`}
|
||||
>
|
||||
<Link
|
||||
to={notificationLink(n)}
|
||||
className="notification-item-link"
|
||||
>
|
||||
{items.map((n) => {
|
||||
const link = notificationLink(n);
|
||||
const inner = (
|
||||
<>
|
||||
<NotifIcon type={n.type} />
|
||||
<div className="notification-body">
|
||||
<span className="notification-content">
|
||||
@@ -403,9 +426,25 @@ export function Notifications(): React.JSX.Element {
|
||||
{!n.read && (
|
||||
<span className="notif-dot" aria-hidden="true" />
|
||||
)}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<li
|
||||
key={n.id}
|
||||
className={`notification-item${
|
||||
!n.read ? " notification-item--unread" : ""
|
||||
}`}
|
||||
>
|
||||
{link
|
||||
? (
|
||||
<Link to={link} className="notification-item-link">
|
||||
{inner}
|
||||
</Link>
|
||||
)
|
||||
: <div className="notification-item-link">{inner}</div>}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</section>
|
||||
))}
|
||||
|
||||
@@ -23,14 +23,14 @@ import { PlaylistEditForm } from "../components/playlist/PlaylistEditForm.tsx";
|
||||
import { PlaylistDumpList } from "../components/playlist/PlaylistDumpList.tsx";
|
||||
|
||||
/**
|
||||
* Renders `/playlists/:playlistId` (an id or a slug), for anyone who may see
|
||||
* the playlist: a private one only to its owner. `usePlaylist` loads it and
|
||||
* keeps it live. Its owner, or a user with `playlist:moderate`, can edit or
|
||||
* Renders `/@:username/playlists/:slug`, for anyone who may see the playlist:
|
||||
* a private one only to its owner. `usePlaylist` loads it, by a former name or
|
||||
* slug too, and keeps it live. Its owner, or a user with `playlist:moderate`, can edit or
|
||||
* delete it, drag its dumps into a new order, and remove one, with a short
|
||||
* window to undo.
|
||||
*/
|
||||
export function PlaylistDetail(): React.JSX.Element {
|
||||
const { playlistId } = useParams<{ playlistId: string }>();
|
||||
const { handle, slug } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const { user } = useAuth();
|
||||
const {
|
||||
@@ -43,7 +43,7 @@ export function PlaylistDetail(): React.JSX.Element {
|
||||
move,
|
||||
saveOrder,
|
||||
deletePlaylist,
|
||||
} = usePlaylist(playlistId);
|
||||
} = usePlaylist(handle?.slice(1), slug);
|
||||
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const headerRef = useHeightTransition<HTMLDivElement>(editOpen);
|
||||
|
||||
@@ -44,11 +44,14 @@ export function ResetPassword(): React.JSX.Element {
|
||||
|
||||
const onSubmit = form.submit(async ({ newPassword }) => {
|
||||
await expectOk(
|
||||
await fetch(`${API_URL}/api/users/reset-password`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ token, newPassword }),
|
||||
}),
|
||||
await fetch(
|
||||
`${API_URL}/api/password-resets/${encodeURIComponent(token)}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ newPassword }),
|
||||
},
|
||||
),
|
||||
);
|
||||
setDone(true);
|
||||
});
|
||||
|
||||
@@ -39,9 +39,13 @@ import {
|
||||
} from "../utils/feed/pagedList.ts";
|
||||
import { useFetchState } from "../hooks/shared/useFetchState.ts";
|
||||
import { useLoadMore } from "../hooks/feed/usePagedList.ts";
|
||||
|
||||
const SEARCH_TABS = ["dumps", "users", "playlists"] as const;
|
||||
type Tab = (typeof SEARCH_TABS)[number];
|
||||
import {
|
||||
SEARCH_TABS,
|
||||
searchPath,
|
||||
type SearchTab as Tab,
|
||||
userPath,
|
||||
} from "../../shared/paths.ts";
|
||||
import { NotFound } from "./NotFound.tsx";
|
||||
|
||||
/**
|
||||
* Held by `Search` for a query, from the first page of `SearchResults`. The
|
||||
@@ -56,7 +60,7 @@ interface Results {
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders `/search?q=` and `/search/~/:searchTab`, for anyone. The results come
|
||||
* Renders `/search?q=` and `/search/:searchTab?q=`, for anyone. The results come
|
||||
* from `GET /api/search`, signed in when the viewer is, so they find their own
|
||||
* private dumps and playlists too. The dumps load a page at a time as the
|
||||
* "dumps" tab scrolls. A new `q` aborts the search under way.
|
||||
@@ -65,7 +69,7 @@ export function Search(): React.JSX.Element {
|
||||
useDocumentTitle(t`Search`);
|
||||
const [searchParams] = useSearchParams();
|
||||
const q = searchParams.get("q") ?? "";
|
||||
const [tab, setTab] = useTabParam<Tab>(SEARCH_TABS, "dumps");
|
||||
const [tab, setTab] = useTabParam<Tab>(searchPath(), SEARCH_TABS, "dumps");
|
||||
|
||||
const { user, authFetch } = useAuth();
|
||||
const search = useCallback(async (page: number, signal?: AbortSignal) => {
|
||||
@@ -120,6 +124,8 @@ export function Search(): React.JSX.Element {
|
||||
return count !== null ? t`${label} (${count})` : label;
|
||||
}
|
||||
|
||||
if (!tab) return <NotFound />;
|
||||
|
||||
return (
|
||||
<div className="page-shell">
|
||||
<AppHeader />
|
||||
@@ -183,7 +189,7 @@ export function Search(): React.JSX.Element {
|
||||
{results.users.map((u) => (
|
||||
<li key={u.id}>
|
||||
<Link
|
||||
to={`/users/${u.username}`}
|
||||
to={userPath(u.username)}
|
||||
className="user-result-item"
|
||||
>
|
||||
<span className="user-result-name">@{u.username}</span>
|
||||
|
||||
213
src/pages/Settings.tsx
Normal file
213
src/pages/Settings.tsx
Normal file
@@ -0,0 +1,213 @@
|
||||
/**
|
||||
* Renders the signed-in user's settings page, `/settings`, where they change
|
||||
* their name, their password, their account's settings and this browser's.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { useState } from "react";
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
// A label shared with the emails is named by its id, its words being in
|
||||
// locales/ only; the macro's Trans takes the English in place.
|
||||
import { Trans as Message } from "@lingui/react";
|
||||
import type { ColorScheme, StyleName } from "../../shared/theme.ts";
|
||||
import type { FeedTab } from "../../shared/paths.ts";
|
||||
import type { Wire } from "../../shared/api.ts";
|
||||
import type { SelfUser } from "../../shared/user.ts";
|
||||
import { API_URL } from "../config/api.ts";
|
||||
import { useTheme } from "../hooks/theme/useTheme.ts";
|
||||
import { useDefaultFeedTab } from "../hooks/feed/useDefaultFeedTab.ts";
|
||||
import { useSoundsEnabled } from "../hooks/shared/useSoundsEnabled.ts";
|
||||
import { useSettings } from "../hooks/auth/useSettings.ts";
|
||||
import { useRequiredAuth } from "../hooks/auth/useAuth.ts";
|
||||
import { useDocumentTitle } from "../hooks/shared/useDocumentTitle.ts";
|
||||
import { EMAIL_ENABLED } from "../config/instance.ts";
|
||||
import { previewChime } from "../utils/shared/sound.ts";
|
||||
import { expectOk } from "../utils/shared/api.ts";
|
||||
import { deserializeSelfUser } from "../utils/shared/deserialize.ts";
|
||||
import { PageShell } from "../components/layout/PageShell.tsx";
|
||||
import {
|
||||
Segmented,
|
||||
type SegmentedOption,
|
||||
} from "../components/shared/Segmented.tsx";
|
||||
import { ChangePasswordModal } from "../components/profile/ChangePasswordModal.tsx";
|
||||
import { ProfileSection } from "../components/profile/ProfileSection.tsx";
|
||||
import { SettingRow } from "../components/profile/SettingRow.tsx";
|
||||
import { UsernameField } from "../components/profile/UsernameField.tsx";
|
||||
import { RENAME_LIMITS } from "../../shared/validation.ts";
|
||||
|
||||
// The styles' names are their own, in every language.
|
||||
const STYLE_OPTIONS: SegmentedOption<StyleName>[] = [
|
||||
{ value: "smooth", label: "Smooth" },
|
||||
{ value: "brutalist", label: "Brutalist" },
|
||||
{ value: "geocities", label: "GeoCities" },
|
||||
{ value: "nyt", label: "Times" },
|
||||
{ value: "kanagawa", label: "Kanagawa" },
|
||||
{ value: "melange", label: "Melange" },
|
||||
];
|
||||
|
||||
const COLOR_SCHEME_OPTIONS: SegmentedOption<ColorScheme>[] = [
|
||||
{ value: "auto", label: <Trans>Auto</Trans> },
|
||||
{ value: "light", label: <Trans>Light</Trans> },
|
||||
{ value: "dark", label: <Trans>Dark</Trans> },
|
||||
];
|
||||
|
||||
const FEED_TAB_OPTIONS: SegmentedOption<FeedTab>[] = [
|
||||
{ value: "hot", label: <Trans>Hot</Trans> },
|
||||
{ value: "new", label: <Trans>New</Trans> },
|
||||
{ value: "journal", label: <Trans>Journal</Trans> },
|
||||
{ value: "follow", label: <Trans>Followed</Trans> },
|
||||
];
|
||||
|
||||
const ON_OFF_OPTIONS: SegmentedOption<boolean>[] = [
|
||||
{ value: true, label: <Trans>On</Trans> },
|
||||
{ value: false, label: <Trans>Off</Trans> },
|
||||
];
|
||||
|
||||
/**
|
||||
* Renders `/settings`, signed in only: the username, the password change,
|
||||
* which opens {@link ChangePasswordModal}, and the settings, each saved as
|
||||
* soon as it is clicked. A new name is saved to `PATCH /api/me`, at most once
|
||||
* in 30 days but for those with `user:manage`, and the old one keeps leading
|
||||
* to the user. The style, color scheme and digests are saved to the account;
|
||||
* the default feed tab and sounds, for now, to this browser.
|
||||
*/
|
||||
export function Settings(): React.JSX.Element {
|
||||
useDocumentTitle(t`Settings`);
|
||||
const { user, authFetch, updateSession } = useRequiredAuth();
|
||||
const { style, colorScheme, setStyle, setColorScheme } = useTheme();
|
||||
const [defaultFeedTab, setDefaultFeedTab] = useDefaultFeedTab();
|
||||
const [soundsEnabled, setSoundsEnabled] = useSoundsEnabled();
|
||||
const { settings, updateSettings } = useSettings();
|
||||
// Until the session has the settings, a click would save over unknown ones.
|
||||
const digestsDisabled = !EMAIL_ENABLED || !settings;
|
||||
const [changePasswordOpen, setChangePasswordOpen] = useState(false);
|
||||
const renameDays = RENAME_LIMITS.USERNAME.windowMs / 86_400_000;
|
||||
|
||||
async function rename(username: string): Promise<string> {
|
||||
const self = deserializeSelfUser(
|
||||
await expectOk<Wire<SelfUser>>(
|
||||
await authFetch(`${API_URL}/api/me`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ username }),
|
||||
}),
|
||||
),
|
||||
);
|
||||
updateSession({ user: self });
|
||||
return self.username;
|
||||
}
|
||||
|
||||
return (
|
||||
<PageShell>
|
||||
<div className="form-page-header">
|
||||
<h1 className="form-page-title">
|
||||
<Trans>Settings</Trans>
|
||||
</h1>
|
||||
</div>
|
||||
<ProfileSection title={<Trans>Account</Trans>}>
|
||||
<div className="profile-appearance-grid">
|
||||
<SettingRow label={<Trans>Username</Trans>}>
|
||||
<UsernameField
|
||||
key={user.username}
|
||||
username={user.username}
|
||||
save={rename}
|
||||
hint={
|
||||
<Trans>
|
||||
You can change it once every {renameDays}{" "}
|
||||
days. Links to your old name keep working, and nobody else can
|
||||
take it.
|
||||
</Trans>
|
||||
}
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow label={<Trans>Password</Trans>}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--ghost"
|
||||
onClick={() => setChangePasswordOpen(true)}
|
||||
>
|
||||
<Trans>Change password…</Trans>
|
||||
</button>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</ProfileSection>
|
||||
<ProfileSection title={<Trans>Appearance</Trans>}>
|
||||
<div className="profile-appearance-grid">
|
||||
<SettingRow label={<Trans>Style</Trans>}>
|
||||
<Segmented
|
||||
options={STYLE_OPTIONS}
|
||||
value={style}
|
||||
onChange={setStyle}
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow label={<Trans>Color scheme</Trans>}>
|
||||
<Segmented
|
||||
options={COLOR_SCHEME_OPTIONS}
|
||||
value={colorScheme}
|
||||
onChange={setColorScheme}
|
||||
/>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</ProfileSection>
|
||||
<ProfileSection title={<Trans>Feeds</Trans>}>
|
||||
<div className="profile-appearance-grid">
|
||||
<SettingRow label={<Trans>Default tab</Trans>}>
|
||||
<Segmented
|
||||
options={FEED_TAB_OPTIONS}
|
||||
value={defaultFeedTab}
|
||||
onChange={setDefaultFeedTab}
|
||||
/>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</ProfileSection>
|
||||
<ProfileSection title={<Trans>Notifications</Trans>}>
|
||||
<div className="profile-appearance-grid">
|
||||
<SettingRow label={<Trans>Sounds</Trans>}>
|
||||
<Segmented
|
||||
options={ON_OFF_OPTIONS}
|
||||
value={soundsEnabled}
|
||||
onChange={(on) => {
|
||||
setSoundsEnabled(on);
|
||||
// Let the user hear what they just turned on.
|
||||
if (on) previewChime("notify");
|
||||
}}
|
||||
/>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</ProfileSection>
|
||||
<ProfileSection title={<Trans>Email</Trans>}>
|
||||
<div className="profile-appearance-grid">
|
||||
<SettingRow label={<Message id="digest.weekly" />}>
|
||||
<Segmented
|
||||
options={ON_OFF_OPTIONS}
|
||||
value={settings?.digestWeekly ?? true}
|
||||
disabled={digestsDisabled}
|
||||
onChange={(on) =>
|
||||
updateSettings({ digestWeekly: on }).catch(() => {})}
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow label={<Message id="digest.monthly" />}>
|
||||
<Segmented
|
||||
options={ON_OFF_OPTIONS}
|
||||
value={settings?.digestMonthly ?? true}
|
||||
disabled={digestsDisabled}
|
||||
onChange={(on) =>
|
||||
updateSettings({ digestMonthly: on }).catch(() => {})}
|
||||
/>
|
||||
</SettingRow>
|
||||
</div>
|
||||
{!EMAIL_ENABLED && (
|
||||
<p className="form-hint profile-appearance-note">
|
||||
<Trans>
|
||||
This site doesn't send email, so no digest goes out.
|
||||
</Trans>
|
||||
</p>
|
||||
)}
|
||||
</ProfileSection>
|
||||
{changePasswordOpen && (
|
||||
<ChangePasswordModal onClose={() => setChangePasswordOpen(false)} />
|
||||
)}
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
@@ -27,7 +27,7 @@ import { readUnsubscribeCadence } from "../utils/auth/unsubscribe.ts";
|
||||
/**
|
||||
* Renders `/unsubscribe?token=`, for anyone holding a digest's link. It asks
|
||||
* before turning the digest off, since mail scanners open every link in an
|
||||
* email, then posts the token to `POST /api/users/unsubscribe`.
|
||||
* email, then posts the token to `POST /api/unsubscribe`.
|
||||
*/
|
||||
export function Unsubscribe(): React.JSX.Element {
|
||||
useDocumentTitle(t`Unsubscribe`);
|
||||
@@ -41,7 +41,7 @@ export function Unsubscribe(): React.JSX.Element {
|
||||
const onSubmit = form.submit(async () => {
|
||||
await expectOk(
|
||||
await fetch(
|
||||
`${API_URL}/api/users/unsubscribe?token=${encodeURIComponent(token)}`,
|
||||
`${API_URL}/api/unsubscribe?token=${encodeURIComponent(token)}`,
|
||||
{ method: "POST" },
|
||||
),
|
||||
);
|
||||
@@ -50,7 +50,7 @@ export function Unsubscribe(): React.JSX.Element {
|
||||
|
||||
const settingsLink = user && (
|
||||
<p className="auth-card-footer">
|
||||
<Link to={`/users/${user.username}/~/settings`}>
|
||||
<Link to="/settings">
|
||||
<Trans>Your settings</Trans>
|
||||
</Link>
|
||||
</p>
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
/**
|
||||
* Renders the page listing all of a user's dumps, which the "dumps" section of
|
||||
* their profile links to.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
import { Link, useParams } from "react-router";
|
||||
|
||||
import { useAuth } from "../hooks/auth/useAuth.ts";
|
||||
import { useDocumentTitle } from "../hooks/shared/useDocumentTitle.ts";
|
||||
import { useWS } from "../hooks/ws/useWS.ts";
|
||||
import { useDumpListSync } from "../hooks/dump/useDumpListSync.ts";
|
||||
import { usePositionAwareSync } from "../hooks/feed/usePositionAwareSync.ts";
|
||||
import { useUserDumpFeed } from "../hooks/dump/useUserDumpFeed.ts";
|
||||
import { DumpCardList } from "../components/dump/DumpCardList.tsx";
|
||||
import { NewDumpButton } from "../components/dump/NewDumpButton.tsx";
|
||||
import { FeedFooter } from "../components/feed/FeedFooter.tsx";
|
||||
import { ProfileSubpageHeader } from "../components/profile/ProfileSubpageHeader.tsx";
|
||||
import { PageShell } from "../components/layout/PageShell.tsx";
|
||||
import { PageError } from "../components/layout/PageError.tsx";
|
||||
|
||||
/**
|
||||
* Renders `/users/:username/dumps`, for anyone. The dumps come from
|
||||
* `useUserDumpFeed`, the private ones for their owner only, and the socket's
|
||||
* events keep them current. On one's own list, a button opens the dump
|
||||
* creation modal.
|
||||
*/
|
||||
export function UserDumps(): React.JSX.Element {
|
||||
const { username } = useParams();
|
||||
const { user: me } = useAuth();
|
||||
const { lastDumpEvent } = useWS();
|
||||
|
||||
useDocumentTitle(username ?? null);
|
||||
|
||||
const { state, setItems, sentinelRef } = useUserDumpFeed(
|
||||
username,
|
||||
"dumps",
|
||||
`feed:user-dumps-full:${username ?? ""}`,
|
||||
);
|
||||
|
||||
const profileUserId = state.status === "loaded" ? state.profileUser.id : null;
|
||||
const isOwnProfile = me?.id === profileUserId;
|
||||
|
||||
const dumpItems = state.status === "loaded" ? state.dumps.items : [];
|
||||
usePositionAwareSync(
|
||||
dumpItems,
|
||||
setItems,
|
||||
lastDumpEvent,
|
||||
(d) => !d.isPrivate && d.userId === profileUserId,
|
||||
);
|
||||
useDumpListSync(setItems, {
|
||||
isOwner: isOwnProfile,
|
||||
});
|
||||
|
||||
if (state.status === "loading") {
|
||||
return (
|
||||
<PageShell>
|
||||
<p className="page-loading">
|
||||
<Trans>Loading…</Trans>
|
||||
</p>
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
|
||||
if (state.status === "error") {
|
||||
return (
|
||||
<PageError
|
||||
message={state.error}
|
||||
actions={
|
||||
<Link to={`/users/${username}`} className="btn-border">
|
||||
<Trans>← Back to profile</Trans>
|
||||
</Link>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const { profileUser, dumps: { items: dumps, hasMore, loadingMore } } = state;
|
||||
|
||||
return (
|
||||
<PageShell>
|
||||
<ProfileSubpageHeader
|
||||
username={username!}
|
||||
profileUser={profileUser}
|
||||
title={t`Dumps`}
|
||||
actions={isOwnProfile && <NewDumpButton />}
|
||||
/>
|
||||
{dumps.length === 0
|
||||
? (
|
||||
<p className="empty-state">
|
||||
<Trans>Nothing here yet.</Trans>
|
||||
</p>
|
||||
)
|
||||
: (
|
||||
<>
|
||||
<DumpCardList dumps={dumps} />
|
||||
<FeedFooter
|
||||
hasMore={hasMore}
|
||||
loadingMore={loadingMore}
|
||||
sentinelRef={sentinelRef}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
@@ -50,7 +50,7 @@ export function UserLogin(): React.JSX.Element {
|
||||
|
||||
const onSubmit = form.submit(async ({ username, password }) => {
|
||||
const data = await expectOk<Wire<AuthResponse>>(
|
||||
await fetch(`${API_URL}/api/users/login`, {
|
||||
await fetch(`${API_URL}/api/sessions`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username, password } satisfies LoginUserRequest),
|
||||
@@ -120,7 +120,7 @@ function ResetRequestPanel() {
|
||||
// The server answers 200 whether or not the address is known, so as not
|
||||
// to reveal which ones are. An error here means it failed.
|
||||
await expectOk(
|
||||
await fetch(`${API_URL}/api/users/request-password-reset`, {
|
||||
await fetch(`${API_URL}/api/password-resets`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email: email.trim() }),
|
||||
|
||||
@@ -1,337 +0,0 @@
|
||||
/**
|
||||
* Renders the page that lists all of a user's playlists, the ones they made and
|
||||
* the ones they follow.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Link, useParams } from "react-router";
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
|
||||
import { API_URL } from "../config/api.ts";
|
||||
import { expectOk, friendlyFetchError } from "../utils/shared/api.ts";
|
||||
import type { Playlist } from "../../shared/playlist.ts";
|
||||
import type { PublicUser } from "../../shared/user.ts";
|
||||
import {
|
||||
deserializePlaylist,
|
||||
hydratePlaylist,
|
||||
} from "../utils/shared/deserialize.ts";
|
||||
import { useAuth } from "../hooks/auth/useAuth.ts";
|
||||
import { useDocumentTitle } from "../hooks/shared/useDocumentTitle.ts";
|
||||
import { useWS } from "../hooks/ws/useWS.ts";
|
||||
import { usePlaylistListSync } from "../hooks/playlist/usePlaylistListSync.ts";
|
||||
import { usePositionAwareSync } from "../hooks/feed/usePositionAwareSync.ts";
|
||||
import { useInfiniteScroll } from "../hooks/feed/useInfiniteScroll.ts";
|
||||
import { useFeedCache } from "../hooks/feed/useFeedCache.ts";
|
||||
import {
|
||||
useScrollRestore,
|
||||
useScrollSave,
|
||||
} from "../hooks/feed/useScrollSave.ts";
|
||||
import {
|
||||
canLoadMore,
|
||||
mapItems,
|
||||
type PagedList,
|
||||
pageUrl,
|
||||
readFirstPage,
|
||||
readPage,
|
||||
restoredList,
|
||||
withFirst,
|
||||
} from "../utils/feed/pagedList.ts";
|
||||
import { useLoadMore } from "../hooks/feed/usePagedList.ts";
|
||||
import { fetchPublicUser } from "../utils/shared/fetchPublicUser.ts";
|
||||
import { PlaylistCardList } from "../components/playlist/PlaylistCardList.tsx";
|
||||
import { FeedFooter } from "../components/feed/FeedFooter.tsx";
|
||||
import { ProfileSection } from "../components/profile/ProfileSection.tsx";
|
||||
import { NewPlaylistButton } from "../components/playlist/NewPlaylistButton.tsx";
|
||||
import { ProfileSubpageHeader } from "../components/profile/ProfileSubpageHeader.tsx";
|
||||
import { ConfirmModal } from "../components/shared/ConfirmModal.tsx";
|
||||
import { PageShell } from "../components/layout/PageShell.tsx";
|
||||
import { PageError } from "../components/layout/PageError.tsx";
|
||||
import { ErrorCard } from "../components/shared/ErrorCard.tsx";
|
||||
|
||||
type State =
|
||||
| { status: "loading" }
|
||||
| { status: "error"; error: string }
|
||||
| {
|
||||
status: "loaded";
|
||||
profileUser: PublicUser;
|
||||
created: PagedList<Playlist>;
|
||||
followed: PagedList<Playlist>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Renders `/users/:username/playlists`, for anyone. It lists the playlists the
|
||||
* user made (the private ones only to them) and the public ones they follow,
|
||||
* from `GET /api/users/:username/playlists` and `…/followed-playlists`, a page
|
||||
* at a time, and the socket keeps both lists live. The user can make and
|
||||
* delete playlists here. Going back to the page restores both lists and the
|
||||
* scroll position from sessionStorage.
|
||||
*/
|
||||
export function UserPlaylists(): React.JSX.Element {
|
||||
const { username } = useParams();
|
||||
const { user: me, authFetch } = useAuth();
|
||||
|
||||
useDocumentTitle(username ?? null);
|
||||
const { lastPlaylistEvent } = useWS();
|
||||
|
||||
const { cached: cachedCreated, saveState: saveCreated } = useFeedCache<
|
||||
Playlist
|
||||
>(
|
||||
`feed:user-playlists:${username ?? ""}`,
|
||||
hydratePlaylist,
|
||||
);
|
||||
const { cached: cachedFollowed, saveState: saveFollowed } = useFeedCache<
|
||||
Playlist
|
||||
>(
|
||||
`feed:user-followed-playlists:${username ?? ""}`,
|
||||
hydratePlaylist,
|
||||
);
|
||||
|
||||
const [state, setState] = useState<State>({ status: "loading" });
|
||||
const [prevUsername, setPrevUsername] = useState(username);
|
||||
if (prevUsername !== username) {
|
||||
setPrevUsername(username);
|
||||
setState({ status: "loading" });
|
||||
}
|
||||
const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null);
|
||||
|
||||
const profileUserId = state.status === "loaded" ? state.profileUser.id : null;
|
||||
const isOwnProfile = me?.id === profileUserId;
|
||||
|
||||
type SetList = (
|
||||
fn: (list: PagedList<Playlist>) => PagedList<Playlist>,
|
||||
) => void;
|
||||
const setCreatedList = useCallback<SetList>(
|
||||
(fn) =>
|
||||
setState((s) =>
|
||||
s.status !== "loaded" ? s : { ...s, created: fn(s.created) }
|
||||
),
|
||||
[],
|
||||
);
|
||||
const setFollowedList = useCallback<SetList>(
|
||||
(fn) =>
|
||||
setState((s) =>
|
||||
s.status !== "loaded" ? s : { ...s, followed: fn(s.followed) }
|
||||
),
|
||||
[],
|
||||
);
|
||||
const setCreated = useCallback(
|
||||
(fn: (prev: Playlist[]) => Playlist[]) => setCreatedList(mapItems(fn)),
|
||||
[setCreatedList],
|
||||
);
|
||||
const setFollowed = useCallback(
|
||||
(fn: (prev: Playlist[]) => Playlist[]) => setFollowedList(mapItems(fn)),
|
||||
[setFollowedList],
|
||||
);
|
||||
const createdItems = state.status === "loaded" ? state.created.items : [];
|
||||
const lastPlaylistItem = lastPlaylistEvent?.type === "updated"
|
||||
? (lastPlaylistEvent.playlist ?? null)
|
||||
: null;
|
||||
// Before usePlaylistListSync: it saves a playlist's place before the sync
|
||||
// takes it out, and puts it back there when it turns public again.
|
||||
usePositionAwareSync(
|
||||
createdItems,
|
||||
setCreated,
|
||||
lastPlaylistItem,
|
||||
(p) => p.isPublic && p.userId === profileUserId,
|
||||
);
|
||||
usePlaylistListSync(setCreated, {
|
||||
isOwner: isOwnProfile,
|
||||
ownerId: profileUserId ?? undefined,
|
||||
});
|
||||
|
||||
usePlaylistListSync(setFollowed, { noNewEntries: true });
|
||||
|
||||
const createdUrl = `${API_URL}/api/users/${username}/playlists`;
|
||||
const followedUrl = `${API_URL}/api/users/${username}/followed-playlists`;
|
||||
const fetchPage = (url: string) => (page: number) =>
|
||||
authFetch(pageUrl(url, page))
|
||||
.then((res) => readPage(res, deserializePlaylist));
|
||||
|
||||
useEffect(() => {
|
||||
if (!username) return;
|
||||
const controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
const firstPageOf = (url: string) =>
|
||||
authFetch(pageUrl(url, 1), { signal })
|
||||
.then((res) => readFirstPage(res, deserializePlaylist));
|
||||
|
||||
// Back on the page, the lists come from the cache and only the user is
|
||||
// fetched again.
|
||||
const cached = cachedCreated && cachedFollowed;
|
||||
Promise.all([
|
||||
fetchPublicUser(username, signal),
|
||||
cached ? restoredList(cachedCreated) : firstPageOf(createdUrl),
|
||||
cached ? restoredList(cachedFollowed) : firstPageOf(followedUrl),
|
||||
])
|
||||
.then(([profileUser, created, followed]) =>
|
||||
setState({ status: "loaded", profileUser, created, followed })
|
||||
)
|
||||
.catch((err) => {
|
||||
if (signal.aborted) return;
|
||||
setState({ status: "error", error: friendlyFetchError(err) });
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [
|
||||
username,
|
||||
cachedCreated,
|
||||
cachedFollowed,
|
||||
authFetch,
|
||||
createdUrl,
|
||||
followedUrl,
|
||||
]);
|
||||
|
||||
const createdList = state.status === "loaded" ? state.created : null;
|
||||
const followedList = state.status === "loaded" ? state.followed : null;
|
||||
const createdSentinelRef = useInfiniteScroll(
|
||||
useLoadMore(createdList, setCreatedList, fetchPage(createdUrl)),
|
||||
canLoadMore(createdList),
|
||||
);
|
||||
const followedSentinelRef = useInfiniteScroll(
|
||||
useLoadMore(followedList, setFollowedList, fetchPage(followedUrl)),
|
||||
canLoadMore(followedList),
|
||||
);
|
||||
|
||||
useScrollSave(
|
||||
state.status === "loaded",
|
||||
useCallback((y) => {
|
||||
if (state.status !== "loaded") return;
|
||||
saveCreated(state.created, y);
|
||||
saveFollowed(state.followed, y);
|
||||
}, [state, saveCreated, saveFollowed]),
|
||||
);
|
||||
|
||||
useScrollRestore(cachedCreated?.scrollY, state.status === "loaded");
|
||||
|
||||
const [deleteError, setDeleteError] = useState<string | null>(null);
|
||||
|
||||
const handleDelete = async (playlistId: string) => {
|
||||
setDeleteError(null);
|
||||
try {
|
||||
const res = await authFetch(`${API_URL}/api/playlists/${playlistId}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
if (!res.ok) await expectOk(res); // throws the server's message
|
||||
} catch (err) {
|
||||
setDeleteError(friendlyFetchError(err));
|
||||
return;
|
||||
}
|
||||
setCreated((items) => items.filter((p) => p.id !== playlistId));
|
||||
};
|
||||
|
||||
if (state.status === "loading") {
|
||||
return (
|
||||
<PageShell>
|
||||
<p className="page-loading">
|
||||
<Trans>Loading…</Trans>
|
||||
</p>
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
|
||||
if (state.status === "error") {
|
||||
return (
|
||||
<PageError
|
||||
message={state.error}
|
||||
actions={
|
||||
<Link to={`/users/${username}`} className="btn-border">
|
||||
<Trans>← Back to profile</Trans>
|
||||
</Link>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const { profileUser, created, followed } = state;
|
||||
|
||||
return (
|
||||
<PageShell>
|
||||
<ProfileSubpageHeader
|
||||
username={username!}
|
||||
profileUser={profileUser}
|
||||
title={t`Playlists`}
|
||||
actions={isOwnProfile && (
|
||||
<NewPlaylistButton
|
||||
toggleClassName="btn-primary"
|
||||
onCreated={(p) => setCreated((items) => withFirst(items, p))}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
{deleteError && (
|
||||
<ErrorCard title={t`Could not delete`} message={deleteError} />
|
||||
)}
|
||||
|
||||
<ProfileSection
|
||||
title={
|
||||
<Trans>
|
||||
Created ({created.items.length}
|
||||
{created.hasMore ? "+" : ""})
|
||||
</Trans>
|
||||
}
|
||||
>
|
||||
{created.items.length === 0
|
||||
? (
|
||||
<p className="empty-state">
|
||||
<Trans>No playlists yet.</Trans>
|
||||
</p>
|
||||
)
|
||||
: (
|
||||
<>
|
||||
<PlaylistCardList
|
||||
playlists={created.items}
|
||||
onDelete={isOwnProfile
|
||||
? (p) => setConfirmDeleteId(p.id)
|
||||
: undefined}
|
||||
/>
|
||||
<FeedFooter
|
||||
hasMore={created.hasMore}
|
||||
loadingMore={created.loadingMore}
|
||||
sentinelRef={createdSentinelRef}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</ProfileSection>
|
||||
|
||||
<ProfileSection
|
||||
title={
|
||||
<Trans>
|
||||
Followed ({followed.items.length}
|
||||
{followed.hasMore ? "+" : ""})
|
||||
</Trans>
|
||||
}
|
||||
>
|
||||
{followed.items.length === 0
|
||||
? (
|
||||
<p className="empty-state">
|
||||
<Trans>No followed playlists yet.</Trans>
|
||||
</p>
|
||||
)
|
||||
: (
|
||||
<>
|
||||
<PlaylistCardList playlists={followed.items} />
|
||||
<FeedFooter
|
||||
hasMore={followed.hasMore}
|
||||
loadingMore={followed.loadingMore}
|
||||
sentinelRef={followedSentinelRef}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</ProfileSection>
|
||||
|
||||
{confirmDeleteId && (
|
||||
<ConfirmModal
|
||||
message={t`Delete this playlist? This cannot be undone.`}
|
||||
confirmLabel={t`Delete playlist`}
|
||||
onConfirm={() => {
|
||||
handleDelete(confirmDeleteId);
|
||||
setConfirmDeleteId(null);
|
||||
}}
|
||||
onCancel={() => setConfirmDeleteId(null)}
|
||||
/>
|
||||
)}
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
@@ -1,139 +1,103 @@
|
||||
/**
|
||||
* Renders a user's profile page, which is also where the signed-in user edits
|
||||
* their own profile and settings.
|
||||
* their own profile.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { useCallback } from "react";
|
||||
import { useNavigate, useParams } from "react-router";
|
||||
import { useLocation, useNavigate, useParams } from "react-router";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
|
||||
import { API_URL } from "../config/api.ts";
|
||||
import type { Invitee, PublicUser } from "../../shared/user.ts";
|
||||
import type { Invitee } from "../../shared/user.ts";
|
||||
import type { Wire } from "../../shared/api.ts";
|
||||
import {
|
||||
deserializeInvitee,
|
||||
deserializePlaylist,
|
||||
deserializePublicUser,
|
||||
} from "../utils/shared/deserialize.ts";
|
||||
FOLLOW_VIEWS,
|
||||
type FollowView,
|
||||
PROFILE_TABS,
|
||||
type ProfileTab,
|
||||
userPath,
|
||||
} from "../../shared/paths.ts";
|
||||
import { deserializeInvitee } from "../utils/shared/deserialize.ts";
|
||||
import { dataOr } from "../utils/shared/api.ts";
|
||||
import { can } from "../utils/auth/permissions.ts";
|
||||
import {
|
||||
type PagedList,
|
||||
pageUrl,
|
||||
readFirstPage,
|
||||
readPage,
|
||||
} from "../utils/feed/pagedList.ts";
|
||||
import { useLoadMore } from "../hooks/feed/usePagedList.ts";
|
||||
import { useAuth } from "../hooks/auth/useAuth.ts";
|
||||
import { useDocumentTitle } from "../hooks/shared/useDocumentTitle.ts";
|
||||
import { useFetchState } from "../hooks/shared/useFetchState.ts";
|
||||
import { useTabParam } from "../hooks/shared/useTabParam.ts";
|
||||
import { useCanonicalPath } from "../hooks/shared/useCanonicalPath.ts";
|
||||
import { useProfile } from "../hooks/profile/useProfile.ts";
|
||||
import { PageShell } from "../components/layout/PageShell.tsx";
|
||||
import { PageError } from "../components/layout/PageError.tsx";
|
||||
import { TabBar } from "../components/shared/TabBar.tsx";
|
||||
import { ProfileHeader } from "../components/profile/ProfileHeader.tsx";
|
||||
import { ProfileDescription } from "../components/profile/ProfileDescription.tsx";
|
||||
import { ProfileOverviewTab } from "../components/profile/ProfileOverviewTab.tsx";
|
||||
import { ProfileDumpsTab } from "../components/profile/ProfileDumpsTab.tsx";
|
||||
import { ProfilePlaylistsTab } from "../components/profile/ProfilePlaylistsTab.tsx";
|
||||
import {
|
||||
type ProfileFollowed,
|
||||
ProfileFollowedTab,
|
||||
} from "../components/profile/ProfileFollowedTab.tsx";
|
||||
import { ProfileFollowTab } from "../components/profile/ProfileFollowTab.tsx";
|
||||
import { ProfileInviteesTab } from "../components/profile/ProfileInviteesTab.tsx";
|
||||
import { ProfileSettingsTab } from "../components/profile/ProfileSettingsTab.tsx";
|
||||
import { ProfileManageTab } from "../components/profile/ProfileManageTab.tsx";
|
||||
import { NotFound } from "./NotFound.tsx";
|
||||
|
||||
/** The overview, the bare `/@name`, which no path segment names. */
|
||||
const OVERVIEW = "overview";
|
||||
type Tab = ProfileTab | typeof OVERVIEW;
|
||||
const TABS: readonly Tab[] = [OVERVIEW, ...PROFILE_TABS];
|
||||
|
||||
/**
|
||||
* The profile's tabs, the `:profileTab` of `/users/:username/~/:profileTab`.
|
||||
* "dumps" is the default, at `/users/:username`.
|
||||
*/
|
||||
const PROFILE_TABS = [
|
||||
"dumps",
|
||||
"playlists",
|
||||
"followed",
|
||||
"invitees",
|
||||
"settings",
|
||||
"manage",
|
||||
] as const;
|
||||
type ProfileTab = (typeof PROFILE_TABS)[number];
|
||||
|
||||
/**
|
||||
* Renders `/users/:username` and `/users/:username/~/:profileTab`, for anyone.
|
||||
* `useProfile` loads the user with their dumps, upvotes and playlists; the
|
||||
* "followed" and "invitees" tabs load theirs when first opened, and keep it
|
||||
* while other tabs show. Each tab is a component of `components/profile/`. On
|
||||
* their own profile, users edit their avatar, description and email, create
|
||||
* invites, and get a "settings" tab. The "manage" tab shows another user's
|
||||
* role to those who hold `user:manage`, and one's own categories to those who
|
||||
* hold `category:manage`.
|
||||
* Renders `/@:username` and its tabs, `/@:username/:tab`, and the follow
|
||||
* tab's view `/@:username/follow/playlists`, for anyone. `useProfile` loads
|
||||
* the user, by a former name or another case too, and the URL then takes the
|
||||
* current one; each tab loads its own lists, by the user's id, when shown.
|
||||
* On their own profile, users edit their avatar, description and email, and
|
||||
* create invites. The "manage" tab, another user's role and name, is for those
|
||||
* who hold `user:manage`. A tab or view the profile hasn't is `NotFound`.
|
||||
*/
|
||||
export function UserPublicProfile(): React.JSX.Element {
|
||||
const { username } = useParams();
|
||||
const { handle = "" } = useParams();
|
||||
const username = handle.slice(1);
|
||||
const { pathname } = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const { user: me, logout } = useAuth();
|
||||
const { state, isOwnProfile, setUser, setPlaylists, upvotedCardClassName } =
|
||||
useProfile(username);
|
||||
const { state, isOwnProfile, setUser } = useProfile(username);
|
||||
const user = state.status === "loaded" ? state.data : null;
|
||||
|
||||
useDocumentTitle(
|
||||
state.status === "loaded"
|
||||
? state.user.username
|
||||
: state.status === "error"
|
||||
? null
|
||||
: undefined,
|
||||
user ? user.username : state.status === "error" ? null : undefined,
|
||||
);
|
||||
|
||||
// The base is the path's own first segment, however it spells the name.
|
||||
const base = `/${pathname.split("/")[1]}`;
|
||||
const [tab, setTab] = useTabParam<Tab>(base, TABS, OVERVIEW);
|
||||
useCanonicalPath(
|
||||
user && `${userPath(user.username)}${pathname.slice(base.length)}`,
|
||||
);
|
||||
|
||||
// Only the follow tab has a view, one segment further.
|
||||
const extra = pathname.slice(base.length).split("/").filter(Boolean).slice(1);
|
||||
const view: FollowView | null = extra.length === 0
|
||||
? "users"
|
||||
: tab === "follow" && extra.length === 1 && extra[0] !== FOLLOW_VIEWS[0] &&
|
||||
(FOLLOW_VIEWS as readonly string[]).includes(extra[0])
|
||||
? extra[0] as FollowView
|
||||
: null;
|
||||
|
||||
const canManageUsers = can(me, "user:manage");
|
||||
const canManageCategories = can(me, "category:manage");
|
||||
// "manage" holds tools for another user on their profile, and site-wide
|
||||
// tools on one's own.
|
||||
const showManageTab = isOwnProfile ? canManageCategories : canManageUsers;
|
||||
const availableTabs: ProfileTab[] = PROFILE_TABS.filter((t) => {
|
||||
if (t === "settings") return isOwnProfile;
|
||||
if (t === "manage") return showManageTab;
|
||||
return true;
|
||||
});
|
||||
// A tab not available here, as while the profile loads, shows "dumps".
|
||||
const [tab, setTab] = useTabParam<ProfileTab>(availableTabs, "dumps");
|
||||
const showManageTab = !isOwnProfile && canManageUsers;
|
||||
|
||||
const loaded = state.status === "loaded";
|
||||
const followedUsersUrl = `${API_URL}/api/users/${username}/followed-users`;
|
||||
const followed = useFetchState<ProfileFollowed>(
|
||||
username,
|
||||
(signal) =>
|
||||
Promise.all([
|
||||
fetch(pageUrl(followedUsersUrl, 1), { signal })
|
||||
.then((res) => readFirstPage(res, deserializePublicUser)),
|
||||
fetch(
|
||||
pageUrl(`${API_URL}/api/users/${username}/followed-playlists`, 1),
|
||||
{ signal },
|
||||
).then((res) => readFirstPage(res, deserializePlaylist)),
|
||||
]).then(([users, playlists]) => ({ users, playlists })),
|
||||
{ enabled: loaded && tab === "followed" },
|
||||
);
|
||||
const invitees = useFetchState<Invitee[]>(
|
||||
username,
|
||||
user?.id,
|
||||
(signal) =>
|
||||
fetch(`${API_URL}/api/users/${username}/invitees`, { signal })
|
||||
fetch(`${API_URL}/api/users/${user!.id}/invitees`, { signal })
|
||||
.then((res) => dataOr<Wire<Invitee>[]>(res, []))
|
||||
.then((entries) => entries.map(deserializeInvitee)),
|
||||
{ enabled: loaded && tab === "invitees" },
|
||||
{ enabled: tab === "invitees" },
|
||||
);
|
||||
|
||||
const setFollowed = followed.setData;
|
||||
const loadMoreFollowedUsers = useLoadMore(
|
||||
followed.state.status === "loaded" ? followed.state.data.users : null,
|
||||
useCallback(
|
||||
(fn: (users: PagedList<PublicUser>) => PagedList<PublicUser>) =>
|
||||
setFollowed((d) => ({ ...d, users: fn(d.users) })),
|
||||
[setFollowed],
|
||||
),
|
||||
(page) =>
|
||||
fetch(pageUrl(followedUsersUrl, page))
|
||||
.then((res) => readPage(res, deserializePublicUser)),
|
||||
);
|
||||
if (!tab || !view || (tab === "manage" && user && !showManageTab)) {
|
||||
return <NotFound />;
|
||||
}
|
||||
|
||||
if (state.status === "loading") {
|
||||
return (
|
||||
@@ -169,32 +133,31 @@ export function UserPublicProfile(): React.JSX.Element {
|
||||
);
|
||||
}
|
||||
|
||||
const { user, dumps, votes, playlists } = state;
|
||||
const profileUser = state.data;
|
||||
|
||||
return (
|
||||
<PageShell>
|
||||
<ProfileHeader
|
||||
user={user}
|
||||
user={profileUser}
|
||||
isOwnProfile={isOwnProfile}
|
||||
onUserChange={(u) => setUser(() => u)}
|
||||
/>
|
||||
<ProfileDescription
|
||||
description={user.description}
|
||||
description={profileUser.description}
|
||||
isOwnProfile={isOwnProfile}
|
||||
onSaved={(description) => setUser((u) => ({ ...u, description }))}
|
||||
/>
|
||||
|
||||
<TabBar
|
||||
tabs={[
|
||||
{ key: "dumps", label: <Trans>Dumps</Trans> },
|
||||
{ key: "playlists", label: <Trans>Playlists</Trans> },
|
||||
{ key: "followed", label: <Trans>Followed</Trans> },
|
||||
{ key: "invitees", label: <Trans>Invitees</Trans> },
|
||||
...(isOwnProfile
|
||||
? [{ key: "settings" as const, label: <Trans>Settings</Trans> }]
|
||||
: []),
|
||||
{ key: OVERVIEW as Tab, label: <Trans>Overview</Trans> },
|
||||
{ key: "dumps" as Tab, label: <Trans>Dumps</Trans> },
|
||||
{ key: "upvoted" as Tab, label: <Trans>Upvoted</Trans> },
|
||||
{ key: "playlists" as Tab, label: <Trans>Playlists</Trans> },
|
||||
{ key: "follow" as Tab, label: <Trans>Followed</Trans> },
|
||||
{ key: "invitees" as Tab, label: <Trans>Invitees</Trans> },
|
||||
...(showManageTab
|
||||
? [{ key: "manage" as const, label: <Trans>Manage</Trans> }]
|
||||
? [{ key: "manage" as Tab, label: <Trans>Manage</Trans> }]
|
||||
: []),
|
||||
]}
|
||||
activeTab={tab}
|
||||
@@ -203,41 +166,28 @@ export function UserPublicProfile(): React.JSX.Element {
|
||||
innerClassName="profile-tabs"
|
||||
/>
|
||||
|
||||
{tab === "dumps" && (
|
||||
{tab === OVERVIEW && (
|
||||
<ProfileOverviewTab user={profileUser} isOwnProfile={isOwnProfile} />
|
||||
)}
|
||||
{(tab === "dumps" || tab === "upvoted") && (
|
||||
<ProfileDumpsTab
|
||||
username={user.username}
|
||||
dumps={dumps}
|
||||
votes={votes}
|
||||
key={tab}
|
||||
user={profileUser}
|
||||
list={tab}
|
||||
isOwnProfile={isOwnProfile}
|
||||
upvotedCardClassName={upvotedCardClassName}
|
||||
/>
|
||||
)}
|
||||
{tab === "playlists" && (
|
||||
<ProfilePlaylistsTab
|
||||
username={user.username}
|
||||
playlists={playlists}
|
||||
isOwnProfile={isOwnProfile}
|
||||
setPlaylists={setPlaylists}
|
||||
/>
|
||||
)}
|
||||
{tab === "followed" && (
|
||||
<ProfileFollowedTab
|
||||
username={user.username}
|
||||
state={followed.state}
|
||||
onLoadMoreUsers={loadMoreFollowedUsers}
|
||||
/>
|
||||
<ProfilePlaylistsTab user={profileUser} isOwnProfile={isOwnProfile} />
|
||||
)}
|
||||
{tab === "follow" && <ProfileFollowTab user={profileUser} view={view} />}
|
||||
{tab === "invitees" && (
|
||||
<ProfileInviteesTab userId={user.id} state={invitees.state} />
|
||||
<ProfileInviteesTab userId={profileUser.id} state={invitees.state} />
|
||||
)}
|
||||
{tab === "settings" && isOwnProfile && <ProfileSettingsTab />}
|
||||
{tab === "manage" && (
|
||||
<ProfileManageTab
|
||||
user={user}
|
||||
isOwnProfile={isOwnProfile}
|
||||
canManageUsers={canManageUsers}
|
||||
canManageCategories={canManageCategories}
|
||||
onRoleSaved={(role) => setUser((u) => ({ ...u, role }))}
|
||||
user={profileUser}
|
||||
onUserSaved={(u) => setUser(() => u)}
|
||||
/>
|
||||
)}
|
||||
</PageShell>
|
||||
|
||||
@@ -82,7 +82,7 @@ export function UserRegister(): React.JSX.Element {
|
||||
|
||||
const onSubmit = form.submit(async ({ username, email, password }) => {
|
||||
const data = await expectOk<Wire<AuthResponse>>(
|
||||
await fetch(`${API_URL}/api/users/register`, {
|
||||
await fetch(`${API_URL}/api/users`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
/**
|
||||
* Renders the page listing all the dumps a user upvoted, which the "upvoted"
|
||||
* section of their profile links to.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { Link, useParams } from "react-router";
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
|
||||
import { useDocumentTitle } from "../hooks/shared/useDocumentTitle.ts";
|
||||
import { useDumpListSync } from "../hooks/dump/useDumpListSync.ts";
|
||||
import { useUpvotedList } from "../hooks/dump/useUpvotedList.ts";
|
||||
import { useUserDumpFeed } from "../hooks/dump/useUserDumpFeed.ts";
|
||||
import { DumpCardList } from "../components/dump/DumpCardList.tsx";
|
||||
import { FeedFooter } from "../components/feed/FeedFooter.tsx";
|
||||
import { ProfileSubpageHeader } from "../components/profile/ProfileSubpageHeader.tsx";
|
||||
import { PageShell } from "../components/layout/PageShell.tsx";
|
||||
import { PageError } from "../components/layout/PageError.tsx";
|
||||
|
||||
/**
|
||||
* Renders `/users/:username/upvoted`, for anyone. The dumps come from
|
||||
* `useUserDumpFeed`, and `useUpvotedList` keeps them in step with the user's
|
||||
* votes.
|
||||
*/
|
||||
export function UserUpvoted(): React.JSX.Element {
|
||||
const { username } = useParams();
|
||||
|
||||
useDocumentTitle(username ?? null);
|
||||
|
||||
const { state, setItems, sentinelRef } = useUserDumpFeed(
|
||||
username,
|
||||
"votes",
|
||||
`feed:user-upvoted-full:${username ?? ""}`,
|
||||
);
|
||||
|
||||
useDumpListSync(setItems);
|
||||
const { cardClassName } = useUpvotedList({
|
||||
profileUserId: state.status === "loaded" ? state.profileUser.id : null,
|
||||
setItems,
|
||||
});
|
||||
|
||||
if (state.status === "loading") {
|
||||
return (
|
||||
<PageShell>
|
||||
<p className="page-loading">
|
||||
<Trans>Loading…</Trans>
|
||||
</p>
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
|
||||
if (state.status === "error") {
|
||||
return (
|
||||
<PageError
|
||||
message={state.error}
|
||||
actions={
|
||||
<Link to={`/users/${username}`} className="btn-border">
|
||||
<Trans>← Back to profile</Trans>
|
||||
</Link>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const { profileUser, dumps: { items: votes, hasMore, loadingMore } } = state;
|
||||
|
||||
return (
|
||||
<PageShell>
|
||||
<ProfileSubpageHeader
|
||||
username={username!}
|
||||
profileUser={profileUser}
|
||||
title={t`Upvoted`}
|
||||
/>
|
||||
{votes.length === 0
|
||||
? (
|
||||
<p className="empty-state">
|
||||
<Trans>Nothing here yet.</Trans>
|
||||
</p>
|
||||
)
|
||||
: (
|
||||
<>
|
||||
<DumpCardList dumps={votes} cardClassName={cardClassName} />
|
||||
<FeedFooter
|
||||
hasMore={hasMore}
|
||||
loadingMore={loadingMore}
|
||||
sentinelRef={sentinelRef}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user