Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: share persona master-detail UI (#4886)

[._.]/ Adam Eivy7fa39fc3122b
diff --git a/client/src/components/music/ArtistsManager.jsx b/client/src/components/music/ArtistsManager.jsx
index 38030aa664..f3377e91fd 100644
--- a/client/src/components/music/ArtistsManager.jsx
+++ b/client/src/components/music/ArtistsManager.jsx
@@ -1,444 +1,69 @@
-/**
- * ArtistsManager — manage reusable music-artist personas (the Music studio's
- * analogue of the Authors page). Master-detail: a selectable list on the left,
- * an editor on the right. An Artist carries a name, genre, bio, musical style,
- * plus a physical description + portrait style used to generate (or upload) an
- * artist portrait. Mirrors pages/Authors.jsx — same portrait
- * generate/upload/gallery affordances, reusing the image-gen pipeline.
- */
-
-import { useEffect, useMemo, useRef, useState } from 'react';
-import { useNavigate, useParams } from 'react-router';
-import { Plus, Loader2, Trash2, Save, ImageIcon, Sparkles, X } from 'lucide-react';
-import BrailleSpinner from '../BrailleSpinner';
-import toast from '../ui/Toast';
-import GalleryImagePicker from '../imageGen/GalleryImagePicker';
-import ConfirmButtonPair from '../ui/ConfirmButtonPair';
-import Field from '../ui/FormField';
-import useMediaJobProgress from '../../hooks/useMediaJobProgress';
-import { useConfirmDelete } from '../../hooks/useConfirmDelete';
-import { DEFAULT_NEGATIVE_PROMPT } from '../../lib/imageGenDefaults';
+import { useParams } from 'react-router';
+import PersonaMasterDetail from '../persona/PersonaMasterDetail';
import {
listArtists, createArtist, updateArtist, deleteArtist, generateImage,
ARTIST_NAME_MAX, ARTIST_GENRE_MAX, ARTIST_BIO_MAX, ARTIST_MUSICAL_STYLE_MAX,
ARTIST_PHYSICAL_DESCRIPTION_MAX, ARTIST_PORTRAIT_STYLE_MAX, ARTIST_PORTRAIT_IMAGE_URL_MAX,
} from '../../services/api';
-// Cap portrait uploads so the base64 round-trip stays small. Enforced by
-// GalleryImagePicker's `maxBytes`.
-const PORTRAIT_MAX_BYTES = 12 * 1024 * 1024;
-
-const emptyForm = () => ({
- name: '', genre: '', bio: '', musicalStyle: '', physicalDescription: '', portraitStyle: '', portraitImageUrl: '',
-});
-
-const formFromArtist = (a) => ({
- name: a.name || '',
- genre: a.genre || '',
- bio: a.bio || '',
- musicalStyle: a.musicalStyle || '',
- physicalDescription: a.physicalDescription || '',
- portraitStyle: a.portraitStyle || '',
- portraitImageUrl: a.portraitImageUrl || '',
-});
-
-// Build the image-gen prompt for an artist portrait from the persona's physical
-// description (the subject) and portrait style (the art direction). Either field
-// alone is enough to render; both are folded into one prompt.
-const buildPortraitPrompt = (f) => {
- const desc = (f.physicalDescription || '').trim();
- const style = (f.portraitStyle || '').trim();
- const subject = desc ? `Music artist portrait. ${desc}` : 'Music artist promotional portrait.';
- return style ? `${subject} ${style}` : subject;
+const FIELDS = [
+ { key: 'name', label: 'Name', placeholder: 'Nova Vale', maxLength: ARTIST_NAME_MAX },
+ {
+ key: 'genre', label: 'Genre', hint: "Primary genre(s) — e.g. 'indie folk, dream pop'.",
+ placeholder: 'indie folk, dream pop', maxLength: ARTIST_GENRE_MAX,
+ },
+ {
+ key: 'musicalStyle', label: 'Musical style', type: 'textarea', rows: 4,
+ hint: 'Voice / production / instrumentation notes — fed into music-gen prompts.',
+ placeholder: 'Warm fingerpicked guitar, breathy close-mic vocals, tape saturation, sparse reverb.', maxLength: ARTIST_MUSICAL_STYLE_MAX,
+ },
+ {
+ key: 'bio', label: 'Bio', type: 'textarea', rows: 4, hint: 'About-the-artist blurb.',
+ placeholder: 'Nova Vale is a songwriter working at the seam of folk and ambient…', maxLength: ARTIST_BIO_MAX,
+ },
+ {
+ key: 'physicalDescription', label: 'Physical description', type: 'textarea', rows: 3,
+ hint: 'Subject of the portrait — appearance, age, expression, wardrobe.',
+ placeholder: 'Androgynous figure, late 20s, cropped platinum hair, vintage band tee, calm gaze.', maxLength: ARTIST_PHYSICAL_DESCRIPTION_MAX,
+ },
+ {
+ key: 'portraitStyle', label: 'Portrait style', type: 'textarea', rows: 3,
+ hint: 'Art / photography direction for the portrait render.',
+ placeholder: 'Moody film photograph, neon backlight, grainy 35mm, shallow depth of field.', maxLength: ARTIST_PORTRAIT_STYLE_MAX,
+ },
+];
+
+const PORTRAIT = {
+ label: 'Portrait', fieldLabel: 'Portrait image', imageKey: 'portraitImageUrl',
+ descriptionKey: 'physicalDescription', styleKey: 'portraitStyle', styleLabel: 'Portrait style',
+ maxLength: ARTIST_PORTRAIT_IMAGE_URL_MAX,
+ hint: 'Optional — generate from the description + style, choose or upload one via the gallery, or paste a URL.',
+ generateTitle: 'Generate a portrait from the description + style',
+ buildPrompt: (form) => {
+ const description = form.physicalDescription.trim();
+ const style = form.portraitStyle.trim();
+ const subject = description ? `Music artist portrait. ${description}` : 'Music artist promotional portrait.';
+ return style ? `${subject} ${style}` : subject;
+ },
};
export default function ArtistsManager() {
- const navigate = useNavigate();
- // Selection lives in the URL (`/music/artists/:id`, `/music/artists/new`) so
- // it's deep-linkable and reload-safe. `id === 'new'` is create mode; a real id
- // is edit mode; absent is idle.
const { id } = useParams();
- const [artists, setArtists] = useState([]);
- const [loading, setLoading] = useState(true);
- const [form, setForm] = useState(emptyForm);
- const [saving, setSaving] = useState(false);
- const { isConfirming: isConfirmingDelete, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
- const [galleryOpen, setGalleryOpen] = useState(false);
- const [startingGen, setStartingGen] = useState(false);
- const [genJobId, setGenJobId] = useState(null);
- // Bumped on every artist switch / new-artist so a stale generate response
- // can't write the wrong persona's portrait (mirrors Authors' genRequestRef).
- const genRequestRef = useRef(0);
-
- const gen = useMediaJobProgress(genJobId);
- const isGenerating = startingGen || !!genJobId;
-
- const setPortrait = (url) => setForm((f) => ({ ...f, portraitImageUrl: url }));
- const clearGeneration = () => { genRequestRef.current += 1; setGenJobId(null); setStartingGen(false); };
-
- useEffect(() => {
- if (!genJobId) return;
- if (gen.status === 'completed' && gen.filename) {
- setPortrait(gen.path || `/data/images/${gen.filename}`);
- setGenJobId(null);
- toast.success('Portrait generated');
- } else if (gen.status === 'failed' || gen.status === 'canceled') {
- setGenJobId(null);
- toast.error(gen.error || 'Portrait generation failed');
- }
- }, [genJobId, gen.status, gen.filename, gen.path, gen.error]);
-
- const handleGeneratePortrait = async () => {
- if (isGenerating) return;
- if (!form.physicalDescription.trim() && !form.portraitStyle.trim()) {
- toast.error('Add a physical description or portrait style to generate from');
- return;
- }
- const requestId = genRequestRef.current;
- setStartingGen(true);
- const queued = await generateImage({
- prompt: buildPortraitPrompt(form),
- negativePrompt: `${DEFAULT_NEGATIVE_PROMPT}, extra limbs, nsfw, nude`,
- width: 768,
- height: 1024,
- }, { silent: true }).catch((err) => ({ error: err }));
- if (genRequestRef.current !== requestId) return;
- setStartingGen(false);
- if (queued?.error) {
- toast.error(queued.error.message || 'Portrait generation failed');
- return;
- }
- if (queued.jobId) {
- setGenJobId(queued.jobId);
- toast.success('Generating portrait…');
- return;
- }
- const path = queued.path || (queued.filename ? `/data/images/${queued.filename}` : '');
- if (path) {
- setPortrait(path);
- toast.success('Portrait generated');
- } else {
- toast.error('Portrait generation returned no image');
- }
- };
-
- // Both "pick an existing gallery image" and "upload one from disk" land here —
- // GalleryImagePicker's `allowUpload` owns the read + POST and hands back the
- // saved image already normalized (issue #4127).
- const handlePortraitPick = (item) => {
- setGalleryOpen(false);
- const url = item?.previewUrl || (item?.filename ? `/data/images/${item.filename}` : '');
- if (url) setPortrait(url);
- };
-
- useEffect(() => {
- listArtists({ silent: true })
- .then((list) => setArtists(Array.isArray(list) ? list : []))
- .catch((err) => toast.error(err.message || 'Failed to load artists'))
- .finally(() => setLoading(false));
- }, []);
-
- const isCreate = id === 'new';
- const selected = useMemo(
- () => (isCreate || !id ? null : artists.find((a) => a.id === id) || null),
- [artists, id, isCreate],
- );
- const notFound = !isCreate && !!id && !loading && !selected;
- const canGenerate = !!(form.physicalDescription.trim() || form.portraitStyle.trim());
-
- const selectArtist = (a) => navigate(`/music/artists/${encodeURIComponent(a.id)}`);
- const startCreate = () => navigate('/music/artists/new');
-
- // Hydrate the editor form from the URL-selected artist. Keyed on the id so a
- // list refresh doesn't clobber the open form; resets run for every selection
- // change (incl. idle / not-found) so a stray render can't land on the previous
- // artist (see Authors.jsx for the base pattern).
- const hydratedRef = useRef(null);
- const selectionKey = id ?? null;
- useEffect(() => {
- if (loading) return;
- if (hydratedRef.current === selectionKey) return;
- hydratedRef.current = selectionKey;
- cancelDelete();
- clearGeneration();
- if (isCreate) setForm(emptyForm());
- else if (selected) setForm(formFromArtist(selected));
- }, [selectionKey, isCreate, selected, loading]);
-
- const handleSave = async () => {
- const name = form.name.trim();
- if (!name) { toast.error('Artist name is required'); return; }
- setSaving(true);
- const payload = { ...form, name };
- if (isCreate) {
- const created = await createArtist(payload, { silent: true }).catch((err) => {
- toast.error(err.message || 'Failed to create artist');
- return null;
- });
- setSaving(false);
- if (!created) return;
- setArtists((prev) => [...prev, created].sort((a, b) => (a.name || '').localeCompare(b.name || '')));
- navigate(`/music/artists/${encodeURIComponent(created.id)}`);
- toast.success(`Created "${created.name}"`);
- } else {
- const updated = await updateArtist(id, payload, { silent: true }).catch((err) => {
- toast.error(err.message || 'Failed to save artist');
- return null;
- });
- setSaving(false);
- if (!updated) return;
- setArtists((prev) => prev
- .map((a) => (a.id === updated.id ? updated : a))
- .sort((a, b) => (a.name || '').localeCompare(b.name || '')));
- toast.success('Saved');
- }
- };
-
- const handleDelete = async () => {
- if (!selected) return;
- const prior = artists;
- setArtists((prev) => prev.filter((a) => a.id !== selected.id));
- navigate('/music/artists');
- await deleteArtist(selected.id, { silent: true }).catch((err) => {
- toast.error(err.message || 'Delete failed');
- setArtists(prior);
- });
- };
-
return (
- <div>
- <div className="flex items-center justify-between mb-4 flex-wrap gap-3">
- <p className="text-sm text-gray-400 max-w-2xl">
- Artist personas are reusable across albums and tracks — the byline plus the genre, musical
- style, bio, and the physical description + style used to generate (or upload) an artist portrait.
- </p>
- <button
- type="button"
- onClick={startCreate}
- className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 text-white text-sm font-medium shrink-0"
- >
- <Plus size={16} aria-hidden="true" />
- New Artist
- </button>
- </div>
-
- <div className="grid grid-cols-1 md:grid-cols-[260px_1fr] gap-4">
- <div className="bg-port-card border border-port-border rounded-lg p-2">
- {loading ? (
- <div className="text-sm p-2"><BrailleSpinner text="Loading…" /></div>
- ) : artists.length === 0 ? (
- <div className="text-gray-500 text-sm p-2">No artists yet. Click <span className="text-port-accent">New Artist</span>.</div>
- ) : (
- <ul className="space-y-1">
- {artists.map((a) => (
- <li key={a.id}>
- <button
- type="button"
- onClick={() => selectArtist(a)}
- className={`w-full text-left px-3 py-2 rounded text-sm truncate ${
- a.id === id ? 'bg-port-accent/20 text-white' : 'text-gray-300 hover:bg-port-bg'
- }`}
- >
- {a.name}
- {a.genre ? <span className="block text-[11px] text-gray-500 truncate">{a.genre}</span> : null}
- </button>
- </li>
- ))}
- </ul>
- )}
- </div>
-
- <div className="bg-port-card border border-port-border rounded-lg p-4">
- {notFound ? (
- <div className="text-gray-500 text-sm">
- That artist could not be found — it may have been deleted.{' '}
- <button type="button" onClick={() => navigate('/music/artists')} className="text-port-accent hover:underline">
- Back to artists
- </button>
- </div>
- ) : !isCreate && !selected ? (
- <div className="text-gray-500 text-sm">Select an artist to edit, or create a new one.</div>
- ) : (
- <div className="space-y-3">
- <Field compact label="Name">
- <input
- value={form.name}
- onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
- placeholder="Nova Vale"
- maxLength={ARTIST_NAME_MAX}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
- autoFocus
- />
- </Field>
- <Field compact label="Genre" hint="Primary genre(s) — e.g. 'indie folk, dream pop'.">
- <input
- value={form.genre}
- onChange={(e) => setForm((f) => ({ ...f, genre: e.target.value }))}
- placeholder="indie folk, dream pop"
- maxLength={ARTIST_GENRE_MAX}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
- />
- </Field>
- <Field compact label="Musical style" hint="Voice / production / instrumentation notes — fed into music-gen prompts.">
- <textarea
- value={form.musicalStyle}
- onChange={(e) => setForm((f) => ({ ...f, musicalStyle: e.target.value }))}
- rows={4}
- maxLength={ARTIST_MUSICAL_STYLE_MAX}
- placeholder="Warm fingerpicked guitar, breathy close-mic vocals, tape saturation, sparse reverb."
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
- />
- </Field>
- <Field compact label="Bio" hint="About-the-artist blurb.">
- <textarea
- value={form.bio}
- onChange={(e) => setForm((f) => ({ ...f, bio: e.target.value }))}
- rows={4}
- maxLength={ARTIST_BIO_MAX}
- placeholder="Nova Vale is a songwriter working at the seam of folk and ambient…"
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
- />
- </Field>
- <Field compact label="Physical description" hint="Subject of the portrait — appearance, age, expression, wardrobe.">
- <textarea
- value={form.physicalDescription}
- onChange={(e) => setForm((f) => ({ ...f, physicalDescription: e.target.value }))}
- rows={3}
- maxLength={ARTIST_PHYSICAL_DESCRIPTION_MAX}
- placeholder="Androgynous figure, late 20s, cropped platinum hair, vintage band tee, calm gaze."
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
- />
- </Field>
- <Field compact label="Portrait style" hint="Art / photography direction for the portrait render.">
- <textarea
- value={form.portraitStyle}
- onChange={(e) => setForm((f) => ({ ...f, portraitStyle: e.target.value }))}
- rows={3}
- maxLength={ARTIST_PORTRAIT_STYLE_MAX}
- placeholder="Moody film photograph, neon backlight, grainy 35mm, shallow depth of field."
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
- />
- </Field>
- <Field compact label="Portrait image" hint="Optional — generate from the description + style, choose or upload one via the gallery, or paste a URL.">
- <div className="flex items-start gap-3">
- {isGenerating ? (
- <div className="relative w-20 h-20 rounded border border-port-border bg-port-bg overflow-hidden flex items-center justify-center shrink-0">
- {gen.currentImage ? (
- <img
- src={`data:image/png;base64,${gen.currentImage}`}
- alt="Generating portrait preview"
- className="w-full h-full object-cover opacity-70"
- />
- ) : (
- <Loader2 size={20} className="animate-spin text-port-accent" aria-hidden="true" />
- )}
- {gen.totalSteps ? (
- <div className="absolute bottom-0 inset-x-0 bg-black/60 text-[9px] text-white text-center py-0.5 font-mono">
- {Math.round((gen.step / gen.totalSteps) * 100)}%
- </div>
- ) : null}
- </div>
- ) : form.portraitImageUrl ? (
- <div className="relative shrink-0">
- <img
- src={form.portraitImageUrl}
- alt="Artist portrait"
- className="w-20 h-20 rounded object-cover border border-port-border bg-port-bg"
- />
- <button
- type="button"
- onClick={() => setPortrait('')}
- title="Remove portrait" aria-label="Remove portrait"
- className="absolute -top-2 -right-2 p-1 rounded-full bg-port-bg border border-port-border text-gray-400 hover:text-port-error"
- >
- <X size={12} />
- </button>
- </div>
- ) : (
- <div className="w-20 h-20 rounded border border-dashed border-port-border bg-port-bg flex items-center justify-center text-gray-600 shrink-0">
- <ImageIcon size={20} aria-hidden="true" />
- </div>
- )}
- <div className="flex-1 space-y-2">
- <div className="flex items-center gap-2 flex-wrap">
- <button
- type="button"
- onClick={handleGeneratePortrait}
- disabled={isGenerating || !canGenerate}
- title={canGenerate
- ? 'Generate a portrait from the description + style'
- : 'Add a physical description or portrait style first'}
- className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50"
- >
- {isGenerating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
- Generate
- </button>
- <button
- type="button"
- onClick={() => setGalleryOpen(true)}
- disabled={isGenerating}
- title="Pick a gallery image, or upload one from this device"
- className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50"
- >
- <ImageIcon size={14} /> Choose or upload
- </button>
- </div>
- <input
- aria-label="Portrait image URL"
- value={form.portraitImageUrl}
- onChange={(e) => setPortrait(e.target.value)}
- disabled={isGenerating}
- placeholder="/images/… or https://…"
- maxLength={ARTIST_PORTRAIT_IMAGE_URL_MAX}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm disabled:opacity-50"
- />
- </div>
- </div>
- </Field>
-
- <div className="flex items-center gap-2 pt-1 flex-wrap">
- <button
- type="button"
- onClick={handleSave}
- disabled={saving || !form.name.trim()}
- className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"
- >
- {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
- {isCreate ? 'Create' : 'Save'}
- </button>
- {!isCreate && selected ? (
- isConfirmingDelete(selected.id) ? (
- <ConfirmButtonPair
- prompt="Delete this artist?"
- confirmText="Yes, delete"
- ariaLabel="Confirm delete artist"
- tone="error"
- onConfirm={() => confirmDelete(handleDelete)}
- onCancel={cancelDelete}
- />
- ) : (
- <button
- type="button"
- onClick={() => requestDelete(selected.id)}
- className="inline-flex items-center gap-2 px-3 py-2 rounded-lg text-gray-400 hover:text-port-error text-sm"
- >
- <Trash2 size={14} /> Delete
- </button>
- )
- ) : null}
- </div>
- </div>
- )}
- </div>
- </div>
-
- <GalleryImagePicker
- open={galleryOpen}
- onClose={() => setGalleryOpen(false)}
- onSelect={handlePortraitPick}
- allowUpload
- maxBytes={PORTRAIT_MAX_BYTES}
- />
- </div>
+ <PersonaMasterDetail
+ basePath="/music/artists"
+ selectedId={id}
+ intro="Artist personas are reusable across albums and tracks — the byline plus the genre, musical style, bio, and the physical description + style used to generate (or upload) an artist portrait."
+ singular="Artist"
+ plural="Artists"
+ fields={FIELDS}
+ listSecondaryKey="genre"
+ portrait={PORTRAIT}
+ listRecords={listArtists}
+ createRecord={createArtist}
+ updateRecord={updateArtist}
+ deleteRecord={deleteArtist}
+ generateImage={generateImage}
+ />
);
}
diff --git a/client/src/components/persona/PersonaMasterDetail.jsx b/client/src/components/persona/PersonaMasterDetail.jsx
new file mode 100644
index 0000000000..a90c3aea2e
--- /dev/null
+++ b/client/src/components/persona/PersonaMasterDetail.jsx
@@ -0,0 +1,304 @@
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { useNavigate } from 'react-router';
+import { ImageIcon, Loader2, Plus, Save, Sparkles, Trash2, X } from 'lucide-react';
+import BrailleSpinner from '../BrailleSpinner';
+import GalleryImagePicker from '../imageGen/GalleryImagePicker';
+import ConfirmButtonPair from '../ui/ConfirmButtonPair';
+import Field from '../ui/FormField';
+import toast from '../ui/Toast';
+import { useConfirmDelete } from '../../hooks/useConfirmDelete';
+import useMediaJobProgress from '../../hooks/useMediaJobProgress';
+import { DEFAULT_NEGATIVE_PROMPT } from '../../lib/imageGenDefaults';
+
+const PERSONA_IMAGE_MAX_BYTES = 12 * 1024 * 1024;
+const byName = (a, b) => (a.name || '').localeCompare(b.name || '');
+
+export default function PersonaMasterDetail({
+ basePath, selectedId, title, titleIcon: TitleIcon, intro, singular, plural, fields,
+ listSecondaryKey, portrait, listRecords, createRecord, updateRecord, deleteRecord, generateImage,
+}) {
+ const navigate = useNavigate();
+ const emptyForm = useMemo(
+ () => Object.fromEntries([...fields.map(({ key }) => key), portrait.imageKey].map((key) => [key, ''])),
+ [fields, portrait.imageKey],
+ );
+ const [records, setRecords] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [form, setForm] = useState(emptyForm);
+ const [saving, setSaving] = useState(false);
+ const { isConfirming: isConfirmingDelete, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
+ const [galleryOpen, setGalleryOpen] = useState(false);
+ const [startingGeneration, setStartingGeneration] = useState(false);
+ const [generationJobId, setGenerationJobId] = useState(null);
+ const generationRequestRef = useRef(0);
+ const hydratedRef = useRef(null);
+
+ const generation = useMediaJobProgress(generationJobId);
+ const isGenerating = startingGeneration || !!generationJobId;
+ const isCreate = selectedId === 'new';
+ const selected = useMemo(
+ () => (isCreate || !selectedId ? null : records.find((record) => record.id === selectedId) || null),
+ [records, selectedId, isCreate],
+ );
+ const notFound = !isCreate && !!selectedId && !loading && !selected;
+ const canGenerate = !!(form[portrait.descriptionKey]?.trim() || form[portrait.styleKey]?.trim());
+
+ const setImage = (url) => setForm((current) => ({ ...current, [portrait.imageKey]: url }));
+ const clearGeneration = () => {
+ generationRequestRef.current += 1;
+ setGenerationJobId(null);
+ setStartingGeneration(false);
+ };
+
+ useEffect(() => {
+ listRecords({ silent: true })
+ .then((list) => setRecords(Array.isArray(list) ? list : []))
+ .catch((err) => toast.error(err.message || `Failed to load ${plural.toLowerCase()}`))
+ .finally(() => setLoading(false));
+ }, [listRecords, plural]);
+
+ useEffect(() => {
+ if (!generationJobId) return;
+ if (generation.status === 'completed' && generation.filename) {
+ setForm((current) => ({
+ ...current,
+ [portrait.imageKey]: generation.path || `/data/images/${generation.filename}`,
+ }));
+ setGenerationJobId(null);
+ toast.success(`${portrait.label} generated`);
+ } else if (generation.status === 'failed' || generation.status === 'canceled') {
+ setGenerationJobId(null);
+ toast.error(generation.error || `${portrait.label} generation failed`);
+ }
+ }, [generationJobId, generation.status, generation.filename, generation.path, generation.error, portrait]);
+
+ useEffect(() => {
+ if (loading || hydratedRef.current === selectedId) return;
+ hydratedRef.current = selectedId;
+ cancelDelete();
+ clearGeneration();
+ if (isCreate) setForm(emptyForm);
+ else if (selected) {
+ setForm(Object.fromEntries(
+ [...fields.map(({ key }) => key), portrait.imageKey].map((key) => [key, selected[key] || '']),
+ ));
+ }
+ }, [selectedId, isCreate, selected, loading, emptyForm, fields, portrait.imageKey]);
+
+ const handleGenerate = async () => {
+ if (isGenerating) return;
+ if (!canGenerate) {
+ toast.error(`Add a physical description or ${portrait.styleLabel.toLowerCase()} to generate from`);
+ return;
+ }
+ const requestId = generationRequestRef.current;
+ setStartingGeneration(true);
+ const queued = await generateImage({
+ prompt: portrait.buildPrompt(form),
+ negativePrompt: `${DEFAULT_NEGATIVE_PROMPT}, extra limbs, nsfw, nude`,
+ width: 768,
+ height: 1024,
+ }, { silent: true }).catch((err) => ({ error: err }));
+ if (generationRequestRef.current !== requestId) return;
+ setStartingGeneration(false);
+ if (queued?.error) {
+ toast.error(queued.error.message || `${portrait.label} generation failed`);
+ return;
+ }
+ if (queued.jobId) {
+ setGenerationJobId(queued.jobId);
+ toast.success(`Generating ${portrait.label.toLowerCase()}…`);
+ return;
+ }
+ const path = queued.path || (queued.filename ? `/data/images/${queued.filename}` : '');
+ if (path) {
+ setImage(path);
+ toast.success(`${portrait.label} generated`);
+ } else {
+ toast.error(`${portrait.label} generation returned no image`);
+ }
+ };
+
+ const handleImagePick = (item) => {
+ setGalleryOpen(false);
+ const url = item?.previewUrl || (item?.filename ? `/data/images/${item.filename}` : '');
+ if (url) setImage(url);
+ };
+
+ const handleSave = async () => {
+ const name = form.name.trim();
+ if (!name) {
+ toast.error(`${singular} name is required`);
+ return;
+ }
+ setSaving(true);
+ const payload = { ...form, name };
+ const saved = await (isCreate
+ ? createRecord(payload, { silent: true })
+ : updateRecord(selectedId, payload, { silent: true }))
+ .catch((err) => {
+ toast.error(err.message || `Failed to ${isCreate ? 'create' : 'save'} ${singular.toLowerCase()}`);
+ return null;
+ });
+ setSaving(false);
+ if (!saved) return;
+ setRecords((current) => (isCreate
+ ? [...current, saved].sort(byName)
+ : current.map((record) => (record.id === saved.id ? saved : record)).sort(byName)));
+ if (isCreate) {
+ navigate(`${basePath}/${encodeURIComponent(saved.id)}`);
+ toast.success(`Created "${saved.name}"`);
+ } else {
+ toast.success('Saved');
+ }
+ };
+
+ const handleDelete = async () => {
+ if (!selected) return;
+ const prior = records;
+ setRecords((current) => current.filter((record) => record.id !== selected.id));
+ navigate(basePath);
+ await deleteRecord(selected.id, { silent: true }).catch((err) => {
+ toast.error(err.message || 'Delete failed');
+ setRecords(prior);
+ });
+ };
+
+ const introBlock = <p className="text-sm text-gray-400 max-w-2xl">{intro}</p>;
+
+ return (
+ <div>
+ {title ? (
+ <>
+ <div className="flex items-center justify-between mb-6 flex-wrap gap-3">
+ <div className="flex items-center gap-3">
+ {TitleIcon ? <TitleIcon className="w-6 h-6 text-port-accent" /> : null}
+ <h1 className="text-2xl font-bold text-white">{title}</h1>
+ </div>
+ <CreateButton singular={singular} onClick={() => navigate(`${basePath}/new`)} />
+ </div>
+ <div className="mb-6">{introBlock}</div>
+ </>
+ ) : (
+ <div className="flex items-center justify-between mb-4 flex-wrap gap-3">
+ {introBlock}
+ <CreateButton singular={singular} onClick={() => navigate(`${basePath}/new`)} />
+ </div>
+ )}
+
+ <div className="grid grid-cols-1 md:grid-cols-[260px_1fr] gap-4">
+ <div className="bg-port-card border border-port-border rounded-lg p-2">
+ {loading ? (
+ <div className="text-sm p-2"><BrailleSpinner text="Loading…" /></div>
+ ) : records.length === 0 ? (
+ <div className="text-gray-500 text-sm p-2">No {plural.toLowerCase()} yet. Click <span className="text-port-accent">New {singular}</span>.</div>
+ ) : (
+ <ul className="space-y-1">
+ {records.map((record) => (
+ <li key={record.id}>
+ <button
+ type="button"
+ onClick={() => navigate(`${basePath}/${encodeURIComponent(record.id)}`)}
+ className={`w-full text-left px-3 py-2 rounded text-sm truncate ${record.id === selectedId ? 'bg-port-accent/20 text-white' : 'text-gray-300 hover:bg-port-bg'}`}
+ >
+ {record.name}
+ {listSecondaryKey && record[listSecondaryKey] ? <span className="block text-[11px] text-gray-500 truncate">{record[listSecondaryKey]}</span> : null}
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+
+ <div className="bg-port-card border border-port-border rounded-lg p-4">
+ {notFound ? (
+ <div className="text-gray-500 text-sm">
+ That {singular.toLowerCase()} could not be found — it may have been deleted.{' '}
+ <button type="button" onClick={() => navigate(basePath)} className="text-port-accent hover:underline">Back to {plural.toLowerCase()}</button>
+ </div>
+ ) : !isCreate && !selected ? (
+ <div className="text-gray-500 text-sm">Select a {singular.toLowerCase()} to edit, or create a new one.</div>
+ ) : (
+ <div className="space-y-3">
+ {fields.map((field) => (
+ <Field key={field.key} compact label={field.label} hint={field.hint}>
+ {field.type === 'textarea' ? (
+ <textarea
+ value={form[field.key]}
+ onChange={(event) => setForm((current) => ({ ...current, [field.key]: event.target.value }))}
+ rows={field.rows}
+ maxLength={field.maxLength}
+ placeholder={field.placeholder}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
+ />
+ ) : (
+ <input
+ value={form[field.key]}
+ onChange={(event) => setForm((current) => ({ ...current, [field.key]: event.target.value }))}
+ placeholder={field.placeholder}
+ maxLength={field.maxLength}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ autoFocus={field.key === 'name'}
+ />
+ )}
+ </Field>
+ ))}
+
+ <Field compact label={portrait.fieldLabel} hint={portrait.hint}>
+ <div className="flex items-start gap-3">
+ {isGenerating ? (
+ <div className="relative w-20 h-20 rounded border border-port-border bg-port-bg overflow-hidden flex items-center justify-center shrink-0">
+ {generation.currentImage ? (
+ <img src={`data:image/png;base64,${generation.currentImage}`} alt={`Generating ${portrait.label.toLowerCase()} preview`} className="w-full h-full object-cover opacity-70" />
+ ) : <Loader2 size={20} className="animate-spin text-port-accent" aria-hidden="true" />}
+ {generation.totalSteps ? <div className="absolute bottom-0 inset-x-0 port-media-overlay text-[9px] text-center py-0.5 font-mono">{Math.round((generation.step / generation.totalSteps) * 100)}%</div> : null}
+ </div>
+ ) : form[portrait.imageKey] ? (
+ <div className="relative shrink-0">
+ <img src={form[portrait.imageKey]} alt={`${singular} ${portrait.label.toLowerCase()}`} className="w-20 h-20 rounded object-cover border border-port-border bg-port-bg" />
+ <button type="button" onClick={() => setImage('')} title={`Remove ${portrait.label.toLowerCase()}`} aria-label={`Remove ${portrait.label.toLowerCase()}`} className="absolute -top-2 -right-2 p-1 rounded-full bg-port-bg border border-port-border text-gray-400 hover:text-port-error"><X size={12} /></button>
+ </div>
+ ) : (
+ <div className="w-20 h-20 rounded border border-dashed border-port-border bg-port-bg flex items-center justify-center text-gray-600 shrink-0"><ImageIcon size={20} aria-hidden="true" /></div>
+ )}
+ <div className="flex-1 space-y-2">
+ <div className="flex items-center gap-2 flex-wrap">
+ <button type="button" onClick={handleGenerate} disabled={isGenerating || !canGenerate} title={canGenerate ? portrait.generateTitle : `Add a physical description or ${portrait.styleLabel.toLowerCase()} first`} className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50">
+ {isGenerating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />} Generate
+ </button>
+ <button type="button" onClick={() => setGalleryOpen(true)} disabled={isGenerating} title="Pick a gallery image, or upload one from this device" className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50"><ImageIcon size={14} /> Choose or upload</button>
+ </div>
+ <input aria-label={`${portrait.label} image URL`} value={form[portrait.imageKey]} onChange={(event) => setImage(event.target.value)} disabled={isGenerating} placeholder="/images/… or https://…" maxLength={portrait.maxLength} className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm disabled:opacity-50" />
+ </div>
+ </div>
+ </Field>
+
+ <div className="flex items-center gap-2 pt-1 flex-wrap">
+ <button type="button" onClick={handleSave} disabled={saving || !form.name.trim()} className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50">
+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />} {isCreate ? 'Create' : 'Save'}
+ </button>
+ {!isCreate && selected ? (
+ isConfirmingDelete(selected.id) ? (
+ <ConfirmButtonPair prompt={`Delete this ${singular.toLowerCase()}?`} confirmText="Yes, delete" ariaLabel={`Confirm delete ${singular.toLowerCase()}`} tone="error" onConfirm={() => confirmDelete(handleDelete)} onCancel={cancelDelete} />
+ ) : (
+ <button type="button" onClick={() => requestDelete(selected.id)} className="inline-flex items-center gap-2 px-3 py-2 rounded-lg text-gray-400 hover:text-port-error text-sm"><Trash2 size={14} /> Delete</button>
+ )
+ ) : null}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+
+ <GalleryImagePicker open={galleryOpen} onClose={() => setGalleryOpen(false)} onSelect={handleImagePick} allowUpload maxBytes={PERSONA_IMAGE_MAX_BYTES} />
+ </div>
+ );
+}
+
+function CreateButton({ singular, onClick }) {
+ return (
+ <button type="button" onClick={onClick} className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 text-white text-sm font-medium shrink-0">
+ <Plus size={16} aria-hidden="true" /> New {singular}
+ </button>
+ );
+}
diff --git a/client/src/pages/Authors.jsx b/client/src/pages/Authors.jsx
index dc6490899f..85723dcee3 100644
--- a/client/src/pages/Authors.jsx
+++ b/client/src/pages/Authors.jsx
@@ -1,463 +1,67 @@
-/**
- * Authors page — manage reusable author personas.
- *
- * An Author is a creative persona used as a series' cover byline and as the
- * prompt source for a book-cover author headshot. Each carries a name, writing
- * style, bio, a physical description + style direction for the headshot, and an
- * optional headshot image pointer.
- *
- * Master-detail: a selectable list on the left, an editor on the right. Picking
- * an author loads it into the editor; "New Author" opens a blank create form.
- */
-
-import { useEffect, useMemo, useRef, useState } from 'react';
-import { useNavigate, useParams } from 'react-router';
-import { FilePen, Plus, Loader2, Trash2, Save, ImageIcon, Sparkles, X } from 'lucide-react';
-import BrailleSpinner from '../components/BrailleSpinner';
-import toast from '../components/ui/Toast';
-import GalleryImagePicker from '../components/imageGen/GalleryImagePicker';
-import Field from '../components/ui/FormField';
-import useMediaJobProgress from '../hooks/useMediaJobProgress';
-import { DEFAULT_NEGATIVE_PROMPT } from '../lib/imageGenDefaults';
+import { FilePen } from 'lucide-react';
+import { useParams } from 'react-router';
+import PersonaMasterDetail from '../components/persona/PersonaMasterDetail';
import {
listAuthors, createAuthor, updateAuthor, deleteAuthor, generateImage,
AUTHOR_NAME_MAX, AUTHOR_WRITING_STYLE_MAX, AUTHOR_BIO_MAX,
AUTHOR_PHYSICAL_DESCRIPTION_MAX, AUTHOR_HEADSHOT_STYLE_MAX, AUTHOR_HEADSHOT_IMAGE_URL_MAX,
} from '../services/api';
-// Cap headshot uploads so the base64 round-trip stays small — a cover headshot
-// never needs more than a few MB. Enforced by GalleryImagePicker's `maxBytes`.
-const HEADSHOT_MAX_BYTES = 12 * 1024 * 1024;
-
-const emptyForm = () => ({
- name: '', writingStyle: '', bio: '', physicalDescription: '', headshotStyle: '', headshotImageUrl: '',
-});
-
-const formFromAuthor = (a) => ({
- name: a.name || '',
- writingStyle: a.writingStyle || '',
- bio: a.bio || '',
- physicalDescription: a.physicalDescription || '',
- headshotStyle: a.headshotStyle || '',
- headshotImageUrl: a.headshotImageUrl || '',
-});
-
-// Build the image-gen prompt for an author headshot from the persona's
-// physical description (the subject) and headshot style (the art direction).
-// Either field alone is enough to render; both are folded into one prompt.
-const buildHeadshotPrompt = (f) => {
- const desc = (f.physicalDescription || '').trim();
- const style = (f.headshotStyle || '').trim();
- const subject = desc ? `Author headshot portrait. ${desc}` : 'Professional author headshot portrait.';
- return style ? `${subject} ${style}` : subject;
+const FIELDS = [
+ { key: 'name', label: 'Name', placeholder: 'Jane Doe', maxLength: AUTHOR_NAME_MAX },
+ {
+ key: 'writingStyle', label: 'Writing style', type: 'textarea', rows: 4,
+ hint: 'Voice / tone / craft notes — fed into stage prompts.',
+ placeholder: 'Spare, noir-tinged prose; short declarative sentences; dry wit.', maxLength: AUTHOR_WRITING_STYLE_MAX,
+ },
+ {
+ key: 'bio', label: 'Bio', type: 'textarea', rows: 4,
+ hint: 'About-the-author blurb for the back cover.', placeholder: 'Jane Doe is the author of…', maxLength: AUTHOR_BIO_MAX,
+ },
+ {
+ key: 'physicalDescription', label: 'Physical description', type: 'textarea', rows: 3,
+ hint: 'Subject of the cover headshot — appearance, age, expression.',
+ placeholder: 'Woman in her 40s, silver-streaked dark hair, warm gaze, slight smile.', maxLength: AUTHOR_PHYSICAL_DESCRIPTION_MAX,
+ },
+ {
+ key: 'headshotStyle', label: 'Headshot style', type: 'textarea', rows: 3,
+ hint: 'Art / photography direction for the headshot render.',
+ placeholder: 'Studio portrait, soft Rembrandt lighting, muted background, 85mm.', maxLength: AUTHOR_HEADSHOT_STYLE_MAX,
+ },
+];
+
+const PORTRAIT = {
+ label: 'Headshot', fieldLabel: 'Headshot image', imageKey: 'headshotImageUrl',
+ descriptionKey: 'physicalDescription', styleKey: 'headshotStyle', styleLabel: 'Headshot style',
+ maxLength: AUTHOR_HEADSHOT_IMAGE_URL_MAX,
+ hint: 'Optional — generate from the description + style, choose or upload one via the gallery, or paste a URL. Used on covers.',
+ generateTitle: 'Generate a headshot from the description + style',
+ buildPrompt: (form) => {
+ const description = form.physicalDescription.trim();
+ const style = form.headshotStyle.trim();
+ const subject = description ? `Author headshot portrait. ${description}` : 'Professional author headshot portrait.';
+ return style ? `${subject} ${style}` : subject;
+ },
};
export default function Authors() {
- const navigate = useNavigate();
- // Selection lives in the URL (`/authors/:authorId`, `/authors/new`) so it's
- // deep-linkable, reload-safe, and reachable from ⌘K/voice. `authorId === 'new'`
- // is create mode; a real id is edit mode; absent is idle.
const { authorId } = useParams();
- const [authors, setAuthors] = useState([]);
- const [loading, setLoading] = useState(true);
- const [form, setForm] = useState(emptyForm);
- const [saving, setSaving] = useState(false);
- const [confirmDelete, setConfirmDelete] = useState(false);
- const [galleryOpen, setGalleryOpen] = useState(false);
- // Headshot generation: `startingGen` covers the request round-trip before a
- // jobId exists; `genJobId` tracks an async (local/codex) render until it
- // completes. External SD-API renders synchronously and never sets genJobId.
- const [startingGen, setStartingGen] = useState(false);
- const [genJobId, setGenJobId] = useState(null);
- // Bumped on every author switch / new-author. A generate request captures
- // this before its POST and bails if it changed by the time the POST resolves
- // — closes the pre-jobId round-trip window where `clearGeneration` alone
- // can't stop a stale response from writing the wrong persona's headshot.
- const genRequestRef = useRef(0);
-
- const gen = useMediaJobProgress(genJobId);
- const isGenerating = startingGen || !!genJobId;
-
- const setHeadshot = (url) => setForm((f) => ({ ...f, headshotImageUrl: url }));
- // Drop any in-flight render so its completion can't write the wrong author.
- const clearGeneration = () => { genRequestRef.current += 1; setGenJobId(null); setStartingGen(false); };
-
- // Land the finished async render into the form, or surface a failure. Cleared
- // genJobId on author switch (see selectAuthor/startCreate) prevents a stale
- // render from writing the wrong author's headshot.
- useEffect(() => {
- if (!genJobId) return;
- if (gen.status === 'completed' && gen.filename) {
- setHeadshot(gen.path || `/data/images/${gen.filename}`);
- setGenJobId(null);
- toast.success('Headshot generated');
- } else if (gen.status === 'failed' || gen.status === 'canceled') {
- setGenJobId(null);
- toast.error(gen.error || 'Headshot generation failed');
- }
- }, [genJobId, gen.status, gen.filename, gen.path, gen.error]);
-
- const handleGenerateHeadshot = async () => {
- if (isGenerating) return;
- if (!form.physicalDescription.trim() && !form.headshotStyle.trim()) {
- toast.error('Add a physical description or headshot style to generate from');
- return;
- }
- const requestId = genRequestRef.current;
- setStartingGen(true);
- // `silent: true` — this catch owns the error toast, so suppress the
- // apiCore `request()` helper's default toast to avoid firing two.
- const queued = await generateImage({
- prompt: buildHeadshotPrompt(form),
- // Shared base plus portrait-specific guards (people-only artifacts).
- negativePrompt: `${DEFAULT_NEGATIVE_PROMPT}, extra limbs, nsfw, nude`,
- width: 768,
- height: 1024,
- }, { silent: true }).catch((err) => ({ error: err }));
- // Superseded by an author switch during the POST round-trip — clearGeneration
- // already reset state; drop this response so it can't land on the new author.
- if (genRequestRef.current !== requestId) return;
- setStartingGen(false);
- if (queued?.error) {
- toast.error(queued.error.message || 'Headshot generation failed');
- return;
- }
- if (queued.jobId) {
- // Async backend — track progress until the job completes.
- setGenJobId(queued.jobId);
- toast.success('Generating headshot…');
- return;
- }
- // Synchronous backend (external SD-API) returns the finished image directly.
- const path = queued.path || (queued.filename ? `/data/images/${queued.filename}` : '');
- if (path) {
- setHeadshot(path);
- toast.success('Headshot generated');
- } else {
- toast.error('Headshot generation returned no image');
- }
- };
-
- // Both "pick an existing gallery image" and "upload one from disk" land here —
- // GalleryImagePicker's `allowUpload` owns the read + POST and hands back the
- // saved image already normalized (issue #4127).
- const handleHeadshotPick = (item) => {
- setGalleryOpen(false);
- const url = item?.previewUrl || (item?.filename ? `/data/images/${item.filename}` : '');
- if (url) setHeadshot(url);
- };
-
- useEffect(() => {
- listAuthors({ silent: true })
- .then((list) => setAuthors(Array.isArray(list) ? list : []))
- .catch((err) => toast.error(err.message || 'Failed to load authors'))
- .finally(() => setLoading(false));
- }, []);
-
- const isCreate = authorId === 'new';
- const selected = useMemo(
- () => (isCreate || !authorId ? null : authors.find((a) => a.id === authorId) || null),
- [authors, authorId, isCreate],
- );
- // A real id that isn't in the loaded list (deleted / bad deep link) → not-found.
- const notFound = !isCreate && !!authorId && !loading && !selected;
- // A headshot render needs at least a subject or an art-direction prompt.
- const canGenerate = !!(form.physicalDescription.trim() || form.headshotStyle.trim());
-
- const selectAuthor = (a) => navigate(`/authors/${encodeURIComponent(a.id)}`);
- const startCreate = () => navigate('/authors/new');
-
- // Hydrate the editor form from the URL-selected author. Keyed on the id so a
- // list refresh (create/update/delete mutating `authors`) doesn't clobber the
- // open form; `hydratedRef` tracks which selection is already loaded. Resets
- // (confirm-delete + any in-flight generation) run for EVERY selection change —
- // including navigating to the idle index or a stale id — so a stray render
- // can't land on the previous author after you've moved on.
- const hydratedRef = useRef(null);
- const selectionKey = authorId ?? null;
- useEffect(() => {
- if (loading) return;
- if (hydratedRef.current === selectionKey) return;
- hydratedRef.current = selectionKey;
- setConfirmDelete(false);
- clearGeneration();
- if (isCreate) setForm(emptyForm());
- else if (selected) setForm(formFromAuthor(selected));
- // else: idle / not-found — leave the form; the fallback UI handles it.
- }, [selectionKey, isCreate, selected, loading]);
-
- const handleSave = async () => {
- const name = form.name.trim();
- if (!name) { toast.error('Author name is required'); return; }
- setSaving(true);
- const payload = { ...form, name };
- if (isCreate) {
- const created = await createAuthor(payload, { silent: true }).catch((err) => {
- toast.error(err.message || 'Failed to create author');
- return null;
- });
- setSaving(false);
- if (!created) return;
- setAuthors((prev) => [...prev, created].sort((a, b) => (a.name || '').localeCompare(b.name || '')));
- navigate(`/authors/${encodeURIComponent(created.id)}`);
- toast.success(`Created "${created.name}"`);
- } else {
- const updated = await updateAuthor(authorId, payload, { silent: true }).catch((err) => {
- toast.error(err.message || 'Failed to save author');
- return null;
- });
- setSaving(false);
- if (!updated) return;
- setAuthors((prev) => prev
- .map((a) => (a.id === updated.id ? updated : a))
- .sort((a, b) => (a.name || '').localeCompare(b.name || '')));
- toast.success('Saved');
- }
- };
-
- const handleDelete = async () => {
- if (!selected) return;
- const prior = authors;
- setAuthors((prev) => prev.filter((a) => a.id !== selected.id));
- setConfirmDelete(false);
- navigate('/authors');
- await deleteAuthor(selected.id, { silent: true }).catch((err) => {
- toast.error(err.message || 'Delete failed');
- setAuthors(prior);
- });
- };
-
return (
- <div>
- <div className="flex items-center justify-between mb-6 flex-wrap gap-3">
- <div className="flex items-center gap-3">
- <FilePen className="w-6 h-6 text-port-accent" />
- <h1 className="text-2xl font-bold text-white">Authors</h1>
- </div>
- <button
- type="button"
- onClick={startCreate}
- className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 text-white text-sm font-medium"
- >
- <Plus size={16} aria-hidden="true" />
- New Author
- </button>
- </div>
-
- <p className="text-sm text-gray-400 mb-6">
- Author personas are reusable across series — the cover byline plus the writing voice, bio, and the
- physical description + style used to generate a book-cover author headshot. Link one to a series from
- the Series Pipeline.
- </p>
-
- <div className="grid grid-cols-1 md:grid-cols-[260px_1fr] gap-4">
- <div className="bg-port-card border border-port-border rounded-lg p-2">
- {loading ? (
- <div className="text-sm p-2"><BrailleSpinner text="Loading…" /></div>
- ) : authors.length === 0 ? (
- <div className="text-gray-500 text-sm p-2">No authors yet. Click <span className="text-port-accent">New Author</span>.</div>
- ) : (
- <ul className="space-y-1">
- {authors.map((a) => (
- <li key={a.id}>
- <button
- type="button"
- onClick={() => selectAuthor(a)}
- className={`w-full text-left px-3 py-2 rounded text-sm truncate ${
- a.id === authorId ? 'bg-port-accent/20 text-white' : 'text-gray-300 hover:bg-port-bg'
- }`}
- >
- {a.name}
- </button>
- </li>
- ))}
- </ul>
- )}
- </div>
-
- <div className="bg-port-card border border-port-border rounded-lg p-4">
- {notFound ? (
- <div className="text-gray-500 text-sm">
- That author could not be found — it may have been deleted.{' '}
- <button type="button" onClick={() => navigate('/authors')} className="text-port-accent hover:underline">
- Back to authors
- </button>
- </div>
- ) : !isCreate && !selected ? (
- <div className="text-gray-500 text-sm">Select an author to edit, or create a new one.</div>
- ) : (
- <div className="space-y-3">
- <Field compact label="Name">
- <input
- value={form.name}
- onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
- placeholder="Jane Doe"
- maxLength={AUTHOR_NAME_MAX}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
- autoFocus
- />
- </Field>
- <Field compact label="Writing style" hint="Voice / tone / craft notes — fed into stage prompts.">
- <textarea
- value={form.writingStyle}
- onChange={(e) => setForm((f) => ({ ...f, writingStyle: e.target.value }))}
- rows={4}
- maxLength={AUTHOR_WRITING_STYLE_MAX}
- placeholder="Spare, noir-tinged prose; short declarative sentences; dry wit."
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
- />
- </Field>
- <Field compact label="Bio" hint="About-the-author blurb for the back cover.">
- <textarea
- value={form.bio}
- onChange={(e) => setForm((f) => ({ ...f, bio: e.target.value }))}
- rows={4}
- maxLength={AUTHOR_BIO_MAX}
- placeholder="Jane Doe is the author of…"
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
- />
- </Field>
- <Field compact label="Physical description" hint="Subject of the cover headshot — appearance, age, expression.">
- <textarea
- value={form.physicalDescription}
- onChange={(e) => setForm((f) => ({ ...f, physicalDescription: e.target.value }))}
- rows={3}
- maxLength={AUTHOR_PHYSICAL_DESCRIPTION_MAX}
- placeholder="Woman in her 40s, silver-streaked dark hair, warm gaze, slight smile."
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
- />
- </Field>
- <Field compact label="Headshot style" hint="Art / photography direction for the headshot render.">
- <textarea
- value={form.headshotStyle}
- onChange={(e) => setForm((f) => ({ ...f, headshotStyle: e.target.value }))}
- rows={3}
- maxLength={AUTHOR_HEADSHOT_STYLE_MAX}
- placeholder="Studio portrait, soft Rembrandt lighting, muted background, 85mm."
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
- />
- </Field>
- <Field compact label="Headshot image" hint="Optional — generate from the description + style, choose or upload one via the gallery, or paste a URL. Used on covers.">
- <div className="flex items-start gap-3">
- {isGenerating ? (
- <div className="relative w-20 h-20 rounded border border-port-border bg-port-bg overflow-hidden flex items-center justify-center shrink-0">
- {gen.currentImage ? (
- <img
- src={`data:image/png;base64,${gen.currentImage}`}
- alt="Generating headshot preview"
- className="w-full h-full object-cover opacity-70"
- />
- ) : (
- <Loader2 size={20} className="animate-spin text-port-accent" aria-hidden="true" />
- )}
- {gen.totalSteps ? (
- <div className="absolute bottom-0 inset-x-0 bg-black/60 text-[9px] text-white text-center py-0.5 font-mono">
- {Math.round((gen.step / gen.totalSteps) * 100)}%
- </div>
- ) : null}
- </div>
- ) : form.headshotImageUrl ? (
- <div className="relative shrink-0">
- <img
- src={form.headshotImageUrl}
- alt="Author headshot"
- className="w-20 h-20 rounded object-cover border border-port-border bg-port-bg"
- />
- <button
- type="button"
- onClick={() => setHeadshot('')}
- title="Remove headshot" aria-label="Remove headshot"
- className="absolute -top-2 -right-2 p-1 rounded-full bg-port-bg border border-port-border text-gray-400 hover:text-port-error"
- >
- <X size={12} />
- </button>
- </div>
- ) : (
- <div className="w-20 h-20 rounded border border-dashed border-port-border bg-port-bg flex items-center justify-center text-gray-600 shrink-0">
- <ImageIcon size={20} aria-hidden="true" />
- </div>
- )}
- <div className="flex-1 space-y-2">
- <div className="flex items-center gap-2 flex-wrap">
- <button
- type="button"
- onClick={handleGenerateHeadshot}
- disabled={isGenerating || !canGenerate}
- title={canGenerate
- ? 'Generate a headshot from the description + style'
- : 'Add a physical description or headshot style first'}
- className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50"
- >
- {isGenerating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
- Generate
- </button>
- <button
- type="button"
- onClick={() => setGalleryOpen(true)}
- disabled={isGenerating}
- title="Pick a gallery image, or upload one from this device"
- className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50"
- >
- <ImageIcon size={14} /> Choose or upload
- </button>
- </div>
- <input
- aria-label="Headshot image URL"
- value={form.headshotImageUrl}
- onChange={(e) => setHeadshot(e.target.value)}
- disabled={isGenerating}
- placeholder="/images/… or https://…"
- maxLength={AUTHOR_HEADSHOT_IMAGE_URL_MAX}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm disabled:opacity-50"
- />
- </div>
- </div>
- </Field>
-
- <div className="flex items-center gap-2 pt-1 flex-wrap">
- <button
- type="button"
- onClick={handleSave}
- disabled={saving || !form.name.trim()}
- className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"
- >
- {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
- {isCreate ? 'Create' : 'Save'}
- </button>
- {!isCreate && selected ? (
- confirmDelete ? (
- <span className="inline-flex items-center gap-2 text-sm">
- <span className="text-port-error">Delete this author?</span>
- <button type="button" onClick={handleDelete} className="px-2 py-1 rounded bg-port-error/20 text-port-error hover:bg-port-error/30">
- Yes, delete
- </button>
- <button type="button" onClick={() => setConfirmDelete(false)} className="px-2 py-1 rounded text-gray-400 hover:text-white">
- Cancel
- </button>
- </span>
- ) : (
- <button
- type="button"
- onClick={() => setConfirmDelete(true)}
- className="inline-flex items-center gap-2 px-3 py-2 rounded-lg text-gray-400 hover:text-port-error text-sm"
- >
- <Trash2 size={14} /> Delete
- </button>
- )
- ) : null}
- </div>
- </div>
- )}
- </div>
- </div>
-
- <GalleryImagePicker
- open={galleryOpen}
- onClose={() => setGalleryOpen(false)}
- onSelect={handleHeadshotPick}
- allowUpload
- maxBytes={HEADSHOT_MAX_BYTES}
- />
- </div>
+ <PersonaMasterDetail
+ basePath="/authors"
+ selectedId={authorId}
+ title="Authors"
+ titleIcon={FilePen}
+ intro="Author personas are reusable across series — the cover byline plus the writing voice, bio, and the physical description + style used to generate a book-cover author headshot. Link one to a series from the Series Pipeline."
+ singular="Author"
+ plural="Authors"
+ fields={FIELDS}
+ portrait={PORTRAIT}
+ listRecords={listAuthors}
+ createRecord={createAuthor}
+ updateRecord={updateAuthor}
+ deleteRecord={deleteAuthor}
+ generateImage={generateImage}
+ />
);
}