v3: fix the frontend's findings, and the backend pieces they needed — each by a rule the code now keeps everywhere. Votes and likes go through one useOptimisticToggles in WSProvider: clicks on one item before any ack share one baseline, which a failure or the timeout restores (a second click used to cancel the first one's rollback), only the last ack's count is applied, a votes_update or comment_likes_update waits while this tab has toggles in flight, and a welcome reconciles them against the server's sets (a vote cast offline left its count one too high). lastLikeEvent, which nothing read, is gone. Follows are refetched when the new follows_changed message, sent to the follower's sockets on every follow write, says another tab changed them; a failed load keeps the Follow buttons disabled and is retried 10 s later instead of leaving them disabled for good (success: false) or enabled over empty sets (network error); follow and unfollow resolve to whether they worked, and the button says when they didn't. CategoriesProvider follows the same rule, so a network error no longer turns every category URL into a 404. Every list is kept by one rule: useDumpListSync and usePlaylistListSync never add an item, and usePositionAwareSync remembers the place of any item that leaves a list, whatever took it out, and puts it back when its next event shows it again; with dump_created now setting lastDumpEvent, a dump going private and back returns to its place on another user's profile, which never happened before, and an updated playlist missing from a list is no longer prepended. useFeedCache keys every cache by viewer (the profile pages restored the owner's private dumps to whoever went back) and reads it again when its key changes (another profile in the same page showed the previous one's list). Every response of a list's first page or next pages goes through expectOk (Index, UserPlaylists, useUserDumpFeed and Notifications read body.data unchecked).
Smaller fixes: the redirects from / and /<slug> keep the navigation state, so the index hides the dump DumpEdit just deleted; Index's mainFetchDone ref, which blocked nothing, is gone; DumpEdit refuses someone else's dump up front, as the API does; the Dump page takes a handed-over dump once and clears it from the history entry, so a reload fetches; a newly upvoted dump is fetched with the viewer's token; the notifications page sends read-all once per notification; the profile's followed and invitees tabs finish loading when left mid-fetch; UserListPopover no longer closes when its own list scrolls; the vote and like counts open their lists for visitors too (a disabled button swallowed the click; they are aria-disabled now); the removal of a playlist's dump forgets it (an edit brought it back), a failed removal puts it back where it was, an undo waits for the removal in flight, and a refused undo says so; PlaylistCreateForm tells whether the dump made it into the new playlist; the cover preview's object URL is revoked; the muted icon has its cross; the bell no longer stays rung after two notifications within 700 ms; a stale invite check can't overwrite a newer one; a stored theme or color scheme is checked; the default feed tab is one store every reader follows, across tabs; the file fields enforce the size they state, derived from DUMP_MAX_FILE_SIZE_BYTES; formatBytes, friendlyFetchError and ImagePicker are translated (Intl names the units), and ImagePicker ignores keys while uploading; visited dumps and playlists keep a week of visits and are parsed once; a chime is claimed under a Web Lock, so two tabs can't both play it; a date in the future reads as "now". Dead code goes: PageShell's centerSlot, overLimit, the exports of isSafeHex and hueFromString, the comment tree's token prop and ChatContext's isChatOpen and closeChat. The French catalogue has the 11 new messages. 214 backend and 632 frontend tests pass; tsc, deno lint, ESLint and doc:lint are clean. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -44,8 +44,6 @@ export interface CommentNodeProps {
|
||||
depth: number;
|
||||
dumpId: string;
|
||||
currentUser: SelfUser | null;
|
||||
/** Only checked for being set before a delete. */
|
||||
token: string | null;
|
||||
onCommentCreated: (comment: Comment) => void;
|
||||
onCommentDeleted: (commentId: string) => void;
|
||||
onCommentUpdated: (comment: Comment) => void;
|
||||
@@ -63,7 +61,6 @@ export function CommentNode({
|
||||
depth,
|
||||
dumpId,
|
||||
currentUser,
|
||||
token,
|
||||
onCommentCreated,
|
||||
onCommentDeleted,
|
||||
onCommentUpdated,
|
||||
@@ -96,7 +93,6 @@ export function CommentNode({
|
||||
}
|
||||
|
||||
async function handleDelete() {
|
||||
if (!token) return;
|
||||
setDeleteFailed(false);
|
||||
const res = await authFetch(`${API_URL}/api/comments/${comment.id}`, {
|
||||
method: "DELETE",
|
||||
@@ -157,7 +153,6 @@ export function CommentNode({
|
||||
depth={depth + 1}
|
||||
dumpId={dumpId}
|
||||
currentUser={currentUser}
|
||||
token={token}
|
||||
onCommentCreated={onCommentCreated}
|
||||
onCommentDeleted={onCommentDeleted}
|
||||
onCommentUpdated={onCommentUpdated}
|
||||
@@ -312,7 +307,6 @@ export function CommentNode({
|
||||
depth={depth + 1}
|
||||
dumpId={dumpId}
|
||||
currentUser={currentUser}
|
||||
token={token}
|
||||
onCommentCreated={onCommentCreated}
|
||||
onCommentDeleted={onCommentDeleted}
|
||||
onCommentUpdated={onCommentUpdated}
|
||||
|
||||
@@ -32,7 +32,6 @@ export interface CommentThreadProps {
|
||||
*/
|
||||
comments: Comment[];
|
||||
currentUser: SelfUser | null;
|
||||
token: string | null;
|
||||
onCommentCreated: (comment: Comment) => void;
|
||||
onCommentDeleted: (commentId: string) => void;
|
||||
onCommentUpdated: (comment: Comment) => void;
|
||||
@@ -59,7 +58,6 @@ export function CommentThread({
|
||||
dumpId,
|
||||
comments,
|
||||
currentUser,
|
||||
token,
|
||||
onCommentCreated,
|
||||
onCommentDeleted,
|
||||
onCommentUpdated,
|
||||
@@ -117,7 +115,6 @@ export function CommentThread({
|
||||
depth={0}
|
||||
dumpId={dumpId}
|
||||
currentUser={currentUser}
|
||||
token={token}
|
||||
onCommentCreated={onCommentCreated}
|
||||
onCommentDeleted={onCommentDeleted}
|
||||
onCommentUpdated={onCommentUpdated}
|
||||
|
||||
@@ -32,7 +32,10 @@ import {
|
||||
import { useAuth } from "../../../hooks/auth/useAuth.ts";
|
||||
import { useWS } from "../../../hooks/ws/useWS.ts";
|
||||
import { dumpUrl, normalizeUrl } from "../../../utils/shared/urls.ts";
|
||||
import { titleFromFileName } from "../../../utils/shared/format.ts";
|
||||
import {
|
||||
formatBytes,
|
||||
titleFromFileName,
|
||||
} from "../../../utils/shared/format.ts";
|
||||
import {
|
||||
clearDumpDraft,
|
||||
type DumpDraft,
|
||||
@@ -413,7 +416,8 @@ export function DumpCreateModal(
|
||||
} else {
|
||||
if (!title.trim()) throw new Error(t`Title is required.`);
|
||||
if (file.size > DUMP_MAX_FILE_SIZE_BYTES) {
|
||||
throw new Error(t`File too large (max 50 MB).`);
|
||||
const max = formatBytes(DUMP_MAX_FILE_SIZE_BYTES);
|
||||
throw new Error(t`File too large (max ${max}).`);
|
||||
}
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
@@ -683,6 +687,7 @@ export function DumpCreateModal(
|
||||
onValueChange={selectFile}
|
||||
disabled={submitting}
|
||||
hint={t`Drop a file here, or paste one`}
|
||||
maxBytes={DUMP_MAX_FILE_SIZE_BYTES}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -54,8 +54,8 @@ async function readPage(res: Response): Promise<PaginatedData<Wire<Dump>>> {
|
||||
type FollowedSection = "users" | "playlists";
|
||||
|
||||
/**
|
||||
* Passed to {@link FollowedFeed} by `Index`, with the vote state and deleted
|
||||
* dumps of `WSContext`. Unlike the other tabs, it loads its own dumps.
|
||||
* Passed to {@link FollowedFeed} by `Index`, with the vote state of
|
||||
* `WSContext`. Unlike the other tabs, it loads its own dumps.
|
||||
*/
|
||||
export interface FollowedFeedProps {
|
||||
/** Scopes both sections to a category. */
|
||||
@@ -66,7 +66,6 @@ export interface FollowedFeedProps {
|
||||
user: SelfUser;
|
||||
castVote: (id: string, shownCount?: number) => void;
|
||||
removeVote: (id: string, shownCount?: number) => void;
|
||||
deletedDumpIds: Set<string>;
|
||||
}
|
||||
|
||||
interface FollowedSubFeedProps {
|
||||
@@ -76,7 +75,6 @@ interface FollowedSubFeedProps {
|
||||
user: SelfUser;
|
||||
castVote: (id: string, shownCount?: number) => void;
|
||||
removeVote: (id: string, shownCount?: number) => void;
|
||||
deletedDumpIds: Set<string>;
|
||||
emptyMessage: string;
|
||||
onLoadMore: () => void;
|
||||
}
|
||||
@@ -89,7 +87,6 @@ function FollowedSubFeed({
|
||||
user,
|
||||
castVote,
|
||||
removeVote,
|
||||
deletedDumpIds,
|
||||
emptyMessage,
|
||||
onLoadMore,
|
||||
}: FollowedSubFeedProps) {
|
||||
@@ -108,16 +105,14 @@ function FollowedSubFeed({
|
||||
return <ErrorCard title={t`Failed to load`} message={state.error} />;
|
||||
}
|
||||
|
||||
const visible = state.dumps.filter((d) => !deletedDumpIds.has(d.id));
|
||||
|
||||
if (visible.length === 0) {
|
||||
if (state.dumps.length === 0) {
|
||||
return <p className="index-status">{emptyMessage}</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<ul className="dump-feed">
|
||||
{visible.map((dump) => (
|
||||
{state.dumps.map((dump) => (
|
||||
<DumpCard
|
||||
key={dump.id}
|
||||
dump={dump}
|
||||
@@ -158,7 +153,6 @@ export function FollowedFeed({
|
||||
user,
|
||||
castVote,
|
||||
removeVote,
|
||||
deletedDumpIds,
|
||||
}: FollowedFeedProps): React.JSX.Element {
|
||||
const { token } = useAuth();
|
||||
|
||||
@@ -168,13 +162,13 @@ export function FollowedFeed({
|
||||
: "";
|
||||
|
||||
const { cached: cachedUsers, saveState: saveUsers } = useFeedCache<Dump>(
|
||||
`feed:followed-users:${scope}:${user.id}`,
|
||||
`feed:followed-users:${scope}`,
|
||||
hydrateDump,
|
||||
);
|
||||
const { cached: cachedPlaylists, saveState: savePlaylists } = useFeedCache<
|
||||
Dump
|
||||
>(
|
||||
`feed:followed-playlists:${scope}:${user.id}`,
|
||||
`feed:followed-playlists:${scope}`,
|
||||
hydrateDump,
|
||||
);
|
||||
|
||||
@@ -268,22 +262,24 @@ export function FollowedFeed({
|
||||
}
|
||||
}, [token, usersState.status, playlistsState.status, catQuery]);
|
||||
|
||||
// Only the lists are kept here: `Index` saves and restores the page's scroll
|
||||
// for every tab, this one included.
|
||||
useScrollSave(
|
||||
usersState.status === "loaded",
|
||||
useCallback((y) => {
|
||||
useCallback(() => {
|
||||
if (usersState.status !== "loaded") return;
|
||||
saveUsers(usersState.dumps, usersState.page, usersState.hasMore, y);
|
||||
saveUsers(usersState.dumps, usersState.page, usersState.hasMore, 0);
|
||||
}, [usersState, saveUsers]),
|
||||
);
|
||||
useScrollSave(
|
||||
playlistsState.status === "loaded",
|
||||
useCallback((y) => {
|
||||
useCallback(() => {
|
||||
if (playlistsState.status !== "loaded") return;
|
||||
savePlaylists(
|
||||
playlistsState.dumps,
|
||||
playlistsState.page,
|
||||
playlistsState.hasMore,
|
||||
y,
|
||||
0,
|
||||
);
|
||||
}, [playlistsState, savePlaylists]),
|
||||
);
|
||||
@@ -376,7 +372,6 @@ export function FollowedFeed({
|
||||
user={user}
|
||||
castVote={castVote}
|
||||
removeVote={removeVote}
|
||||
deletedDumpIds={deletedDumpIds}
|
||||
emptyMessage={t`Follow some users to see their dumps here.`}
|
||||
onLoadMore={loadMoreUsers}
|
||||
/>
|
||||
@@ -390,7 +385,6 @@ export function FollowedFeed({
|
||||
user={user}
|
||||
castVote={castVote}
|
||||
removeVote={removeVote}
|
||||
deletedDumpIds={deletedDumpIds}
|
||||
emptyMessage={t`Follow some public playlists to see their dumps here.`}
|
||||
onLoadMore={loadMorePlaylists}
|
||||
/>
|
||||
|
||||
@@ -32,9 +32,10 @@ export interface FileDropZoneProps {
|
||||
/** Replaces the "Drop a file here" prompt. */
|
||||
hint?: string;
|
||||
/**
|
||||
* Shows "Max 50 MB", which is written out rather than read from
|
||||
* `DUMP_MAX_FILE_SIZE_BYTES`. The zone doesn't enforce it.
|
||||
* Stated under the prompt when `showLimit` is on. `FileField` refuses a
|
||||
* larger file.
|
||||
*/
|
||||
maxBytes?: number;
|
||||
showLimit?: boolean;
|
||||
}
|
||||
|
||||
@@ -48,9 +49,11 @@ export function FileDropZone({
|
||||
onChange,
|
||||
disabled,
|
||||
hint,
|
||||
maxBytes,
|
||||
showLimit = true,
|
||||
}: FileDropZoneProps): React.JSX.Element {
|
||||
const resolvedHint = hint ?? t`Drop a file here`;
|
||||
const limit = maxBytes === undefined ? null : formatBytes(maxBytes);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
|
||||
@@ -161,9 +164,9 @@ export function FileDropZone({
|
||||
or <span className="fdz__browse-link">browse files</span>
|
||||
</Trans>
|
||||
</p>
|
||||
{showLimit && (
|
||||
{showLimit && limit && (
|
||||
<p className="fdz__limit">
|
||||
<Trans>Max 50 MB</Trans>
|
||||
<Trans>Max {limit}</Trans>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -13,7 +13,9 @@ import {
|
||||
useFormContext,
|
||||
} from "react-hook-form";
|
||||
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { FileDropZone } from "./FileDropZone.tsx";
|
||||
import { formatBytes } from "../../utils/shared/format.ts";
|
||||
|
||||
/**
|
||||
* Passed to {@link FileField} by a dump form. The field it names holds the
|
||||
@@ -23,6 +25,9 @@ export interface FileFieldProps<T extends FieldValues> {
|
||||
name: Path<T>;
|
||||
label?: string;
|
||||
hint?: string;
|
||||
/** Refuses a larger file, as a field error, as soon as it is picked. */
|
||||
maxBytes?: number;
|
||||
/** States `maxBytes` in the drop zone. */
|
||||
showLimit?: boolean;
|
||||
disabled?: boolean;
|
||||
rules?: RegisterOptions<T, Path<T>>;
|
||||
@@ -41,13 +46,22 @@ export function FileField<T extends FieldValues>({
|
||||
name,
|
||||
label,
|
||||
hint,
|
||||
maxBytes,
|
||||
showLimit,
|
||||
disabled,
|
||||
rules,
|
||||
onValueChange,
|
||||
}: FileFieldProps<T>): React.JSX.Element {
|
||||
const { control, formState: { errors } } = useFormContext<T>();
|
||||
const { control, formState: { errors }, trigger } = useFormContext<T>();
|
||||
const error = errors[name];
|
||||
const fitsLimit = (file: File | null) => {
|
||||
if (maxBytes === undefined || !file || file.size <= maxBytes) return true;
|
||||
const limit = formatBytes(maxBytes);
|
||||
return t`That file is over ${limit}.`;
|
||||
};
|
||||
const validate = typeof rules?.validate === "function"
|
||||
? { custom: rules.validate, fitsLimit }
|
||||
: { ...rules?.validate, fitsLimit };
|
||||
|
||||
return (
|
||||
<div className="form-field">
|
||||
@@ -55,15 +69,18 @@ export function FileField<T extends FieldValues>({
|
||||
<Controller
|
||||
name={name}
|
||||
control={control}
|
||||
rules={rules}
|
||||
rules={{ ...rules, validate } as RegisterOptions<T, Path<T>>}
|
||||
render={({ field }) => (
|
||||
<FileDropZone
|
||||
file={(field.value as File | null) ?? null}
|
||||
onChange={(file) => {
|
||||
field.onChange(file);
|
||||
onValueChange?.(file);
|
||||
// Said at once, not on submit.
|
||||
trigger(name);
|
||||
}}
|
||||
hint={hint}
|
||||
maxBytes={maxBytes}
|
||||
showLimit={showLimit}
|
||||
disabled={disabled}
|
||||
/>
|
||||
|
||||
@@ -17,7 +17,11 @@ export function NotificationBell(): React.JSX.Element {
|
||||
const { unreadNotificationCount, lastNotification } = useWS();
|
||||
const navigate = useNavigate();
|
||||
const [ringing, setRinging] = useState(false);
|
||||
// The ring's timers outlive the effect that starts them: a notification
|
||||
// arriving mid-ring must not cancel its end, or the bell stays rung.
|
||||
const timersRef = useRef<ReturnType<typeof setTimeout>[]>([]);
|
||||
const animatingRef = useRef(false);
|
||||
useEffect(() => () => timersRef.current.forEach(clearTimeout), []);
|
||||
// Each page mounts its own header, so a notification already in context
|
||||
// must not ring the bell again after a navigation.
|
||||
const lastSeenIdRef = useRef<string | null>(lastNotification?.id ?? null);
|
||||
@@ -29,15 +33,13 @@ export function NotificationBell(): React.JSX.Element {
|
||||
|
||||
if (animatingRef.current) return;
|
||||
animatingRef.current = true;
|
||||
const tStart = setTimeout(() => setRinging(true), 0);
|
||||
const tEnd = setTimeout(() => {
|
||||
setRinging(false);
|
||||
animatingRef.current = false;
|
||||
}, 700);
|
||||
return () => {
|
||||
clearTimeout(tStart);
|
||||
clearTimeout(tEnd);
|
||||
};
|
||||
timersRef.current = [
|
||||
setTimeout(() => setRinging(true), 0),
|
||||
setTimeout(() => {
|
||||
setRinging(false);
|
||||
animatingRef.current = false;
|
||||
}, 700),
|
||||
];
|
||||
}, [lastNotification]);
|
||||
|
||||
return (
|
||||
|
||||
@@ -13,17 +13,15 @@ export interface PageShellProps {
|
||||
children: ReactNode;
|
||||
/** Centers the content, for a lone card such as a form or an error. */
|
||||
centered?: boolean;
|
||||
/** Passed on to `AppHeader`. */
|
||||
centerSlot?: ReactNode;
|
||||
}
|
||||
|
||||
/** Renders {@link AppHeader}, then the page's content as the `<main>`. */
|
||||
export function PageShell(
|
||||
{ children, centered = false, centerSlot }: PageShellProps,
|
||||
{ children, centered = false }: PageShellProps,
|
||||
): React.JSX.Element {
|
||||
return (
|
||||
<div className="page-shell">
|
||||
<AppHeader centerSlot={centerSlot} />
|
||||
<AppHeader />
|
||||
<main
|
||||
className={`page-content${centered ? " page-content--centered" : ""}`}
|
||||
>
|
||||
|
||||
@@ -33,7 +33,17 @@ export const IconVolume = (
|
||||
<svg viewBox="0 0 24 24" fill="currentColor">
|
||||
{muted
|
||||
? (
|
||||
<path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3A4.5 4.5 0 0 0 14 7.97v8.05c1.48-.73 2.5-2.25 2.5-4.02zM19 12c0 2.76-1.67 5.12-4 6.19V5.81C17.33 6.88 19 9.24 19 12z M19 12l2.5 2.5M21.5 12 19 14.5" />
|
||||
<>
|
||||
<path d="M3 9v6h4l5 5V4L7 9H3z" />
|
||||
{/* The cross is stroked: the icon's other shapes are fills. */}
|
||||
<path
|
||||
d="M16 9l5 6M21 9l-5 6"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
</>
|
||||
)
|
||||
: (
|
||||
<path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3A4.5 4.5 0 0 0 14 7.97v8.05c1.48-.73 2.5-2.25 2.5-4.02zM19 12c0 2.76-1.67 5.12-4 6.19V5.81C17.33 6.88 19 9.24 19 12z" />
|
||||
|
||||
@@ -33,7 +33,8 @@ import { VisibilityToggle } from "../form/SegmentedField.tsx";
|
||||
export interface PlaylistCreateFormProps {
|
||||
/** Added to the new playlist, which the submit button says. */
|
||||
dumpId?: string;
|
||||
onCreated: (playlist: Playlist) => void;
|
||||
/** `hasDump` tells whether `dumpId` made it into the new playlist. */
|
||||
onCreated: (playlist: Playlist, hasDump: boolean) => void;
|
||||
onCancel: () => void;
|
||||
className?: string;
|
||||
}
|
||||
@@ -46,7 +47,8 @@ interface Values {
|
||||
|
||||
/**
|
||||
* Renders the form that creates a playlist with `POST /api/playlists`, then
|
||||
* adds `dumpId` to it when given. A failure to add the dump goes unreported.
|
||||
* adds `dumpId` to it when given. The playlist exists even if adding the dump
|
||||
* fails, so `onCreated` runs either way and says which.
|
||||
*/
|
||||
export function PlaylistCreateForm(
|
||||
{ dumpId, onCreated, onCancel, className }: PlaylistCreateFormProps,
|
||||
@@ -72,13 +74,15 @@ export function PlaylistCreateForm(
|
||||
}),
|
||||
),
|
||||
);
|
||||
let hasDump = false;
|
||||
if (dumpId) {
|
||||
await authFetch(
|
||||
const res = await authFetch(
|
||||
`${API_URL}/api/playlists/${playlist.id}/dumps/${dumpId}`,
|
||||
{ method: "POST" },
|
||||
);
|
||||
).catch(() => null);
|
||||
hasDump = !!res?.ok;
|
||||
}
|
||||
onCreated(playlist);
|
||||
onCreated(playlist, hasDump);
|
||||
});
|
||||
|
||||
return (
|
||||
|
||||
@@ -91,8 +91,8 @@ export function PlaylistMembershipPanel({
|
||||
<PlaylistCreateForm
|
||||
className="animate-in"
|
||||
dumpId={dumpId}
|
||||
onCreated={(playlist) => {
|
||||
onPlaylistCreated({ playlist, hasDump: true });
|
||||
onCreated={(playlist, hasDump) => {
|
||||
onPlaylistCreated({ playlist, hasDump });
|
||||
setShowNewForm(false);
|
||||
}}
|
||||
onCancel={() => setShowNewForm(false)}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
|
||||
import { useRef } from "react";
|
||||
import { t } from "@lingui/core/macro";
|
||||
|
||||
/**
|
||||
* Passed to {@link ImagePicker} by an edit page, which uploads the file and
|
||||
@@ -43,6 +44,9 @@ export function ImagePicker({
|
||||
}: ImagePickerProps): React.JSX.Element {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const sizeStyle = { width: size, height: size, borderRadius };
|
||||
const pick = () => {
|
||||
if (!uploading) inputRef.current?.click();
|
||||
};
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
@@ -55,12 +59,16 @@ export function ImagePicker({
|
||||
<div
|
||||
className={className ? `img-picker ${className}` : "img-picker"}
|
||||
style={sizeStyle}
|
||||
onClick={() => !uploading && inputRef.current?.click()}
|
||||
title={src ? "Change image" : "Add image"}
|
||||
onClick={pick}
|
||||
title={src ? t`Change image` : t`Add image`}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-disabled={uploading}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") inputRef.current?.click();
|
||||
if (e.key !== "Enter" && e.key !== " ") return;
|
||||
// Or Space would also scroll the page.
|
||||
e.preventDefault();
|
||||
pick();
|
||||
}}
|
||||
>
|
||||
{src
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
/**
|
||||
* Renders the Follow buttons of a user's profile and of a playlist's page.
|
||||
* Both go through `FollowContext`, which follows at once and rolls back when
|
||||
* the server refuses.
|
||||
* the request fails; the button then says so beside it.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { useState } from "react";
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
import { useAuth } from "../../hooks/auth/useAuth.ts";
|
||||
@@ -35,24 +36,33 @@ export function FollowUserButton(
|
||||
): React.JSX.Element | null {
|
||||
const { user } = useAuth();
|
||||
const { followedUserIds, followUser, unfollowUser, isLoaded } = useFollows();
|
||||
const [failed, setFailed] = useState(false);
|
||||
|
||||
if (!user || user.id === targetUserId) return null;
|
||||
|
||||
const isFollowing = followedUserIds.has(targetUserId);
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`follow-btn${isFollowing ? " follow-btn--following" : ""}`}
|
||||
disabled={!isLoaded}
|
||||
onClick={() =>
|
||||
isFollowing ? unfollowUser(targetUserId) : followUser(targetUserId)}
|
||||
aria-label={isFollowing
|
||||
? t`Unfollow ${targetUsername}`
|
||||
: t`Follow ${targetUsername}`}
|
||||
>
|
||||
{isFollowing ? <Trans>Following</Trans> : <Trans>Follow</Trans>}
|
||||
</button>
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className={`follow-btn${isFollowing ? " follow-btn--following" : ""}`}
|
||||
disabled={!isLoaded}
|
||||
onClick={async () => {
|
||||
setFailed(false);
|
||||
const ok = await (isFollowing
|
||||
? unfollowUser(targetUserId)
|
||||
: followUser(targetUserId));
|
||||
setFailed(!ok);
|
||||
}}
|
||||
aria-label={isFollowing
|
||||
? t`Unfollow ${targetUsername}`
|
||||
: t`Follow ${targetUsername}`}
|
||||
>
|
||||
{isFollowing ? <Trans>Following</Trans> : <Trans>Follow</Trans>}
|
||||
</button>
|
||||
{failed && <FollowError />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -68,23 +78,38 @@ export function FollowPlaylistButton(
|
||||
const { user } = useAuth();
|
||||
const { followedPlaylistIds, followPlaylist, unfollowPlaylist, isLoaded } =
|
||||
useFollows();
|
||||
const [failed, setFailed] = useState(false);
|
||||
|
||||
if (!user || !isPublic) return null;
|
||||
|
||||
const isFollowing = followedPlaylistIds.has(targetPlaylistId);
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`follow-btn${isFollowing ? " follow-btn--following" : ""}`}
|
||||
disabled={!isLoaded}
|
||||
onClick={() =>
|
||||
isFollowing
|
||||
? unfollowPlaylist(targetPlaylistId)
|
||||
: followPlaylist(targetPlaylistId)}
|
||||
aria-label={isFollowing ? t`Unfollow playlist` : t`Follow playlist`}
|
||||
>
|
||||
{isFollowing ? <Trans>Following</Trans> : <Trans>Follow</Trans>}
|
||||
</button>
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className={`follow-btn${isFollowing ? " follow-btn--following" : ""}`}
|
||||
disabled={!isLoaded}
|
||||
onClick={async () => {
|
||||
setFailed(false);
|
||||
const ok = await (isFollowing
|
||||
? unfollowPlaylist(targetPlaylistId)
|
||||
: followPlaylist(targetPlaylistId));
|
||||
setFailed(!ok);
|
||||
}}
|
||||
aria-label={isFollowing ? t`Unfollow playlist` : t`Follow playlist`}
|
||||
>
|
||||
{isFollowing ? <Trans>Following</Trans> : <Trans>Follow</Trans>}
|
||||
</button>
|
||||
{failed && <FollowError />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function FollowError(): React.JSX.Element {
|
||||
return (
|
||||
<span className="follow-error" role="alert">
|
||||
<Trans>Couldn't update. Try again.</Trans>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -44,9 +44,13 @@ export function LikeButton(
|
||||
className={`comment-action-btn${
|
||||
liked ? " comment-action-btn--liked" : ""
|
||||
}`}
|
||||
onClick={() =>
|
||||
liked ? onUnlike(commentId, count) : onLike(commentId, count)}
|
||||
disabled={disabled}
|
||||
// Not `disabled`, as for VoteButton: its count opens the likers.
|
||||
onClick={() => {
|
||||
if (disabled) return;
|
||||
if (liked) onUnlike(commentId, count);
|
||||
else onLike(commentId, count);
|
||||
}}
|
||||
aria-disabled={disabled}
|
||||
aria-label={liked ? t`Remove like` : t`Like`}
|
||||
title={disabled ? t`Log in to like` : undefined}
|
||||
>
|
||||
|
||||
@@ -24,7 +24,7 @@ import type { PublicUser } from "../../../shared/user.ts";
|
||||
*/
|
||||
export interface UserListPopoverProps {
|
||||
anchorRef: React.RefObject<HTMLElement | null>;
|
||||
/** Called on an outside click, on Escape, and on any scroll. */
|
||||
/** Called on an outside click, on Escape, and on a scroll outside it. */
|
||||
onClose: () => void;
|
||||
/**
|
||||
* A paginated endpoint answering `PaginatedData<PublicUser>`, without a query
|
||||
@@ -120,8 +120,12 @@ export function UserListPopover(
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") onClose();
|
||||
}
|
||||
// Captured, so a scroll inside any container closes it too.
|
||||
function onScroll() {
|
||||
// Captured, so a scroll inside any container closes it too, but not one
|
||||
// of its own list, which scrolls through a long list of users.
|
||||
function onScroll(e: Event) {
|
||||
if (e.target instanceof Node && popoverRef.current?.contains(e.target)) {
|
||||
return;
|
||||
}
|
||||
onClose();
|
||||
}
|
||||
document.addEventListener("mousedown", onMouseDown);
|
||||
|
||||
@@ -41,8 +41,14 @@ export function VoteButton(
|
||||
<button
|
||||
type="button"
|
||||
className={`vote-btn${voted ? " vote-btn--active" : ""}`}
|
||||
onClick={() => voted ? onRemove(dumpId, count) : onCast(dumpId, count)}
|
||||
disabled={disabled}
|
||||
// Not `disabled`: a disabled button swallows its count's clicks, and
|
||||
// visitors may open the list of voters too.
|
||||
onClick={() => {
|
||||
if (disabled) return;
|
||||
if (voted) onRemove(dumpId, count);
|
||||
else onCast(dumpId, count);
|
||||
}}
|
||||
aria-disabled={disabled}
|
||||
aria-label={voted ? t`Remove vote` : t`Upvote`}
|
||||
title={disabled ? t`Log in to vote` : undefined}
|
||||
>
|
||||
|
||||
Reference in New Issue
Block a user