Files
gerbeur/src/components/dump/create/DumpCreateModal.tsx
khannurien 80f3292c8f
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 55s
Build and Deploy Static Documentation Site / build-and-push (push) Successful in 22s
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>
2026-09-29 20:08:00 +00:00

812 lines
29 KiB
TypeScript

/**
* The modal that posts a dump from a link or a file, then offers to add it to
* the poster's playlists. Every "new dump" button opens it.
*
* @module
*/
import { useCallback, useEffect, useRef, useState } from "react";
import { Link } from "react-router";
import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { API_URL } from "../../../config/api.ts";
import {
DUMP_MAX_FILE_SIZE_BYTES,
VALIDATION,
} from "../../../../shared/validation.ts";
import type {
CreateUrlDumpRequest,
Dump,
DumpUrlMatch,
LinkPreview,
RichContent,
} from "../../../../shared/dump.ts";
import type { PlaylistMembership } from "../../../../shared/playlist.ts";
import type { Wire } from "../../../../shared/api.ts";
import {
deserializeDump,
deserializeDumpUrlMatch,
deserializePlaylistMembership,
} from "../../../utils/shared/deserialize.ts";
import { useAuth } from "../../../hooks/auth/useAuth.ts";
import { useWS } from "../../../hooks/ws/useWS.ts";
import { dumpUrl, normalizeUrl } from "../../../utils/shared/urls.ts";
import {
formatBytes,
titleFromFileName,
} from "../../../utils/shared/format.ts";
import {
clearDumpDraft,
type DumpDraft,
EMPTY_DUMP_DRAFT,
loadDumpDraft,
saveDumpDraft,
} from "../../../utils/dump/draft.ts";
import { RichContentCard } from "../RichContentCard.tsx";
import { Modal } from "../../shared/Modal.tsx";
import type { TextEditorHandle } from "../../editor/TextEditor.tsx";
import { CategorySelect } from "../../category/CategorySelect.tsx";
import { PlaylistMembershipPanel } from "../../playlist/PlaylistMembershipPanel.tsx";
import { expectOk } from "../../../utils/shared/api.ts";
import { FileField } from "../../form/FileField.tsx";
import { FormError } from "../../form/FormError.tsx";
import { FormProvider } from "react-hook-form";
import { RichTextField } from "../../form/RichTextField.tsx";
import { SubmitButton } from "../../form/SubmitButton.tsx";
import { useApiForm } from "../../../hooks/form/useApiForm.ts";
import { VisibilityToggle } from "../../form/SegmentedField.tsx";
import { DuplicateNotice } from "./DuplicateNotice.tsx";
import { LocalFilePreview } from "./LocalFilePreview.tsx";
import { type Step, StepIndicator } from "./StepIndicator.tsx";
import { TitleField } from "./TitleField.tsx";
/** Kept stable so `DuplicateNotice` doesn't re-render on every keystroke. */
const NO_DUPLICATES: DumpUrlMatch[] = [];
/** `reached` is false when the server couldn't fetch the page at all. */
type UrlPreview =
| { status: "idle" }
| { status: "loading" }
| { status: "done"; reached: boolean; richContent: RichContent | null };
interface CreateValues {
url: string;
file: File | null;
title: string;
comment: string;
isPublic: boolean;
}
/**
* Checks whether the pointer is coarse. On a touch device, focusing a field
* raises a keyboard that covers most of the modal before the user has seen it.
*/
function prefersNoAutoFocus(): boolean {
return globalThis.matchMedia?.("(pointer: coarse)").matches ?? false;
}
/**
* Passed to {@link DumpCreateModal} by the button that opens it. The parent
* unmounts the modal on `onClose`, which the modal also calls after a
* confirmed dismissal.
*/
export interface DumpCreateModalProps {
onClose: () => void;
/**
* A link shared from Android's share sheet, which `AppHeader` passes on from
* `Index`. It replaces any saved draft.
*/
initialUrl?: string;
}
/**
* Renders the dump creation modal. The first panel takes a link, previewed
* through `GET /api/preview` and checked against `GET /api/dumps/by-url`, or a
* file. The second takes the "why", categories and visibility, and posts to
* `POST /api/dumps`. The third adds the new dump to playlists. The new dump is
* handed to `WSContext`'s `injectDump` so the feeds show it at once. Everything
* but the file is saved as a draft (`utils/dump/draft.ts`) until it is posted.
*/
export function DumpCreateModal(
{ onClose, initialUrl = "" }: DumpCreateModalProps,
): React.JSX.Element {
const { authFetch, authUpload } = useAuth();
const { injectDump } = useWS();
const [step, setStep] = useState<Step>("what");
const [direction, setDirection] = useState<"forward" | "back">("forward");
const [createdDump, setCreatedDump] = useState<Dump | null>(null);
const goToStep = (next: Step, dir: "forward" | "back") => {
setDirection(dir);
setStep(next);
};
// Arriving with a URL (the Android share sheet) is a request to post *that*,
// so an abandoned draft is dropped whole rather than half-merged: pairing
// someone's old "why" with a link they just shared from another app would be
// more confusing than starting them clean.
const [restoredDraft] = useState<DumpDraft | null>(() =>
initialUrl ? null : loadDumpDraft()
);
const draft = restoredDraft ?? EMPTY_DUMP_DRAFT;
const [draftNoticeVisible, setDraftNoticeVisible] = useState(!!restoredDraft);
const [titleEditing, setTitleEditing] = useState(false);
const [titleFromUser, setTitleFromUser] = useState(draft.titleFromUser);
const [urlFetchState, setUrlFetchState] = useState<UrlPreview>({
status: "idle",
});
// Tagged with the URL they describe, so a result never lingers over the next
// link during the debounce, and clearing them needs no effect.
const [duplicateState, setDuplicateState] = useState<
{ url: string; matches: DumpUrlMatch[] }
>({ url: "", matches: [] });
// Undefined when no upload runs, null once the body is sent and the server
// is still processing it, else the fraction sent.
const [uploadProgress, setUploadProgress] = useState<number | null>();
const [confirmClose, setConfirmClose] = useState(false);
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const commentEditorRef = useRef<TextEditorHandle | null>(null);
const form = useApiForm<CreateValues>({
defaultValues: {
url: initialUrl || draft.url,
file: null,
title: draft.title,
comment: draft.comment,
isPublic: draft.isPublic,
},
});
const { register, setValue, watch, clearErrors, reset } = form;
const submitting = form.formState.isSubmitting;
const url = watch("url");
const file = watch("file");
const title = watch("title");
const comment = watch("comment");
const isPublic = watch("isPublic");
// The dump's kind is whatever the user actually provided, so there is no mode
// to pick: attaching a file makes it a file dump, typing a link makes it a
// link dump, and clearing either offers both again.
const mode: "url" | "file" = file ? "file" : "url";
const [selectedCategoryIds, setSelectedCategoryIds] = useState<Set<string>>(
() => new Set(draft.categoryIds),
);
const toggleCategory = (id: string) =>
setSelectedCategoryIds((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
const [memberships, setMemberships] = useState<PlaylistMembership[]>([]);
const [playlistsLoading, setPlaylistsLoading] = useState(false);
const selectFile = useCallback((f: File | null) => {
setValue("file", f);
if (f) {
setValue("title", titleFromFileName(f.name));
setTitleFromUser(false);
}
setTitleEditing(false);
}, [setValue]);
// The effects below key on this rather than on the raw input, so that
// "example.com" and the "https://example.com" onBlur rewrites it to don't
// fetch the preview twice.
let canonicalUrl: string | null;
try {
const u = new URL(normalizeUrl(url));
canonicalUrl = (u.protocol === "http:" || u.protocol === "https:")
? u.toString()
: null;
} catch {
canonicalUrl = null;
}
// Deriving "idle" here spares the effect below from resetting the state when
// the link is cleared.
const urlPreview: UrlPreview = canonicalUrl
? urlFetchState
: { status: "idle" };
const duplicates = canonicalUrl && duplicateState.url === canonicalUrl
? duplicateState.matches
: NO_DUPLICATES;
// The preview and the duplicate lookup concern the same link, so they share
// one debounce.
useEffect(() => {
if (debounceRef.current) clearTimeout(debounceRef.current);
if (!canonicalUrl) return;
// Deferred: the set-state-in-effect lint rule forbids setting state
// synchronously in an effect.
queueMicrotask(() => setUrlFetchState({ status: "loading" }));
// A preview can take seconds, since the server fetches the page. An answer
// for a link that has since changed must not show, or set the title.
const controller = new AbortController();
const { signal } = controller;
debounceRef.current = setTimeout(() => {
const encoded = encodeURIComponent(canonicalUrl);
authFetch(`${API_URL}/api/preview?url=${encoded}`, { signal })
.then((res) => res.json())
.then((body) => {
if (signal.aborted) return;
const data = body.success ? body.data as LinkPreview : undefined;
setUrlFetchState({
status: "done",
reached: data?.reached ?? false,
richContent: data?.richContent ?? null,
});
})
.catch(() => {
if (signal.aborted) return;
setUrlFetchState({
status: "done",
reached: false,
richContent: null,
});
});
// Signed in, so that the poster's own private dumps count as duplicates.
authFetch(`${API_URL}/api/dumps/by-url?url=${encoded}`, { signal })
.then((res) => res.json())
.then((body) => {
if (signal.aborted) return;
setDuplicateState({
url: canonicalUrl,
matches: body.success
? (body.data as Wire<DumpUrlMatch>[]).map(deserializeDumpUrlMatch)
: [],
});
})
.catch(() => {
if (!signal.aborted) {
setDuplicateState({ url: canonicalUrl, matches: [] });
}
});
}, 600);
return () => {
if (debounceRef.current) clearTimeout(debounceRef.current);
controller.abort();
};
}, [canonicalUrl, authFetch]);
// Until the poster edits it, the title follows the preview. An empty
// suggestion is written too, or the previous link's title would stay.
const suggestedTitle = urlPreview.status === "done"
? urlPreview.richContent?.title ?? ""
: "";
useEffect(() => {
if (mode !== "url" || titleFromUser) return;
setValue("title", suggestedTitle);
}, [mode, titleFromUser, suggestedTitle, setValue]);
// Once posted, the draft is cleared and must not be written back.
useEffect(() => {
if (step === "playlist") return;
saveDumpDraft({
url,
title,
titleFromUser,
comment,
isPublic,
categoryIds: [...selectedCategoryIds],
});
}, [
step,
url,
title,
titleFromUser,
comment,
isPublic,
selectedCategoryIds,
]);
const discardDraft = () => {
clearDumpDraft();
reset({
url: "",
file: null,
title: "",
comment: "",
isPublic: true,
});
setSelectedCategoryIds(new Set());
setTitleFromUser(false);
setTitleEditing(false);
setDraftNoticeVisible(false);
};
// Not on touch, where the keyboard would cover the categories.
useEffect(() => {
if (step !== "details" || prefersNoAutoFocus()) return;
commentEditorRef.current?.focus();
}, [step]);
// Only the attached file is lost on close, since the draft keeps the rest,
// so only a file makes the modal ask first.
const handleBeforeClose = useCallback(() => {
if (step === "playlist" || submitting || !file || confirmClose) return true;
setConfirmClose(true);
return false;
}, [step, submitting, file, confirmClose]);
// Cancel asks first too, like Escape and the ✕.
const requestClose = () => {
if (handleBeforeClose()) onClose();
};
// A paste anywhere in the page takes a file or a link.
useEffect(() => {
const handler = (e: ClipboardEvent) => {
// Fields handle their own paste: the "why" editor uploads a pasted image
// as an attachment, and the link field has its own handler below.
const tag = (e.target as HTMLElement).tagName;
if (tag === "INPUT" || tag === "TEXTAREA") return;
const pastedFile = e.clipboardData?.files[0];
if (pastedFile) {
setValue("url", "");
selectFile(pastedFile);
clearErrors("root");
return;
}
const text = e.clipboardData?.getData("text") ?? "";
try {
const u = new URL(normalizeUrl(text));
if (u.protocol === "http:" || u.protocol === "https:") {
selectFile(null);
setValue("url", u.toString());
clearErrors("root");
}
} catch { /* not a URL */ }
};
globalThis.addEventListener("paste", handler);
return () => globalThis.removeEventListener("paste", handler);
}, [selectFile, setValue, clearErrors]);
const [dragging, setDragging] = useState(false);
// The whole modal takes a drop, since the drop zone is hidden while a link
// is typed.
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
setDragging(false);
if (submitting) return;
const dropped = e.dataTransfer.files[0];
if (dropped) {
setValue("url", "");
selectFile(dropped);
clearErrors("root");
}
};
const onSubmit = form.submit(async (
{ url, file, title, comment, isPublic },
) => {
const isPrivate = !isPublic;
let res: Response;
if (!file) {
const normalizedUrl = normalizeUrl(url);
if (!normalizedUrl) throw new Error(t`URL is required.`);
setValue("url", normalizedUrl);
const body: CreateUrlDumpRequest = {
url: normalizedUrl,
// Left to the server unless typed, so it takes the page's title
// itself.
title: titleFromUser && title.trim() ? title.trim() : undefined,
comment: comment.trim() || undefined,
isPrivate,
categoryIds: [...selectedCategoryIds],
};
res = await authFetch(`${API_URL}/api/dumps`, {
method: "POST",
body: JSON.stringify(body),
});
} else {
if (!title.trim()) throw new Error(t`Title is required.`);
if (file.size > DUMP_MAX_FILE_SIZE_BYTES) {
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);
if (comment.trim()) formData.append("comment", comment.trim());
if (title.trim()) formData.append("title", title.trim());
formData.append("isPrivate", String(isPrivate));
formData.append("categoryIds", JSON.stringify([...selectedCategoryIds]));
setUploadProgress(0);
try {
res = await authUpload(
`${API_URL}/api/dumps`,
formData,
setUploadProgress,
);
} finally {
setUploadProgress(undefined);
}
}
const dump = deserializeDump(await expectOk<Wire<Dump>>(res));
clearDumpDraft();
injectDump(dump);
setCreatedDump(dump);
goToStep("playlist", "forward");
setPlaylistsLoading(true);
authFetch(`${API_URL}/api/playlists/by-dump/${dump.id}/memberships`)
.then((r) => r.json())
.then((body) => {
if (body.success) {
setMemberships(
(body.data as Wire<PlaylistMembership>[]).map(
deserializePlaylistMembership,
),
);
}
})
.catch(() => {})
.finally(() => setPlaylistsLoading(false));
});
const toggleMembership = async (membership: PlaylistMembership) => {
if (!createdDump) return;
const { playlist, hasDump } = membership;
// Not optimistic: the box changes only once the server agrees.
try {
const res = await authFetch(
`${API_URL}/api/playlists/${playlist.id}/dumps/${createdDump.id}`,
{ method: hasDump ? "DELETE" : "POST" },
);
if (!res.ok) return;
} catch {
return;
}
setMemberships((prev) =>
prev.map((m) =>
m.playlist.id === playlist.id ? { ...m, hasDump: !hasDump } : m
)
);
};
const canProceed = !!file || !!canonicalUrl;
const recap = title.trim() || file?.name || normalizeUrl(url);
const uploadPercentLabel = t`Uploading ${
Math.round((uploadProgress ?? 0) * 100)
}%`;
// Enter on the first panel moves on to the second rather than posting.
const onFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
if (step === "what") {
e.preventDefault();
if (canProceed) goToStep("details", "forward");
return;
}
void onSubmit(e);
};
return (
<Modal
title={step === "playlist" ? t`Add to playlist` : t`New dump`}
onClose={onClose}
onBeforeClose={handleBeforeClose}
wide
>
<div
className={`dump-create${dragging ? " dump-create--drag" : ""}`}
onDragOver={(e) => {
e.preventDefault();
if (!submitting && step !== "playlist") setDragging(true);
}}
onDragLeave={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {
setDragging(false);
}
}}
onDrop={handleDrop}
>
{confirmClose && (
<div className="dump-create-confirm" role="alert">
<p>
<Trans>
Close without posting? The attached file won't be kept —
everything you typed will.
</Trans>
</p>
<div className="dump-create-confirm-actions">
<button type="button" onClick={() => setConfirmClose(false)}>
<Trans>Keep editing</Trans>
</button>
<button type="button" className="btn-danger" onClick={onClose}>
<Trans>Close anyway</Trans>
</button>
</div>
</div>
)}
{draftNoticeVisible && step === "what" && (
<div className="dump-create-draft" role="status">
<span>
<Trans>Picked up where you left off.</Trans>
</span>
<button
type="button"
className="dump-create-draft-discard"
onClick={discardDraft}
>
<Trans>Start fresh</Trans>
</button>
</div>
)}
<StepIndicator current={step} />
{step === "playlist"
? (
<div className="dump-panel dump-panel--forward">
{createdDump && (
<p className="dump-create-success">
<Trans>Dumped!</Trans>{" "}
<Link to={dumpUrl(createdDump)} onClick={onClose}>
<Trans>View dump →</Trans>
</Link>
</p>
)}
<PlaylistMembershipPanel
dumpId={createdDump?.id ?? ""}
memberships={memberships}
loading={playlistsLoading}
onToggle={toggleMembership}
onPlaylistCreated={(membership) =>
setMemberships((prev) => [membership, ...prev])}
/>
<div className="form-actions">
<div className="form-actions-right">
<button
type="button"
className="btn-primary"
onClick={onClose}
>
<Trans>Done</Trans>
</button>
</div>
</div>
</div>
)
: (
<FormProvider {...form}>
<form onSubmit={onFormSubmit} className="form">
<FormError title={t`Failed to post`} />
{/* Keyed so a new panel remounts and plays its slide-in. */}
<div
key={step}
className={`dump-panel dump-panel--${direction}`}
>
{step === "what"
? (
<>
{mode === "url" && (
<>
<div className="form-field">
<label className="form-label" htmlFor="dc-url">
<Trans>Link</Trans>
</label>
<input
id="dc-url"
type="url"
{...register("url")}
onBlur={(e) =>
setValue("url", normalizeUrl(e.target.value))}
onPaste={(e) => {
const pastedFile = e.clipboardData.files[0];
if (pastedFile) {
e.preventDefault();
setValue("url", "");
selectFile(pastedFile);
clearErrors("root");
}
}}
disabled={submitting}
placeholder={t`Paste a link…`}
autoFocus={!prefersNoAutoFocus()}
/>
</div>
{urlPreview.status === "loading" && (
<p className="preview-loading">
<Trans>Fetching preview…</Trans>
</p>
)}
{urlPreview.status === "done" && (
<>
{urlPreview.richContent && (
<RichContentCard
richContent={urlPreview.richContent}
/>
)}
{!urlPreview.reached && (
<p className="preview-note">
<Trans>
Couldn't load a preview for this link —
check it, or post it as-is and refresh the
preview later.
</Trans>
</p>
)}
</>
)}
{duplicates.length > 0 && (
<DuplicateNotice
matches={duplicates}
onNavigate={onClose}
/>
)}
{urlPreview.status === "done" && (
<TitleField
registration={register("title")}
editing={titleEditing}
onEdit={() => {
setTitleEditing(true);
setTitleFromUser(true);
}}
onReset={titleFromUser && suggestedTitle
? () => {
setTitleFromUser(false);
setTitleEditing(false);
setValue("title", suggestedTitle);
}
: undefined}
disabled={submitting}
/>
)}
</>
)}
{
/* An empty panel offers both a link and a file. */
}
{!(mode === "url" && url.trim()) && (
<FileField<CreateValues>
name="file"
onValueChange={selectFile}
disabled={submitting}
hint={t`Drop a file here, or paste one`}
maxBytes={DUMP_MAX_FILE_SIZE_BYTES}
/>
)}
{file && (
<>
<LocalFilePreview file={file} />
<TitleField
registration={register("title")}
editing={titleEditing}
onEdit={() => {
setTitleEditing(true);
setTitleFromUser(true);
}}
disabled={submitting}
/>
</>
)}
</>
)
: (
<>
{
/* The link or file is a panel back, so recall it. */
}
<p className="dump-panel-recap" title={recap}>
<span aria-hidden="true">
{mode === "url" ? "🔗" : "📎"}
</span>{" "}
{recap}
</p>
{uploadProgress !== undefined && (
<div
className={`dump-upload-progress${
typeof uploadProgress === "number"
? ""
: " dump-upload-progress--indeterminate"
}`}
role="progressbar"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={typeof uploadProgress === "number"
? Math.round(uploadProgress * 100)
: undefined}
>
<div
className="dump-upload-progress-fill"
style={typeof uploadProgress === "number"
? { width: `${uploadProgress * 100}%` }
: undefined}
/>
</div>
)}
<RichTextField<CreateValues>
name="comment"
label={t`Why?`}
placeholder={t`What makes it worth it?`}
rows={3}
maxLength={VALIDATION.DUMP_COMMENT_MAX}
disabled={submitting}
editorRef={commentEditorRef}
/>
<CategorySelect
selected={selectedCategoryIds}
onToggle={toggleCategory}
disabled={submitting}
/>
<VisibilityToggle<CreateValues>
name="isPublic"
label={t`Who can see it`}
disabled={submitting}
/>
</>
)}
</div>
<div className="form-actions">
{step === "details" && (
<button
type="button"
className="form-cancel"
onClick={() => goToStep("what", "back")}
disabled={submitting}
>
<Trans>← Back</Trans>
</button>
)}
<div className="form-actions-right">
{step === "what" && (
<button
type="button"
className="form-cancel"
onClick={requestClose}
>
<Trans>Cancel</Trans>
</button>
)}
<SubmitButton
disabled={step === "what" && !canProceed}
pendingLabel={mode === "url"
? <Trans>Posting…</Trans>
: typeof uploadProgress === "number"
? uploadPercentLabel
: <Trans>Uploading…</Trans>}
>
{step === "what"
? <Trans>Next →</Trans>
: <Trans>Dump it</Trans>}
</SubmitButton>
</div>
</div>
</form>
</FormProvider>
)}
</div>
</Modal>
);
}