NGU-Web/src/pages/admin/AdminClips.tsx
Zaldimmar 185f9831e2 Fix accessibility found in the audit
- Text contrast: teal text and button fills use #0f7183 (5.7:1), section
  accents darkened to pass on white, solid CTA buttons instead of the
  gradient, footer and subnav text raised to white/65, event and region
  colours kept on borders and swatches with ink text
- Hidden carousel slides and collapsed past events are inert
- Admin list rows carry a real link for keyboard use
- Mobile menu is a modal dialog: focus, Escape, inert background, above
  the header
- Skip to content link, one focus-visible ring, reduced-motion rule,
  focus rings on the calendar inputs
- Region headings hold their button instead of sitting inside it
- font-700 style classes (not Tailwind v4 utilities) replaced with named
  weights, and the 700/800 font files loaded
- Migration 038: alt text for blog covers and schedule graphics; event
  logos next to their title are decorative
- Drop the Church Center script from index.html; Giving loads it itself

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 22:07:56 -05:00

515 lines
20 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
ADMIN: VIDEO CLIPS (Tools → Video clips, admins and up)
Paste one of our YouTube or Facebook links, and the server
downloads it (server/src/clips.js). Then cut clips from it: set
the start and end while watching, pick a shape (16:9, square, or
9:16 for Reels and Shorts, cropped around a point you choose) and
video or audio, and make it. Clips queue on the server and run
one at a time; this page asks for progress every POLL_MS while
anything is queued or running.
A finished clip downloads as a file and is then deleted from the
server, unless it's saved to the media library first. Everything
here is swept a day after it was made.
═══════════════════════════════════════════════════════════════ */
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import { Link } from "react-router-dom";
import { ApiError, del, get, post } from "../../lib/api.ts";
const TEAL = "#0f7183";
const MUTED = "#4a6b72";
const POLL_MS = 2000;
type Job = {
id: number;
kind: "source" | "clip";
status: "queued" | "running" | "done" | "failed";
progress: number;
source_url: string | null;
source_id: number | null;
params: { start: number; end: number; shape: string; focus: number; format: string } | null;
title: string | null;
duration: number | null;
bytes: number | null;
error: string | null;
has_file: boolean;
saved_media_id: number | null;
saved_url: string | null;
downloaded_at: string | null;
};
type Listing = {
tools: { ytdlp: string | null; ffmpeg: string | null };
sources: Job[];
clips: Job[];
};
const SHAPES: Array<[string, string, number | null]> = [
["original", "As filmed", null],
["landscape", "Landscape 16:9", 16 / 9],
["square", "Square 1:1", 1],
["vertical", "Vertical 9:16 (Reels, Shorts, TikTok)", 9 / 16],
];
/* 83.5 → "1:23.5"; 3723 → "1:02:03". */
function clock(seconds: number | null | undefined): string {
if (seconds == null || !Number.isFinite(seconds)) return "-";
const whole = Math.floor(seconds);
const tenths = Math.round((seconds - whole) * 10);
const h = Math.floor(whole / 3600);
const m = Math.floor((whole % 3600) / 60);
const s = whole % 60;
const ss = `${String(s).padStart(2, "0")}${tenths ? `.${tenths % 10}` : ""}`;
return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`;
}
/* "1:23.5", "83.5" or "1:02:03" → seconds; null when it isn't a time. */
function parseClock(text: string): number | null {
const parts = text.trim().split(":");
if (!parts.length || parts.some((p) => !/^\d+(\.\d+)?$/.test(p))) return null;
return parts.reduce((total, part) => total * 60 + Number(part), 0);
}
function sizeOf(bytes: number | null): string {
if (!bytes) return "";
return bytes > 1024 * 1024 * 1024
? `${(bytes / 1024 / 1024 / 1024).toFixed(1)} GB`
: `${Math.round(bytes / 1024 / 1024)} MB`;
}
const button =
"rounded-full border border-[#138ba0] px-4 py-2 text-sm font-semibold text-[#0f7183] transition-colors hover:bg-[#eef9fb] disabled:cursor-default disabled:opacity-50";
const primary =
"rounded-full bg-[#0f7183] px-5 py-2.5 font-semibold text-white transition-colors hover:bg-[#0b5c6a] disabled:bg-[#4a6b72]/25";
const input =
"rounded-lg border border-[#4a6b72]/25 bg-white px-3 py-2 text-sm text-[#26454c] outline-none focus:border-[#138ba0] focus:ring-2 focus:ring-[#138ba0]/25";
function Card({ title, children }: { title: string; children: ReactNode }) {
return (
<section className="mt-6 rounded-2xl border border-[#138ba0]/20 bg-white p-5">
<h2 className="text-lg font-semibold text-[#26454c]">{title}</h2>
<div className="mt-4">{children}</div>
</section>
);
}
function Status({ job }: { job: Job }) {
if (job.status === "failed") return <p className="text-sm text-[#b3261e]">Failed: {job.error}</p>;
if (job.status === "done") return null;
const percent = Math.round(job.progress * 100);
return (
<div className="mt-2">
<div className="h-2 overflow-hidden rounded-full bg-[#eef9fb]">
<div className="h-full bg-[#0f7183] transition-all" style={{ width: `${job.status === "queued" ? 0 : percent}%` }} />
</div>
<p className="mt-1 text-xs" style={{ color: MUTED }}>
{job.status === "queued" ? "Waiting its turn…" : `${percent}%`}
</p>
</div>
);
}
/* ── The editor for one downloaded video ─────────────────────── */
function Editor({ source, onMade }: { source: Job; onMade: () => void }) {
const videoRef = useRef<HTMLVideoElement>(null);
const [aspect, setAspect] = useState<number | null>(null);
const [now, setNow] = useState(0);
const [start, setStart] = useState(0);
const [end, setEnd] = useState(Math.min(source.duration ?? 60, 60));
const [startText, setStartText] = useState(clock(0));
const [endText, setEndText] = useState(clock(Math.min(source.duration ?? 60, 60)));
const [shape, setShape] = useState("original");
const [focus, setFocus] = useState(0.5);
const [format, setFormat] = useState("video");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const target = SHAPES.find(([id]) => id === shape)?.[2] ?? null;
const setStartAt = (s: number) => {
setStart(s);
setStartText(clock(s));
};
const setEndAt = (s: number) => {
setEnd(s);
setEndText(clock(s));
};
// The crop box over the video, in percent of the frame.
let crop: { left: number; top: number; width: number; height: number } | null = null;
if (target && aspect && format === "video") {
if (aspect > target) {
const width = (target / aspect) * 100;
crop = { width, height: 100, top: 0, left: Math.min(Math.max(focus * 100 - width / 2, 0), 100 - width) };
} else {
const height = (aspect / target) * 100;
crop = { width: 100, height, left: 0, top: Math.min(Math.max(focus * 100 - height / 2, 0), 100 - height) };
}
}
async function make() {
setBusy(true);
setError(null);
try {
await post("/admin/clips", { source_id: source.id, start, end, shape, focus, format });
onMade();
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't queue the clip.");
} finally {
setBusy(false);
}
}
return (
<div className="grid gap-6 lg:grid-cols-[minmax(0,3fr)_minmax(0,2fr)]">
<div>
<div
className="relative overflow-hidden rounded-xl bg-black"
style={{ aspectRatio: aspect ? String(aspect) : "16 / 9" }}
>
<video
ref={videoRef}
src={`/api/admin/clips/${source.id}/video`}
controls
preload="metadata"
className="h-full w-full"
onLoadedMetadata={(e) => {
const v = e.currentTarget;
if (v.videoWidth && v.videoHeight) setAspect(v.videoWidth / v.videoHeight);
}}
onTimeUpdate={(e) => setNow(e.currentTarget.currentTime)}
/>
{crop && (
// Everything outside the box is dimmed by its huge shadow.
<div
aria-hidden="true"
className="pointer-events-none absolute border-2 border-white"
style={{
left: `${crop.left}%`,
top: `${crop.top}%`,
width: `${crop.width}%`,
height: `${crop.height}%`,
boxShadow: "0 0 0 9999px rgba(0,0,0,0.55)",
}}
/>
)}
</div>
<p className="mt-2 text-sm" style={{ color: MUTED }}>
At {clock(now)} of {clock(source.duration)}
</p>
</div>
<div className="space-y-5">
<div className="grid grid-cols-2 gap-4">
{(
[
["Start", startText, setStartText, setStartAt, start],
["End", endText, setEndText, setEndAt, end],
] as const
).map(([label, text, setText, setAt, value]) => (
<div key={label}>
<label className="block text-sm font-medium text-[#26454c]" htmlFor={`clip-${label}`}>
{label}
</label>
<input
id={`clip-${label}`}
value={text}
onChange={(e) => {
setText(e.target.value);
const s = parseClock(e.target.value);
if (s != null) (label === "Start" ? setStart : setEnd)(s);
}}
onBlur={() => setText(clock(value))}
className={`mt-1 w-full ${input}`}
/>
<div className="mt-2 flex gap-2">
<button type="button" className={button} onClick={() => setAt(Math.round(now * 10) / 10)}>
Set to {clock(now)}
</button>
<button
type="button"
className="text-sm underline"
style={{ color: TEAL }}
onClick={() => {
if (videoRef.current) videoRef.current.currentTime = value;
}}
>
Go
</button>
</div>
</div>
))}
</div>
<p className="text-sm" style={{ color: end > start ? MUTED : "#b3261e" }}>
{end > start ? `Clip length: ${clock(end - start)}` : "The start has to be before the end."}
</p>
<div>
<p className="text-sm font-medium text-[#26454c]">Make it</p>
<div className="mt-2 flex gap-4 text-sm">
{[
["video", "Video (MP4)"],
["audio", "Audio only (MP3)"],
].map(([id, label]) => (
<label key={id} className="flex items-center gap-2">
<input type="radio" name="clip-format" checked={format === id} onChange={() => setFormat(id)} />
{label}
</label>
))}
</div>
</div>
{format === "video" && (
<div>
<p className="text-sm font-medium text-[#26454c]">Shape</p>
<div className="mt-2 grid gap-1.5 text-sm">
{SHAPES.map(([id, label]) => (
<label key={id} className="flex items-center gap-2">
<input type="radio" name="clip-shape" checked={shape === id} onChange={() => setShape(id)} />
{label}
</label>
))}
</div>
{target && (
<label className="mt-3 block text-sm text-[#26454c]">
Where to crop
<input
type="range"
min={0}
max={1}
step={0.01}
value={focus}
onChange={(e) => setFocus(Number(e.target.value))}
className="mt-1 w-full accent-[#138ba0]"
/>
<span className="text-xs" style={{ color: MUTED }}>
The white box on the video is what's kept.
</span>
</label>
)}
</div>
)}
<button type="button" className={primary} disabled={busy || end <= start} onClick={make}>
{busy ? "Queuing…" : "Make clip"}
</button>
{error && <p className="text-sm text-[#b3261e]">{error}</p>}
</div>
</div>
);
}
/* ── The page ────────────────────────────────────────────────── */
export default function AdminClips() {
const [data, setData] = useState<Listing | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [url, setUrl] = useState("");
const [adding, setAdding] = useState(false);
const [addError, setAddError] = useState<string | null>(null);
const [openId, setOpenId] = useState<number | null>(null);
const [rowError, setRowError] = useState<string | null>(null);
const load = useCallback(() => {
get("/admin/clips", { ttl: 0 })
.then((d) => {
setData(d);
setLoadError(null);
})
.catch((err) => setLoadError(err instanceof ApiError ? err.message : "Couldn't load the clips."));
}, []);
useEffect(load, [load]);
const busy = data ? [...data.sources, ...data.clips].some((j) => j.status === "queued" || j.status === "running") : false;
useEffect(() => {
if (!busy) return undefined;
const timer = window.setInterval(load, POLL_MS);
return () => window.clearInterval(timer);
}, [busy, load]);
async function addSource(e) {
e.preventDefault();
setAdding(true);
setAddError(null);
try {
await post("/admin/clips/sources", { url });
setUrl("");
load();
} catch (err) {
setAddError(err instanceof ApiError ? err.message : "Couldn't queue the download.");
} finally {
setAdding(false);
}
}
async function act(fn: () => Promise<unknown>) {
setRowError(null);
try {
await fn();
} catch (err) {
setRowError(err instanceof ApiError ? err.message : "That didn't work.");
}
load();
}
if (!data) {
return <p style={{ color: loadError ? "#b3261e" : MUTED }}>{loadError ?? "Loading…"}</p>;
}
const missing = [!data.tools.ytdlp && "yt-dlp", !data.tools.ffmpeg && "ffmpeg"].filter(Boolean);
const open = data.sources.find((s) => s.id === openId && s.status === "done" && s.has_file) ?? null;
const sourceTitle = (id: number | null) => data.sources.find((s) => s.id === id)?.title ?? "Clip";
return (
<div>
<div className="flex flex-wrap items-baseline gap-3">
<h1 className="text-2xl font-bold text-[#0f7183]">Video clips</h1>
<p className="text-sm" style={{ color: MUTED }}>
Cut clips from our YouTube and Facebook videos, for Reels, Shorts, the site or a podcast.
</p>
</div>
{missing.length > 0 && (
<p className="mt-4 rounded-xl bg-[#fdf3f2] px-4 py-3 text-sm text-[#b3261e]">
{missing.join(" and ")} {missing.length > 1 ? "aren't" : "isn't"} installed on the server, so this
won't work until {missing.length > 1 ? "they are" : "it is"}. See docs/video-clips.md.
</p>
)}
<Card title="1. Download a video">
<form onSubmit={addSource} className="flex flex-wrap gap-3">
<input
type="url"
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder="https://www.youtube.com/watch?v=…"
className={`min-w-0 flex-1 ${input}`}
/>
<button type="submit" className={primary} disabled={adding || !url.trim()}>
{adding ? "Adding…" : "Download"}
</button>
</form>
<p className="mt-2 text-xs" style={{ color: MUTED }}>
YouTube and Facebook links only, and only videos NGU owns or has permission to use. Up to 4 hours long.
</p>
{addError && <p className="mt-2 text-sm text-[#b3261e]">{addError}</p>}
{data.sources.length > 0 && (
<ul className="mt-5 divide-y divide-[#138ba0]/10">
{data.sources.map((s) => (
<li key={s.id} className="py-3">
<div className="flex flex-wrap items-center gap-3">
<div className="min-w-0 flex-1">
<p className="truncate font-medium text-[#26454c]">{s.title ?? s.source_url}</p>
<p className="text-xs" style={{ color: MUTED }}>
{[s.duration && clock(s.duration), sizeOf(s.bytes)].filter(Boolean).join(" · ")}
</p>
</div>
{s.status === "done" && s.has_file && (
<button type="button" className={button} onClick={() => setOpenId(openId === s.id ? null : s.id)}>
{openId === s.id ? "Close" : "Make clips"}
</button>
)}
{s.status !== "running" && (
<button
type="button"
className="text-sm hover:text-[#b3261e]"
style={{ color: MUTED }}
onClick={() =>
window.confirm("Delete this video and its clips from the server?") &&
act(() => del(`/admin/clips/${s.id}`))
}
>
Delete
</button>
)}
</div>
<Status job={s} />
</li>
))}
</ul>
)}
</Card>
{open && (
<Card title={`2. Cut: ${open.title ?? "video"}`}>
<Editor source={open} onMade={load} />
</Card>
)}
{data.clips.length > 0 && (
<Card title="Clips">
{rowError && <p className="mb-3 text-sm text-[#b3261e]">{rowError}</p>}
<ul className="divide-y divide-[#138ba0]/10">
{data.clips.map((clip) => (
<li key={clip.id} className="py-3">
<div className="flex flex-wrap items-center gap-3">
<div className="min-w-0 flex-1">
<p className="truncate font-medium text-[#26454c]">{sourceTitle(clip.source_id)}</p>
<p className="text-xs" style={{ color: MUTED }}>
{clip.params &&
[
`${clock(clip.params.start)} to ${clock(clip.params.end)}`,
clip.params.format === "audio"
? "MP3"
: SHAPES.find(([id]) => id === clip.params!.shape)?.[1],
sizeOf(clip.bytes),
]
.filter(Boolean)
.join(" · ")}
</p>
</div>
{clip.status === "done" && clip.has_file && (
<>
<a
href={`/api/admin/clips/${clip.id}/download`}
className={primary}
onClick={() => window.setTimeout(load, 3000)}
>
Download
</a>
<button type="button" className={button} onClick={() => act(() => post(`/admin/clips/${clip.id}/save`, {}))}>
Save to library
</button>
</>
)}
{clip.saved_url && (
<Link to="/admin/media" className="text-sm underline" style={{ color: TEAL }}>
In the media library
</Link>
)}
{clip.status === "done" && !clip.has_file && !clip.saved_url && (
<span className="text-sm" style={{ color: MUTED }}>
Downloaded, and deleted from the server
</span>
)}
{clip.status !== "running" && (
<button
type="button"
className="text-sm hover:text-[#b3261e]"
style={{ color: MUTED }}
onClick={() => act(() => del(`/admin/clips/${clip.id}`))}
>
Remove
</button>
)}
</div>
<Status job={clip} />
</li>
))}
</ul>
<p className="mt-3 text-xs" style={{ color: MUTED }}>
A clip is deleted from the server once it's downloaded, unless it's saved to the library first.
Everything here is cleared a day after it's made.
</p>
</Card>
)}
</div>
);
}