Media: name files when saving, and rename them in the library (file and references)

Every upload and save (Upload, Frame at, Video thumbnails, a clip's
Save to library) has a prefilled Name box; the name is also the
readable part of the file's name, plus a short random ending. Fetch
preview names its picture after the page. Rename on the Media page
changes both, moving the file and its small copy and pointing every
record that names it at the new path in one transaction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Aidan Dona 2026-10-08 15:47:30 -05:00
parent 14a22ca44d
commit 687ba898f6
9 changed files with 475 additions and 74 deletions

View file

@ -134,14 +134,54 @@ export function mediaSize(item: MediaItem) {
/* ── Data ────────────────────────────────────────────────────── */
export function uploadImage(file: File, keepOriginal: boolean, folder?: string): Promise<MediaItem> {
/* `name` is the library's name for it and the readable part of its
file name (server/src/media.js); blank: the file's own name. */
export function uploadImage(file: File, keepOriginal: boolean, folder?: string, name?: string): Promise<MediaItem> {
const form = new FormData();
form.append("file", file);
if (name?.trim()) form.append("name", name.trim());
if (keepOriginal) form.append("keep_original", "1");
if (folder) form.append("folder", folder);
return upload("/admin/media", form).then((data) => data.media);
}
/* What a Name box starts with for a chosen file: its name without the
ending, separators read as spaces ("spring_retreat-1.jpg" →
"spring retreat 1"). */
export function nameOfFile(file: File): string {
return file.name.replace(/\.[^.]+$/, "").replace(/[_-]+/g, " ").trim();
}
/* A Name box, labeled, for anything about to be saved to the library. */
export function NameBox({
value,
onChange,
className = "",
label = "Name",
}: {
value: string;
onChange: (value: string) => void;
className?: string;
label?: string;
}) {
const id = useId();
return (
<div className={`flex min-w-0 items-center gap-2 ${className}`}>
<label htmlFor={id} className="shrink-0 text-sm text-muted">
{label}
</label>
<input
id={id}
type="text"
value={value}
maxLength={200}
onChange={(e) => onChange(e.target.value)}
className="min-w-0 flex-1 border border-muted/25 bg-surface px-2 py-1 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25"
/>
</div>
);
}
/* How long a search waits after the last keystroke. */
export const SEARCH_PAUSE_MS = 250;
/* The most the library route sends (MAX_LIST, server/src/routes/media.js). */
@ -204,36 +244,58 @@ export function UploadButton({
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [framing, setFraming] = useState<File | null>(null);
// Chosen (and framed) but not sent yet: each waits with a Name box,
// prefilled from its own name, until Upload is pressed.
const [pending, setPending] = useState<Array<{ file: File; name: string }>>([]);
// Captions are kept as they are, so there's no original to keep.
const captions = folder === "captions";
const clearInput = () => {
if (inputRef.current) inputRef.current.value = "";
};
// A single photo for a field with a shape is framed first; SVGs and
// GIFs (which would lose their animation) go as they are.
// GIFs (which would lose their animation) go as they are. Either
// way the names come next.
function choose(files: FileList | null) {
const one = files?.length === 1 ? files[0] : null;
if (crop && one && /^image\/(jpeg|png|webp)$/.test(one.type)) setFraming(one);
else send(files ? Array.from(files) : []);
else name(files ? Array.from(files) : []);
}
async function send(files: File[]) {
function name(files: File[]) {
setError(null);
setPending(files.map((file) => ({ file, name: nameOfFile(file) })));
clearInput();
}
function cancel() {
setPending([]);
clearInput();
}
async function send() {
const files = pending;
if (files.length === 0) return;
setBusy(true);
setError(null);
try {
// One at a time: each is up to 25 MB, and a failure should
// name the file it happened to.
for (const file of files) {
// name the file it happened to. What went stays gone from the
// list; what didn't stays, to try again.
for (const [index, { file, name }] of files.entries()) {
try {
onUploaded(await uploadImage(file, keepOriginal, folder));
onUploaded(await uploadImage(file, keepOriginal, folder, name));
} catch (err) {
const why = err instanceof ApiError ? err.message : "Upload failed.";
setError(files.length > 1 ? `${file.name}: ${why}` : why);
break;
setError(files.length > 1 ? `${name || file.name}: ${why}` : why);
setPending(files.slice(index));
return;
}
}
setPending([]);
} finally {
setBusy(false);
if (inputRef.current) inputRef.current.value = "";
}
}
@ -243,10 +305,10 @@ export function UploadButton({
<button
type="button"
className={button}
disabled={busy}
disabled={busy || pending.length > 0}
onClick={() => inputRef.current?.click()}
>
{busy ? "Uploading…" : label}
{label}
</button>
<input
ref={inputRef}
@ -269,6 +331,29 @@ export function UploadButton({
</label>
)}
</div>
{pending.length > 0 && (
<div className="mt-2 space-y-2 border border-muted/20 bg-surface p-3">
{pending.map((item, index) => (
<NameBox
key={`${item.file.name}-${index}`}
label={pending.length > 1 ? `Name ${index + 1}` : "Name"}
value={item.name}
onChange={(value) =>
setPending((list) => list.map((entry, i) => (i === index ? { ...entry, name: value } : entry)))
}
/>
))}
<p className="text-xs text-muted">Also its file name, eg. spring-retreat-group-3f9c1a.webp.</p>
<div className="flex flex-wrap gap-2">
<button type="button" className={button} disabled={busy} onClick={send}>
{busy ? "Uploading…" : pending.length > 1 ? `Upload ${pending.length}` : "Upload"}
</button>
<button type="button" className="px-2 py-1 text-sm text-muted hover:text-danger" disabled={busy} onClick={cancel}>
Cancel
</button>
</div>
</div>
)}
{error && <p className="mt-1 text-xs text-danger">{error}</p>}
{framing && crop && (
<CropDialog
@ -276,8 +361,8 @@ export function UploadButton({
crop={crop}
onDone={(file) => {
setFraming(null);
if (file) send([file]);
else if (inputRef.current) inputRef.current.value = "";
if (file) name([file]);
else clearInput();
}}
/>
)}
@ -658,18 +743,24 @@ export function startOf(url: string): number {
}
}
/* What a frame's Name box says until somebody types in it. */
export const frameName = (text: string) => `Video frame at ${text.trim() || "0:00"}`;
function FrameFromVideo({ url, className, onSaved }: { url: string; className: string; onSaved: (value: string) => void }) {
const [text, setText] = useState(() => clock(startOf(url)));
// null: follow the time ("Video frame at 1:23"); typed, it's kept.
const [typedName, setTypedName] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const timeId = useId();
const seconds = parseClock(text);
const name = typedName ?? frameName(text);
async function take() {
setBusy(true);
setError(null);
try {
const { media } = await post("/admin/video-frame", { url, seconds });
const { media } = await post("/admin/video-frame", { url, seconds, name });
onSaved(media.url);
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't take that frame.");
@ -686,6 +777,7 @@ function FrameFromVideo({ url, className, onSaved }: { url: string; className: s
<div className="w-24">
<input id={timeId} type="text" value={text} onChange={(e) => setText(e.target.value)} placeholder="eg. 1:23" className={className} />
</div>
<NameBox value={name} onChange={setTypedName} className="w-64" />
<button type="button" className={button} disabled={busy || seconds == null} onClick={take}>
{busy ? "Taking…" : "Use this frame"}
</button>

View file

@ -20,6 +20,7 @@ import { Link } from "react-router-dom";
import { ApiError, del, get, post } from "../../lib/api.ts";
import { clock, parseClock } from "../../lib/clock.ts";
import { accentText, BRAND } from '../../lib/color.ts'
import { NameBox } from "../../components/admin/MediaLibrary.tsx";
const MUTED = "var(--color-muted)";
const POLL_MS = 2000;
@ -71,6 +72,52 @@ const primary =
const input =
"border border-muted/25 bg-surface px-3 py-2 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25";
/* Save to library: a Name box first, prefilled with the video's title
(and a clip's span), which also names the file. `act` is the
page's, so a failure shows on the row like any other action. */
function SaveToLibrary({
id,
defaultName,
act,
}: {
id: number;
defaultName: string;
act: (fn: () => Promise<unknown>) => Promise<void>;
}) {
const [name, setName] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
if (name === null) {
return (
<button type="button" className={button} onClick={() => setName(defaultName)}>
Save to library
</button>
);
}
return (
<div className="flex w-full flex-wrap items-center gap-2">
<NameBox value={name} onChange={setName} className="min-w-64 flex-1" />
<button
type="button"
className={button}
disabled={busy || !name.trim()}
onClick={async () => {
setBusy(true);
await act(() => post(`/admin/clips/${id}/save`, { name }));
setBusy(false);
setName(null);
}}
>
{busy ? "Saving…" : "Save"}
</button>
<button type="button" className="text-sm text-muted hover:underline" disabled={busy} onClick={() => setName(null)}>
Cancel
</button>
</div>
);
}
/* Save to Drive: a folder under Media (Tools → Media → Files), then
the clip goes there as a Files entry. Opens on a folder named for
the clip's kind (Videos, Audio) when there is one. */
@ -477,9 +524,7 @@ export default function AdminClips() {
{/* The whole video, before (or without) cutting: it
stays here to cut from either way. */}
{s.status === "done" && s.has_file && !s.saved_url && (
<button type="button" className={button} onClick={() => act(() => post(`/admin/clips/${s.id}/save`, {}))}>
Save to library
</button>
<SaveToLibrary id={s.id} defaultName={s.title ?? "Video"} act={act} />
)}
{s.saved_url && (
<Link to="/admin/media" className="text-sm underline" style={{ color: accentText(BRAND) }}>
@ -553,9 +598,13 @@ export default function AdminClips() {
>
Download
</a>
<button type="button" className={button} onClick={() => act(() => post(`/admin/clips/${clip.id}/save`, {}))}>
Save to library
</button>
<SaveToLibrary
id={clip.id}
defaultName={`${sourceTitle(clip.source_id)}${
clip.params ? ` (${clock(clip.params.start)} to ${clock(clip.params.end)})` : ""
}`}
act={act}
/>
</>
)}
{clip.saved_url && (

View file

@ -17,7 +17,7 @@
a page (an image field stores the path, not a foreign key).
═══════════════════════════════════════════════════════════════ */
import { useEffect, useState } from "react";
import { useEffect, useState, type FormEvent } from "react";
import { Link } from "react-router-dom";
import { ApiError, del, get, patch, post } from "../../lib/api.ts";
@ -38,6 +38,7 @@ import {
FolderTabs,
formatBytes,
MediaGrid,
NameBox,
UPLOAD_HELP,
UploadButton,
useMediaLibrary,
@ -131,6 +132,73 @@ function DeleteControl({
);
}
/* Rename: the library's name and the file's own. Opening it asks what
uses the file first, since the server repoints those records at the
new address and anything outside the site (a sent newsletter, a
shared link) keeps the old one, which stops working. */
function RenameControl({ item, onRenamed }: { item: MediaItem; onRenamed: (item: MediaItem) => void }) {
const [name, setName] = useState<string | null>(null);
const [uses, setUses] = useState<Use[] | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
async function open() {
setName(item.original_name);
setError(null);
setUses(null);
try {
setUses((await get(`/admin/media/${item.id}/uses`, { ttl: 0 })).uses);
} catch {
setUses([]);
}
}
async function save(e: FormEvent) {
e.preventDefault();
if (!name?.trim()) return;
setBusy(true);
setError(null);
try {
const { media } = await patch(`/admin/media/${item.id}`, { name });
onRenamed(media);
setName(null);
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't rename that.");
} finally {
setBusy(false);
}
}
if (name === null) {
return (
<button type="button" onClick={open} className="text-xs text-link hover:underline">
Rename
</button>
);
}
const count = uses?.reduce((sum, use) => sum + use.count, 0) ?? 0;
return (
<form onSubmit={save} className="w-full space-y-2 bg-tint p-2 text-xs text-body">
<NameBox value={name} onChange={setName} />
<p className="text-muted">
{uses === null
? "Checking what uses it…"
: `Also renames the file${count > 0 ? `, and updates the ${count} record${count === 1 ? "" : "s"} using it` : ""}. Links to the old address outside the site (eg. a sent newsletter) will stop working.`}
</p>
<div className="flex gap-3">
<button type="submit" disabled={busy || !name.trim()} className="font-medium text-link hover:underline disabled:opacity-50">
{busy ? "Renaming…" : "Save name"}
</button>
<button type="button" onClick={() => setName(null)} className="text-muted hover:underline">
Cancel
</button>
</div>
{error && <p className="text-danger">{error}</p>}
</form>
);
}
function CopyPath({ url, label = "Copy path" }: { url: string; label?: string }) {
const [copied, setCopied] = useState(false);
return (
@ -573,6 +641,14 @@ export default function AdminMedia() {
>
Open
</a>
{roleCanWrite(user) && (
<RenameControl
item={item}
onRenamed={(renamed) =>
setItems((current) => (current ?? []).map((m) => (m.id === renamed.id ? renamed : m)))
}
/>
)}
{canDelete(user) && (
<div className="w-full">
<DeleteControl

View file

@ -16,7 +16,7 @@ import { Link } from "react-router-dom";
import { ApiError, post } from "../../lib/api.ts";
import { clock, parseClock } from "../../lib/clock.ts";
import { startOf, type MediaItem } from "../../components/admin/MediaLibrary.tsx";
import { frameName, startOf, type MediaItem } from "../../components/admin/MediaLibrary.tsx";
const MUTED = "var(--color-muted)";
@ -49,7 +49,10 @@ function Frame({ frame }: { frame: Taken }) {
</a>
<div className="space-y-3 p-4">
<div>
<p className="font-medium text-body">At {clock(frame.seconds)}</p>
<p className="font-medium text-body">{frame.media.original_name}</p>
<p className="text-xs" style={{ color: MUTED }}>
At {clock(frame.seconds)}
</p>
<p className="truncate text-xs" style={{ color: MUTED }} title={frame.url}>
{frame.url}
</p>
@ -78,10 +81,14 @@ export default function AdminVideoFrames() {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [frames, setFrames] = useState<Taken[]>([]);
// null: follow the time ("Video frame at 1:23"); typed, it's kept.
const [typedName, setTypedName] = useState<string | null>(null);
const urlId = useId();
const timeId = useId();
const nameId = useId();
const seconds = parseClock(time);
const name = typedName ?? frameName(time);
// A pasted link that carries its own time (t=83) sets the box.
function changeUrl(next: string) {
@ -97,7 +104,7 @@ export default function AdminVideoFrames() {
setError(null);
try {
const link = url.trim();
const { media } = await post("/admin/video-frame", { url: link, seconds });
const { media } = await post("/admin/video-frame", { url: link, seconds, name });
setFrames((list) => [{ media, url: link, seconds }, ...list]);
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't take that frame.");
@ -143,6 +150,19 @@ export default function AdminVideoFrames() {
className={`mt-1 w-full ${input}`}
/>
</div>
<div className="w-64">
<label htmlFor={nameId} className="block text-sm font-medium text-body">
Name
</label>
<input
id={nameId}
type="text"
value={name}
maxLength={200}
onChange={(e) => setTypedName(e.target.value)}
className={`mt-1 w-full ${input}`}
/>
</div>
<button type="submit" className={primary} disabled={busy || !url.trim() || seconds == null}>
{busy ? "Taking…" : "Take frame"}
</button>