Let the image picker take photos sent with requests
A From requests tab in every image picker lists photos from the Request form (they live in Drive), the request being edited from first. Picking one copies it into the media library, in the field's folder, once per file, and the field gets that copy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
110b655d5e
commit
6ccbc03b52
3 changed files with 128 additions and 8 deletions
|
|
@ -13,6 +13,7 @@ import { requireAuth, requireRole } from "../auth.js";
|
||||||
import { NO_STORE } from "../shape.js";
|
import { NO_STORE } from "../shape.js";
|
||||||
import { driveDelete, driveDownload, driveReady, driveTree } from "../googleService.js";
|
import { driveDelete, driveDownload, driveReady, driveTree } from "../googleService.js";
|
||||||
import { DRIVE_FOLDER, TYPE_FOLDERS } from "./requests.js";
|
import { DRIVE_FOLDER, TYPE_FOLDERS } from "./requests.js";
|
||||||
|
import { addToLibrary, shape as mediaShape } from "./media.js";
|
||||||
import { HttpError } from "../admin-crud.js";
|
import { HttpError } from "../admin-crud.js";
|
||||||
import { importDocx } from "./import.js";
|
import { importDocx } from "./import.js";
|
||||||
|
|
||||||
|
|
@ -246,6 +247,9 @@ admin.delete("/feedback/:id", requireRole("admin"), async (c) => {
|
||||||
GET /feedback/:id/files/:file download, from Drive
|
GET /feedback/:id/files/:file download, from Drive
|
||||||
POST /feedback/:id/files/:file/blog-post a .docx as a new
|
POST /feedback/:id/files/:file/blog-post a .docx as a new
|
||||||
unpublished blog post (import.js), editors and up
|
unpublished blog post (import.js), editors and up
|
||||||
|
POST /feedback/:id/files/:file/to-library { folder }: a photo
|
||||||
|
into the media library, for an image field (the picker's
|
||||||
|
From requests tab), editors and up
|
||||||
DELETE /feedback/:id/files/:file into Drive's trash and
|
DELETE /feedback/:id/files/:file into Drive's trash and
|
||||||
off the request, admins and up
|
off the request, admins and up
|
||||||
GET /request-files every request's files,
|
GET /request-files every request's files,
|
||||||
|
|
@ -284,6 +288,29 @@ admin.get("/feedback/:id/files/:file", async (c) => {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/* A request's photo as an upload: records' images live in the media
|
||||||
|
library, not Drive. Once per file: the copy is found again by name. */
|
||||||
|
admin.post("/feedback/:id/files/:file/to-library", requireRole("editor"), async (c) => {
|
||||||
|
const file = fileOf(c);
|
||||||
|
if (!file) return c.json({ error: "No such file." }, 404);
|
||||||
|
if (!file.mime.startsWith("image/")) return c.json({ error: "Only a photo (JPEG or PNG) can go in the library." }, 400);
|
||||||
|
const db = c.get("db");
|
||||||
|
const name = `${file.name} (request ${c.req.param("id")})`.slice(0, 200);
|
||||||
|
const known = db.prepare(`SELECT m.* FROM media m WHERE m.original_name = ?`).get(name);
|
||||||
|
if (known) return c.json({ media: mediaShape(known) }, 200, NO_STORE);
|
||||||
|
try {
|
||||||
|
const bytes = await fromDrive(file);
|
||||||
|
const body = (await c.req.json().catch(() => null)) ?? {};
|
||||||
|
const row = await addToLibrary(db, bytes, { originalName: name, folder: body.folder, userId: c.get("user").id });
|
||||||
|
console.log(`feedback #${c.req.param("id")}: ${file.name} into the media library by ${c.get("user").email}`);
|
||||||
|
return c.json({ media: mediaShape(row) }, 201, NO_STORE);
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof HttpError) return c.json({ error: err.message }, err.status);
|
||||||
|
if (err?.status && err?.message) return c.json({ error: err.message }, err.status); // MediaError
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
admin.post("/feedback/:id/files/:file/blog-post", requireRole("editor"), async (c) => {
|
admin.post("/feedback/:id/files/:file/blog-post", requireRole("editor"), async (c) => {
|
||||||
const file = fileOf(c);
|
const file = fileOf(c);
|
||||||
if (!file) return c.json({ error: "No such file." }, 404);
|
if (!file) return c.json({ error: "No such file." }, 404);
|
||||||
|
|
|
||||||
|
|
@ -58,7 +58,7 @@ let lastScan = 0;
|
||||||
/* Tables that can't hold an image path, or mustn't be searched. */
|
/* Tables that can't hold an image path, or mustn't be searched. */
|
||||||
const NOT_CONTENT = new Set(["media", "drive_files", "admin_users", "sessions", "feedback", "feedback_files", "sqlite_sequence"]);
|
const NOT_CONTENT = new Set(["media", "drive_files", "admin_users", "sessions", "feedback", "feedback_files", "sqlite_sequence"]);
|
||||||
|
|
||||||
function shape(row) {
|
export function shape(row) {
|
||||||
return {
|
return {
|
||||||
id: row.id,
|
id: row.id,
|
||||||
// A hand-copied file keeps its own name, which may need escaping
|
// A hand-copied file keeps its own name, which may need escaping
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,10 @@
|
||||||
ImageInput the `widget: "image"` form field. A preview, the
|
ImageInput the `widget: "image"` form field. A preview, the
|
||||||
stored value as editable text, and buttons to
|
stored value as editable text, and buttons to
|
||||||
upload a new file or pick an earlier one.
|
upload a new file or pick an earlier one.
|
||||||
MediaPicker the dialog behind "Choose from library".
|
MediaPicker the dialog behind "Choose from library". Its From
|
||||||
|
requests tab lists photos sent with the Request
|
||||||
|
form (in Drive); picking one copies it into the
|
||||||
|
library first (RequestImages).
|
||||||
MediaGrid the thumbnails both the picker and the Media page
|
MediaGrid the thumbnails both the picker and the Media page
|
||||||
(pages/admin/AdminMedia.tsx) draw.
|
(pages/admin/AdminMedia.tsx) draw.
|
||||||
UploadButton a file input dressed as a button, with the
|
UploadButton a file input dressed as a button, with the
|
||||||
|
|
@ -37,6 +40,8 @@
|
||||||
import { FileAudio, X } from "@phosphor-icons/react";
|
import { FileAudio, X } from "@phosphor-icons/react";
|
||||||
import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from "react";
|
import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from "react";
|
||||||
|
|
||||||
|
import { useLocation } from "react-router-dom";
|
||||||
|
|
||||||
import { ApiError, get, post, upload } from "../../lib/api.ts";
|
import { ApiError, get, post, upload } from "../../lib/api.ts";
|
||||||
import { useAuth } from "../../lib/auth.tsx";
|
import { useAuth } from "../../lib/auth.tsx";
|
||||||
import { canWrite as roleCanWrite } from "../../lib/roles.ts";
|
import { canWrite as roleCanWrite } from "../../lib/roles.ts";
|
||||||
|
|
@ -65,11 +70,20 @@ export const IMAGE_FOLDERS = [
|
||||||
] as const;
|
] as const;
|
||||||
export type ImageFolder = (typeof IMAGE_FOLDERS)[number][0];
|
export type ImageFolder = (typeof IMAGE_FOLDERS)[number][0];
|
||||||
|
|
||||||
/* A tab strip over the folders; `value` is the one showing. */
|
/* A tab strip over the folders; `value` is the one showing. `extra`
|
||||||
export function FolderTabs({ value, onChange }: { value: string; onChange: (folder: ImageFolder) => void }) {
|
adds tabs after them (the picker's From requests). */
|
||||||
|
export function FolderTabs({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
extra = [],
|
||||||
|
}: {
|
||||||
|
value: string;
|
||||||
|
onChange: (folder: string) => void;
|
||||||
|
extra?: [string, string][];
|
||||||
|
}) {
|
||||||
return (
|
return (
|
||||||
<div role="tablist" aria-label="Folders" className="flex flex-wrap gap-1">
|
<div role="tablist" aria-label="Folders" className="flex flex-wrap gap-1">
|
||||||
{IMAGE_FOLDERS.map(([folder, label]) => (
|
{[...IMAGE_FOLDERS, ...extra].map(([folder, label]) => (
|
||||||
<button
|
<button
|
||||||
key={folder}
|
key={folder}
|
||||||
type="button"
|
type="button"
|
||||||
|
|
@ -305,6 +319,75 @@ export function MediaGrid({
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── Photos sent with requests ───────────────────────────────── */
|
||||||
|
|
||||||
|
const REQUESTS_TAB = "requests";
|
||||||
|
|
||||||
|
/* Photos from the Request form, which live in Drive: the one being
|
||||||
|
edited from first (Forms → Content requests → Create from this),
|
||||||
|
then newest. Picking one copies it into the library, into the
|
||||||
|
field's folder, and that copy is what the field gets. */
|
||||||
|
function RequestImages({ folder, onPick }: { folder?: string; onPick: (item: MediaItem) => void }) {
|
||||||
|
const current = (useLocation().state as any)?.fromRequest?.request ?? null;
|
||||||
|
const [files, setFiles] = useState<any[] | null>(null);
|
||||||
|
const [busy, setBusy] = useState<number | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
get("/admin/request-files", { ttl: 0 })
|
||||||
|
.then((data) => {
|
||||||
|
const photos = data.files.filter((f) => f.mime.startsWith("image/") && !f.missing);
|
||||||
|
setFiles([...photos.filter((f) => f.feedback_id === current), ...photos.filter((f) => f.feedback_id !== current)]);
|
||||||
|
})
|
||||||
|
.catch((err) => setError(err instanceof ApiError ? err.message : "Couldn't load the request files."));
|
||||||
|
}, [current]);
|
||||||
|
|
||||||
|
async function pick(file) {
|
||||||
|
setBusy(file.id);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const { media } = await post(`/admin/feedback/${file.feedback_id}/files/${file.id}/to-library`, { folder });
|
||||||
|
onPick(media);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof ApiError ? err.message : "Couldn't copy it into the library.");
|
||||||
|
setBusy(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error && !files) return <p className="text-sm text-danger">{error}</p>;
|
||||||
|
if (!files) return <p className="text-sm text-muted">Loading…</p>;
|
||||||
|
if (files.length === 0) return <p className="text-sm text-muted">No photos have come in with requests.</p>;
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{error && <p className="mb-3 text-sm text-danger">{error}</p>}
|
||||||
|
<ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
|
||||||
|
{files.map((file) => (
|
||||||
|
<li key={file.id} className="rounded-xl border border-muted/20 bg-surface p-2">
|
||||||
|
<button type="button" disabled={busy !== null} onClick={() => pick(file)} className="block w-full text-left disabled:opacity-60">
|
||||||
|
<div className="aspect-[4/3] overflow-hidden rounded-lg" style={CHECKER}>
|
||||||
|
{/* Straight from Drive through the server; private to the admin. */}
|
||||||
|
<img
|
||||||
|
src={`/api/admin/feedback/${file.feedback_id}/files/${file.id}`}
|
||||||
|
alt=""
|
||||||
|
loading="lazy"
|
||||||
|
className="h-full w-full object-contain"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p className="mt-1.5 truncate text-xs font-medium text-body" title={file.name}>
|
||||||
|
{busy === file.id ? "Copying…" : file.name}
|
||||||
|
</p>
|
||||||
|
<p className="truncate text-xs text-muted/80">
|
||||||
|
{file.feedback_id === current ? "This request" : `Request #${file.feedback_id}`}
|
||||||
|
{file.subject ? `: ${file.subject}` : ""}
|
||||||
|
</p>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/* ── Picker dialog ───────────────────────────────────────────── */
|
/* ── Picker dialog ───────────────────────────────────────────── */
|
||||||
|
|
||||||
export function MediaPicker({
|
export function MediaPicker({
|
||||||
|
|
@ -322,7 +405,8 @@ export function MediaPicker({
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const [query, setQuery] = useState("");
|
const [query, setQuery] = useState("");
|
||||||
const [tab, setTab] = useState<string>(folder);
|
const [tab, setTab] = useState<string>(folder);
|
||||||
const { items, error, setItems } = useMediaLibrary(query, "image", tab);
|
const fromRequests = tab === REQUESTS_TAB;
|
||||||
|
const { items, error, setItems } = useMediaLibrary(query, "image", fromRequests ? undefined : tab);
|
||||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||||
|
|
||||||
// showModal gives focus trapping, Escape and the backdrop for free.
|
// showModal gives focus trapping, Escape and the backdrop for free.
|
||||||
|
|
@ -361,7 +445,7 @@ export function MediaPicker({
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="border-b border-brand/10 px-5 py-3">
|
<div className="border-b border-brand/10 px-5 py-3">
|
||||||
<FolderTabs value={tab} onChange={setTab} />
|
<FolderTabs value={tab} onChange={setTab} extra={[[REQUESTS_TAB, "From requests"]]} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{roleCanWrite(user) && (
|
{roleCanWrite(user) && (
|
||||||
|
|
@ -380,7 +464,16 @@ export function MediaPicker({
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="overflow-y-auto px-5 py-4">
|
<div className="overflow-y-auto px-5 py-4">
|
||||||
{error ? (
|
{fromRequests ? (
|
||||||
|
<RequestImages
|
||||||
|
folder={folder}
|
||||||
|
onPick={(item) => {
|
||||||
|
setItems((current) => [item, ...(current ?? []).filter((m) => m.id !== item.id)]);
|
||||||
|
onPick(item);
|
||||||
|
dialogRef.current?.close();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : error ? (
|
||||||
<p className="text-sm text-danger">{error}</p>
|
<p className="text-sm text-danger">{error}</p>
|
||||||
) : items === null ? (
|
) : items === null ? (
|
||||||
<p className="text-sm text-muted">Loading…</p>
|
<p className="text-sm text-muted">Loading…</p>
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue