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

@ -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>