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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: collapse the writers-room bible trio into a shared BibleSection
[._.]/ Adam Eivy852455461794
diff --git a/client/src/components/music/AlbumsManager.jsx b/client/src/components/music/AlbumsManager.jsxindex 2b8030a1bc..338ab39844 100644--- a/client/src/components/music/AlbumsManager.jsx+++ b/client/src/components/music/AlbumsManager.jsx@@ -14,7 +14,9 @@ import { Plus, Loader2, Trash2, Save, Upload, ImageIcon, Sparkles, X, ArrowUp, Aimport toast from '../ui/Toast';import FilePickerButton from '../ui/FilePickerButton';import GalleryImagePicker from '../imageGen/GalleryImagePicker';+import ConfirmButtonPair from '../ui/ConfirmButtonPair';import useMediaJobProgress from '../../hooks/useMediaJobProgress';+import { useConfirmDelete } from '../../hooks/useConfirmDelete';import { DEFAULT_NEGATIVE_PROMPT } from '../../lib/imageGenDefaults';import { readFileAsBase64 } from '../../utils/fileUpload';import { formatTimecode } from '../../utils/formatters';@@ -76,7 +78,7 @@ export default function AlbumsManager() {const [loading, setLoading] = useState(true);const [form, setForm] = useState(emptyForm);const [saving, setSaving] = useState(false);- const [confirmDelete, setConfirmDelete] = useState(false);+ const { isConfirming: isConfirmingDelete, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();const [galleryOpen, setGalleryOpen] = useState(false);const [uploadingCover, setUploadingCover] = useState(false);const [startingGen, setStartingGen] = useState(false);@@ -135,7 +137,7 @@ export default function AlbumsManager() {if (loading) return;if (hydratedRef.current === selectionKey) return;hydratedRef.current = selectionKey;- setConfirmDelete(false);+ cancelDelete();clearGeneration();if (isCreate) setForm(emptyForm());else if (selected) setForm(formFromAlbum(selected));@@ -245,7 +247,6 @@ export default function AlbumsManager() {if (!selected) return;const prior = albums;setAlbums((prev) => prev.filter((a) => a.id !== selected.id));- setConfirmDelete(false);navigate('/music/albums');await deleteAlbum(selected.id, { silent: true }).catch((err) => { toast.error(err.message || 'Delete failed'); setAlbums(prior); });};@@ -411,14 +412,17 @@ export default function AlbumsManager() {{isCreate ? 'Create' : 'Save'}</button>{!isCreate && selected ? (- confirmDelete ? (- <span className="inline-flex items-center gap-2 text-sm">- <span className="text-port-error">Delete this album?</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>+ isConfirmingDelete(selected.id) ? (+ <ConfirmButtonPair+ prompt="Delete this album?"+ confirmText="Yes, delete"+ ariaLabel="Confirm delete album"+ tone="error"+ onConfirm={() => confirmDelete(handleDelete)}+ onCancel={cancelDelete}+ />) : (- <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">+ <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>)diff --git a/client/src/components/music/ArtistsManager.jsx b/client/src/components/music/ArtistsManager.jsxindex 1779338f88..69e7c4a2f4 100644--- a/client/src/components/music/ArtistsManager.jsx+++ b/client/src/components/music/ArtistsManager.jsx@@ -13,7 +13,9 @@ import { Plus, Loader2, Trash2, Save, Upload, ImageIcon, Sparkles, X } from 'lucimport toast from '../ui/Toast';import FilePickerButton from '../ui/FilePickerButton';import GalleryImagePicker from '../imageGen/GalleryImagePicker';+import ConfirmButtonPair from '../ui/ConfirmButtonPair';import useMediaJobProgress from '../../hooks/useMediaJobProgress';+import { useConfirmDelete } from '../../hooks/useConfirmDelete';import { DEFAULT_NEGATIVE_PROMPT } from '../../lib/imageGenDefaults';import { readFileAsBase64 } from '../../utils/fileUpload';import {@@ -69,7 +71,7 @@ export default function ArtistsManager() {const [loading, setLoading] = useState(true);const [form, setForm] = useState(emptyForm);const [saving, setSaving] = useState(false);- const [confirmDelete, setConfirmDelete] = useState(false);+ const { isConfirming: isConfirmingDelete, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();const [galleryOpen, setGalleryOpen] = useState(false);const [uploadingPortrait, setUploadingPortrait] = useState(false);const [startingGen, setStartingGen] = useState(false);@@ -188,7 +190,7 @@ export default function ArtistsManager() {if (loading) return;if (hydratedRef.current === selectionKey) return;hydratedRef.current = selectionKey;- setConfirmDelete(false);+ cancelDelete();clearGeneration();if (isCreate) setForm(emptyForm());else if (selected) setForm(formFromArtist(selected));@@ -227,7 +229,6 @@ export default function ArtistsManager() {if (!selected) return;const prior = artists;setArtists((prev) => prev.filter((a) => a.id !== selected.id));- setConfirmDelete(false);navigate('/music/artists');await deleteArtist(selected.id, { silent: true }).catch((err) => {toast.error(err.message || 'Delete failed');@@ -445,20 +446,19 @@ export default function ArtistsManager() {{isCreate ? 'Create' : 'Save'}</button>{!isCreate && selected ? (- confirmDelete ? (- <span className="inline-flex items-center gap-2 text-sm">- <span className="text-port-error">Delete this artist?</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>+ isConfirmingDelete(selected.id) ? (+ <ConfirmButtonPair+ prompt="Delete this artist?"+ confirmText="Yes, delete"+ ariaLabel="Confirm delete artist"+ tone="error"+ onConfirm={() => confirmDelete(handleDelete)}+ onCancel={cancelDelete}+ />) : (<buttontype="button"- onClick={() => setConfirmDelete(true)}+ 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} /> Deletediff --git a/client/src/components/music/TracksManager.jsx b/client/src/components/music/TracksManager.jsxindex ceac5f5653..738b7c2a74 100644--- a/client/src/components/music/TracksManager.jsx+++ b/client/src/components/music/TracksManager.jsx@@ -17,6 +17,8 @@ import { Link, useNavigate, useParams } from 'react-router';import { Plus, Loader2, Trash2, Save, Upload, Music2, Library } from 'lucide-react';import toast from '../ui/Toast';import FilePickerButton from '../ui/FilePickerButton';+import ConfirmButtonPair from '../ui/ConfirmButtonPair';+import { useConfirmDelete } from '../../hooks/useConfirmDelete';import { formatTimecode } from '../../utils/formatters';import ArtistPicker from './ArtistPicker';import MusicGenPanel from './MusicGenPanel';@@ -69,7 +71,7 @@ export default function TracksManager() {const [loading, setLoading] = useState(true);const [form, setForm] = useState(emptyForm);const [saving, setSaving] = useState(false);- const [confirmDelete, setConfirmDelete] = useState(false);+ const { isConfirming: isConfirmingDelete, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();const [uploading, setUploading] = useState(false);const [libraryOpen, setLibraryOpen] = useState(false);const [library, setLibrary] = useState([]);@@ -123,7 +125,7 @@ export default function TracksManager() {// NEWLY selected track (the action handlers read persisted?.id), sending the// old render's id to the wrong track.const resetTrackViewState = () => {- setConfirmDelete(false);+ cancelDelete();setLibraryOpen(false);setModalRender(null);setRemix(null);@@ -616,14 +618,17 @@ export default function TracksManager() {{isCreate ? 'Create' : 'Save'}</button>{!isCreate && selected ? (- confirmDelete ? (- <span className="inline-flex items-center gap-2 text-sm">- <span className="text-port-error">Delete this track?</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>+ isConfirmingDelete(selected.id) ? (+ <ConfirmButtonPair+ prompt="Delete this track?"+ confirmText="Yes, delete"+ ariaLabel="Confirm delete track"+ tone="error"+ onConfirm={() => confirmDelete(handleDelete)}+ onCancel={cancelDelete}+ />) : (- <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">+ <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>)diff --git a/client/src/components/music/TracksManager.test.jsx b/client/src/components/music/TracksManager.test.jsxindex 9086710575..725a441b8a 100644--- a/client/src/components/music/TracksManager.test.jsx+++ b/client/src/components/music/TracksManager.test.jsx@@ -1,4 +1,4 @@-import { render, screen, cleanup, fireEvent } from '@testing-library/react';+import { render, screen, cleanup, fireEvent, waitFor, within } from '@testing-library/react';import { MemoryRouter, Routes, Route } from 'react-router';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -31,7 +31,7 @@ vi.mock('../../services/api', () => ({vi.mock('../../services/apiMusicVideo.js', () => ({ listMusicVideoProjects: vi.fn() }));import TracksManager from './TracksManager.jsx';-import { listTracks, listAlbums, createTrack } from '../../services/api';+import { listTracks, listAlbums, createTrack, deleteTrack, updateTrack } from '../../services/api';import { listMusicVideoProjects } from '../../services/apiMusicVideo.js';const TRACK = { id: 'track-1', title: 'Example Song', audioFilename: 'example.mp3', renders: [] };@@ -159,3 +159,79 @@ describe('<TracksManager> generator mode toggle', () => {expect(screen.queryByTestId('chiptune-panel')).toBeNull();});});++// ConfirmButtonPair delete wiring (via useConfirmDelete) and the field-edit+// save path. The hook's own arm/disarm mechanics are unit-tested in+// useConfirmDelete.test.jsx; this covers TracksManager's INTEGRATION of it —+// that the trash button arms without calling the API, that the confirm/cancel+// buttons it renders drive deleteTrack with the exact track id (or not at+// all), and that a field edit reaches updateTrack with the exact payload.+describe('<TracksManager> delete confirm + save wiring', () => {+ beforeEach(() => {+ listTracks.mockResolvedValue([TRACK]);+ listAlbums.mockResolvedValue([]);+ listMusicVideoProjects.mockResolvedValue([]);+ });+ afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ });++ it('arms on the first click with no API call, then confirms with the exact track id', async () => {+ deleteTrack.mockResolvedValue({});+ renderAt('track-1');+ await screen.findByDisplayValue('Example Song');++ fireEvent.click(screen.getByRole('button', { name: /delete/i }));++ // Armed: the confirm pair replaces the trash button; no delete fired yet.+ const confirmGroup = await screen.findByRole('group', { name: 'Confirm delete track' });+ expect(within(confirmGroup).getByText('Delete this track?')).toBeInTheDocument();+ expect(deleteTrack).not.toHaveBeenCalled();++ fireEvent.click(within(confirmGroup).getByRole('button', { name: 'Yes, delete' }));++ expect(deleteTrack).toHaveBeenCalledTimes(1);+ expect(deleteTrack).toHaveBeenCalledWith('track-1', { silent: true });+ });++ it('disarms on Cancel without ever calling deleteTrack', async () => {+ renderAt('track-1');+ await screen.findByDisplayValue('Example Song');++ fireEvent.click(screen.getByRole('button', { name: /delete/i }));+ const confirmGroup = await screen.findByRole('group', { name: 'Confirm delete track' });++ fireEvent.click(within(confirmGroup).getByRole('button', { name: 'Cancel' }));++ // Disarmed: back to the plain trash button, confirm pair gone.+ expect(screen.queryByRole('group', { name: 'Confirm delete track' })).toBeNull();+ expect(screen.getByRole('button', { name: /delete/i })).toBeInTheDocument();+ expect(deleteTrack).not.toHaveBeenCalled();+ });++ it('saves an edited title with the exact update payload', async () => {+ updateTrack.mockResolvedValue({ ...TRACK, title: 'Example Song Updated' });+ renderAt('track-1');+ const titleInput = await screen.findByDisplayValue('Example Song');++ fireEvent.change(titleInput, { target: { value: 'Example Song Updated' } });+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(updateTrack).toHaveBeenCalledTimes(1));+ // `albumId` is dropped when unchanged from the loaded track (see+ // TracksManager's handleSave) — the exact-shape assertion pins that too.+ expect(updateTrack).toHaveBeenCalledWith(+ 'track-1',+ {+ title: 'Example Song Updated',+ artistId: '',+ artist: '',+ lyrics: '',+ prompt: '',+ audioFilename: 'example.mp3',+ },+ { silent: true },+ );+ });+});diff --git a/client/src/components/writers-room/BibleSection.jsx b/client/src/components/writers-room/BibleSection.jsxnew file mode 100644index 0000000000..6359741f94--- /dev/null+++ b/client/src/components/writers-room/BibleSection.jsx@@ -0,0 +1,307 @@+import { useEffect, useState } from 'react';+import { AlertTriangle, Check, Loader2, Pencil, Plus, Trash2, X } from 'lucide-react';+import toast from '../ui/Toast';+import useMounted from '../../hooks/useMounted';++// Shared implementation behind ObjectsBible / PlacesBible / CharactersBible —+// three near-identical editable "bible" lists (recurring objects, world+// locations, characters) that persist across analysis runs and feed+// image-gen prompts. Each kind differs only in field config, icon, copy, and+// a couple of row-header/title quirks — everything else (controlled vs.+// uncontrolled list state, fetch-on-mount, upsert/removeOne with+// sort-on-write, Row + Editor shells, inputCls, toast handling) lives here.+//+// `config` (per kind, built by the thin ObjectsBible.jsx / PlacesBible.jsx /+// CharactersBible.jsx wrappers) shape:+// noun, icon, iconClassName — row icon (icon may be null)+// countLabel(n) — text under the header ("N objects · …")+// emptyText — shown when the list is empty+// editButtonTitle — title="" on the row's edit button+// primary: { key, label, placeholder, inputExtraClass, autoFocus, trim }+// — the bare identity input (object/character name, place slugline)+// fields: [{ key, label, placeholder, kind: 'text'|'csv'|'multiline', rows, trim }]+// — every other editable field, rendered in order in the Editor+// bodyField, bodyEmptyText — the row's primary description line+// detailBlocks: [{ key, label, marginClass }] — extra "Label: value" lines+// blanksExcludeKeys — fields skipped by the "Missing: …" warning+// renderTitle(item, { light }) — row title JSX+// renderHeaderExtras(item) — badges after the title (aka/role/era/ai…)+// getDisplayName(item) — used in toasts + edit-button aria-label+// getSortKey(item) — list sort comparator key+// validate(draft) — returns an error string, or null+// api: { list, create, update, remove }+export function BibleAiBadge() {+ return (+ <span className="text-[9px] text-gray-500" title="Created by AI extraction — edit to mark as user-curated">+ ai+ </span>+ );+}++export default function BibleSection({ workId, items: itemsProp, onItemsChange, readingTheme = 'dark', hotRefId = null, config }) {+ const [internalItems, setInternalItems] = useState(itemsProp || []);+ const items = itemsProp ?? internalItems;+ const [editingId, setEditingId] = useState(null);+ const [creating, setCreating] = useState(false);+ const [loading, setLoading] = useState(false);+ const mountedRef = useMounted();++ useEffect(() => {+ if (itemsProp) return;+ if (!workId) return;+ setLoading(true);+ config.api.list(workId)+ .then((list) => { if (mountedRef.current) setInternalItems(list); })+ .catch(() => { if (mountedRef.current) setInternalItems([]); })+ .finally(() => { if (mountedRef.current) setLoading(false); });+ }, [workId, itemsProp, mountedRef]);++ // Internal state uses a functional updater so back-to-back saves (the add+ // form and a row editor can both be open) each merge against the freshest+ // list. The onItemsChange callback stays outside the updater (side effects+ // in updaters double-fire under StrictMode) and receives the view computed+ // from the current merged snapshot, as before.+ const upsert = (record) => {+ const sorted = (arr) => arr.sort((a, b) => config.getSortKey(a).localeCompare(config.getSortKey(b)));+ const merge = (arr) => {+ const idx = arr.findIndex((it) => it.id === record.id);+ return idx < 0+ ? sorted([...arr, record])+ : sorted(arr.map((it, i) => (i === idx ? record : it)));+ };+ setInternalItems((prev) => merge(prev));+ onItemsChange?.(merge(items));+ };++ const removeOne = (id) => {+ setInternalItems((prev) => prev.filter((it) => it.id !== id));+ onItemsChange?.(items.filter((it) => it.id !== id));+ };++ return (+ <div className="text-xs">+ <div className="flex items-center justify-between mb-2">+ <div className="text-[11px] text-gray-500">{config.countLabel(items.length)}</div>+ <button+ onClick={() => { setCreating(true); setEditingId(null); }}+ className="flex items-center gap-1 text-[11px] text-gray-400 hover:text-port-accent"+ >+ <Plus size={12} /> Add+ </button>+ </div>++ {loading && items.length === 0 && (+ <div className="text-gray-500 italic">Loading…</div>+ )}++ {!loading && items.length === 0 && !creating && (+ <div className="text-gray-500 italic px-1 mb-2">{config.emptyText}</div>+ )}++ {creating && (+ <BibleEditor+ workId={workId}+ item={null}+ config={config}+ onSaved={(record) => { upsert(record); setCreating(false); }}+ onCancel={() => setCreating(false)}+ />+ )}++ <ul className="space-y-1.5">+ {items.map((item) => {+ const isEditing = editingId === item.id;+ if (isEditing) {+ return (+ <li key={item.id}>+ <BibleEditor+ workId={workId}+ item={item}+ config={config}+ onSaved={(updated) => { upsert(updated); setEditingId(null); }}+ onDeleted={() => { removeOne(item.id); setEditingId(null); }}+ onCancel={() => setEditingId(null)}+ />+ </li>+ );+ }+ const isHot = hotRefId === item.id;+ return (+ <li+ key={item.id}+ className={`border rounded transition-all ${+ isHot+ ? 'border-port-accent ring-2 ring-port-accent/40 shadow-[0_0_0_3px_rgba(59,130,246,0.08)]'+ : 'border-port-border'+ }`}+ >+ <BibleRow item={item} config={config} onEdit={() => setEditingId(item.id)} readingTheme={readingTheme} />+ </li>+ );+ })}+ </ul>+ </div>+ );+}++function BibleRow({ item, config, onEdit, readingTheme }) {+ const light = readingTheme === 'light';+ const Icon = config.icon;+ const blanks = config.fields.filter((f) => {+ if (config.blanksExcludeKeys.includes(f.key)) return false;+ return !String(item[f.key] || '').trim();+ });+ return (+ <div className="px-3 py-2">+ <div className="flex items-start gap-2">+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 flex-wrap">+ {Icon && <Icon size={11} className={config.iconClassName} />}+ {config.renderTitle(item, { light })}+ {config.renderHeaderExtras(item)}+ </div>+ {item[config.bodyField] ? (+ <div className={`text-[11px] mt-0.5 ${light ? 'text-gray-700' : 'text-gray-400'}`}>+ {item[config.bodyField]}+ </div>+ ) : (+ <div className="text-[11px] mt-0.5 text-port-warning italic">{config.bodyEmptyText}</div>+ )}+ {config.detailBlocks.map((b) => item[b.key] && (+ <div key={b.key} className={`text-[10px] text-gray-500 ${b.marginClass}`}>+ <span className="uppercase tracking-wider text-[9px]">{b.label}:</span> {item[b.key]}+ </div>+ ))}+ {blanks.length > 0 && (+ <div className="text-[10px] text-port-warning mt-1 flex items-center gap-1">+ <AlertTriangle size={9} /> Missing: {blanks.map((f) => f.label.toLowerCase()).join(', ')}+ </div>+ )}+ {item.missingFromProse?.length > 0 && (+ <div className="text-[10px] text-gray-500 mt-1">+ <span className="uppercase tracking-wider text-[9px]">Prose gaps:</span> {item.missingFromProse.join(', ')}+ </div>+ )}+ </div>+ <button+ onClick={onEdit}+ className="text-gray-500 hover:text-port-accent shrink-0"+ title={config.editButtonTitle}+ aria-label={`Edit ${config.getDisplayName(item)}`}+ >+ <Pencil size={11} />+ </button>+ </div>+ </div>+ );+}++function BibleEditor({ workId, item, config, onSaved, onDeleted, onCancel }) {+ const isCreate = !item;+ const { primary, fields } = config;+ const [draft, setDraft] = useState(() => {+ const seed = { [primary.key]: item?.[primary.key] || '' };+ for (const f of fields) {+ seed[f.key] = f.kind === 'csv' ? (item?.[f.key] || []).join(', ') : (item?.[f.key] || '');+ }+ return seed;+ });+ const [saving, setSaving] = useState(false);++ const set = (field) => (e) => setDraft((d) => ({ ...d, [field]: e.target.value }));++ const save = async () => {+ const error = config.validate(draft);+ if (error) {+ toast.error(error);+ return;+ }+ setSaving(true);+ const payload = { [primary.key]: draft[primary.key].trim() };+ for (const f of fields) {+ payload[f.key] = f.kind === 'csv'+ ? draft[f.key].split(',').map((s) => s.trim()).filter(Boolean)+ : (f.trim ? draft[f.key].trim() : draft[f.key]);+ }+ const result = await (isCreate+ ? config.api.create(workId, payload, { silent: true })+ : config.api.update(workId, item.id, payload, { silent: true })+ ).catch((err) => {+ toast.error(`Save failed: ${err.message}`);+ return null;+ });+ setSaving(false);+ if (!result) return;+ toast.success(`${config.getDisplayName(result)} saved`);+ onSaved?.(result);+ };++ const remove = async () => {+ if (!item) return;+ setSaving(true);+ const ok = await config.api.remove(workId, item.id, { silent: true }).then(() => true).catch((err) => {+ toast.error(`Delete failed: ${err.message}`);+ return false;+ });+ setSaving(false);+ if (ok) {+ toast.success(`${config.getDisplayName(item)} removed`);+ onDeleted?.();+ }+ };++ const inputCls = 'w-full bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-gray-200 focus:border-port-accent outline-none';++ return (+ <div className="border border-port-accent/40 rounded p-2 bg-port-card/40 space-y-1.5">+ <div className="flex items-center justify-between gap-2">+ <label className="flex-1">+ <span className="sr-only">{primary.label}</span>+ <input+ value={draft[primary.key]}+ onChange={set(primary.key)}+ placeholder={primary.placeholder}+ className={`${inputCls} ${primary.inputExtraClass || ''}`}+ autoFocus={primary.autoFocus}+ />+ </label>+ <button+ onClick={onCancel}+ className="text-gray-500 hover:text-white shrink-0"+ aria-label="Cancel edit"+ title="Cancel"+ >+ <X size={12} />+ </button>+ </div>+ {fields.map((f) => (+ <label key={f.key} className="block">+ <span className="text-[9px] uppercase tracking-wider text-gray-500">{f.label}</span>+ {f.kind === 'multiline' ? (+ <textarea value={draft[f.key]} onChange={set(f.key)} placeholder={f.placeholder} rows={f.rows || 2} className={`${inputCls} font-sans resize-y`} />+ ) : (+ <input value={draft[f.key]} onChange={set(f.key)} placeholder={f.placeholder} className={inputCls} />+ )}+ </label>+ ))}+ <div className="flex items-center justify-between pt-1">+ {!isCreate ? (+ <button+ onClick={remove}+ disabled={saving}+ className="flex items-center gap-1 text-[10px] text-port-error hover:underline disabled:opacity-50"+ >+ <Trash2 size={10} /> Delete+ </button>+ ) : <span />}+ <button+ onClick={save}+ disabled={saving}+ className="flex items-center gap-1 px-2 py-1 bg-port-accent text-white rounded text-[10px] hover:bg-port-accent/80 disabled:opacity-50"+ >+ {saving ? <Loader2 size={10} className="animate-spin" /> : <Check size={10} />} Save+ </button>+ </div>+ </div>+ );+}diff --git a/client/src/components/writers-room/BibleSection.test.jsx b/client/src/components/writers-room/BibleSection.test.jsxnew file mode 100644index 0000000000..42971b64a5--- /dev/null+++ b/client/src/components/writers-room/BibleSection.test.jsx@@ -0,0 +1,244 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { render, screen, waitFor, cleanup } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++vi.mock('../../services/apiWritersRoom', () => ({+ listWritersRoomObjects: vi.fn(),+ createWritersRoomObject: vi.fn(),+ updateWritersRoomObject: vi.fn(),+ deleteWritersRoomObject: vi.fn(),+ listWritersRoomPlaces: vi.fn(),+ createWritersRoomPlace: vi.fn(),+ updateWritersRoomPlace: vi.fn(),+ deleteWritersRoomPlace: vi.fn(),+ listWritersRoomCharacters: vi.fn(),+ createWritersRoomCharacter: vi.fn(),+ updateWritersRoomCharacter: vi.fn(),+ deleteWritersRoomCharacter: vi.fn(),+}));++vi.mock('../ui/Toast', () => ({+ default: { success: vi.fn(), error: vi.fn(), warning: vi.fn() },+}));++import ObjectsBible from './ObjectsBible';+import PlacesBible from './PlacesBible';+import CharactersBible from './CharactersBible';+import toast from '../ui/Toast';+import {+ listWritersRoomObjects,+ createWritersRoomObject,+ updateWritersRoomObject,+ deleteWritersRoomObject,+ listWritersRoomPlaces,+ createWritersRoomPlace,+ updateWritersRoomPlace,+ deleteWritersRoomPlace,+ listWritersRoomCharacters,+ createWritersRoomCharacter,+ updateWritersRoomCharacter,+ deleteWritersRoomCharacter,+} from '../../services/apiWritersRoom';++// BibleSection.jsx is the shared implementation behind ObjectsBible /+// PlacesBible / CharactersBible — each just supplies a `config`. Drive all+// three through the same scenarios instead of duplicating the file per kind.+const SCENARIOS = [+ {+ label: 'ObjectsBible',+ Component: ObjectsBible,+ itemsPropName: 'objects',+ onChangePropName: 'onObjectsChange',+ primaryKey: 'name',+ primaryLabel: 'Name',+ api: {+ list: listWritersRoomObjects,+ create: createWritersRoomObject,+ update: updateWritersRoomObject,+ remove: deleteWritersRoomObject,+ },+ existingItem: {+ id: 'obj-1', name: 'The Locket', aliases: [], description: 'A tarnished silver locket.',+ significance: '', notes: '', source: 'user',+ },+ createPrimaryValue: 'The Fedora',+ createPayload: { name: 'The Fedora', aliases: [], description: '', significance: '', notes: '' },+ createdRecord: {+ id: 'obj-2', name: 'The Fedora', aliases: [], description: '', significance: '', notes: '', source: 'user',+ },+ updateFieldLabel: 'Description',+ updateFieldKey: 'description',+ updateFieldValue: 'A weathered gray fedora.',+ updatePayload: { name: 'The Locket', aliases: [], description: 'A weathered gray fedora.', significance: '', notes: '' },+ },+ {+ label: 'PlacesBible',+ Component: PlacesBible,+ itemsPropName: 'places',+ onChangePropName: 'onPlacesChange',+ primaryKey: 'slugline',+ primaryLabel: 'Slugline',+ api: {+ list: listWritersRoomPlaces,+ create: createWritersRoomPlace,+ update: updateWritersRoomPlace,+ remove: deleteWritersRoomPlace,+ },+ existingItem: {+ id: 'place-1', slugline: 'INT. KITCHEN — NIGHT', name: 'The Kitchen',+ description: 'A cozy kitchen with warm light.', palette: '', era: '', weather: '',+ recurringDetails: '', notes: '', source: 'user',+ },+ createPrimaryValue: 'EXT. GARDEN — DAY',+ createPayload: {+ slugline: 'EXT. GARDEN — DAY', name: '', description: '', palette: '', era: '', weather: '',+ recurringDetails: '', notes: '',+ },+ createdRecord: {+ id: 'place-2', slugline: 'EXT. GARDEN — DAY', name: '', description: '', palette: '', era: '',+ weather: '', recurringDetails: '', notes: '', source: 'user',+ },+ updateFieldLabel: 'Description',+ updateFieldKey: 'description',+ updateFieldValue: 'A garden filled with roses.',+ updatePayload: {+ slugline: 'INT. KITCHEN — NIGHT', name: 'The Kitchen', description: 'A garden filled with roses.',+ palette: '', era: '', weather: '', recurringDetails: '', notes: '',+ },+ },+ {+ label: 'CharactersBible',+ Component: CharactersBible,+ itemsPropName: 'characters',+ onChangePropName: 'onCharactersChange',+ primaryKey: 'name',+ primaryLabel: 'Name',+ api: {+ list: listWritersRoomCharacters,+ create: createWritersRoomCharacter,+ update: updateWritersRoomCharacter,+ remove: deleteWritersRoomCharacter,+ },+ existingItem: {+ id: 'char-1', name: 'Ada', aliases: [], role: 'protagonist', physicalDescription: 'Tall, dark hair.',+ personality: '', background: '', notes: '', source: 'user',+ },+ createPrimaryValue: 'Bly',+ createPayload: { name: 'Bly', aliases: [], role: '', physicalDescription: '', personality: '', background: '', notes: '' },+ createdRecord: {+ id: 'char-2', name: 'Bly', aliases: [], role: '', physicalDescription: '', personality: '',+ background: '', notes: '', source: 'user',+ },+ updateFieldLabel: 'Physical description',+ updateFieldKey: 'physicalDescription',+ updateFieldValue: 'Short, silver hair, sharp eyes.',+ updatePayload: {+ name: 'Ada', aliases: [], role: 'protagonist', physicalDescription: 'Short, silver hair, sharp eyes.',+ personality: '', background: '', notes: '',+ },+ },+];++describe.each(SCENARIOS)('$label (BibleSection)', (s) => {+ beforeEach(() => {+ vi.clearAllMocks();+ });+ afterEach(() => {+ cleanup();+ });++ const displayText = (item) => item[s.primaryKey];++ it('uncontrolled mode: fetches on mount and renders the fetched items', async () => {+ s.api.list.mockResolvedValue([s.existingItem]);++ render(<s.Component workId="work-1" />);++ await screen.findByText(displayText(s.existingItem));+ expect(s.api.list).toHaveBeenCalledWith('work-1');+ });++ it('controlled mode: does not fetch on mount and routes edits through onItemsChange instead of its own fetch', async () => {+ const onChange = vi.fn();+ const updated = { ...s.existingItem, [s.updateFieldKey]: s.updateFieldValue };+ s.api.update.mockResolvedValue(updated);++ const props = { workId: 'work-1', [s.itemsPropName]: [s.existingItem], [s.onChangePropName]: onChange };+ render(<s.Component {...props} />);++ await screen.findByText(displayText(s.existingItem));+ // Give any accidental mount-time fetch a tick to fire before asserting absence.+ await waitFor(() => expect(s.api.list).not.toHaveBeenCalled());++ await userEvent.click(screen.getByRole('button', { name: `Edit ${displayText(s.existingItem)}` }));+ const field = screen.getByLabelText(s.updateFieldLabel);+ await userEvent.clear(field);+ await userEvent.type(field, s.updateFieldValue);+ await userEvent.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(s.api.update).toHaveBeenCalled());+ await waitFor(() => expect(onChange).toHaveBeenCalledWith([updated]));+ expect(s.api.list).not.toHaveBeenCalled();+ });++ it('create: submits the identity field and appends the returned record to the list', async () => {+ s.api.list.mockResolvedValue([]);+ s.api.create.mockResolvedValue(s.createdRecord);++ render(<s.Component workId="work-1" />);+ await screen.findByText(/no .* yet/i);++ await userEvent.click(screen.getByRole('button', { name: 'Add' }));+ const field = screen.getByLabelText(s.primaryLabel);+ await userEvent.type(field, s.createPrimaryValue);+ await userEvent.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(s.api.create).toHaveBeenCalledWith('work-1', s.createPayload, { silent: true }));+ await screen.findByText(displayText(s.createdRecord));+ });++ it('update: editing a field on an existing item persists via the update API and reflects in the UI', async () => {+ s.api.list.mockResolvedValue([s.existingItem]);+ const updated = { ...s.existingItem, [s.updateFieldKey]: s.updateFieldValue };+ s.api.update.mockResolvedValue(updated);++ render(<s.Component workId="work-1" />);+ await screen.findByText(displayText(s.existingItem));++ await userEvent.click(screen.getByRole('button', { name: `Edit ${displayText(s.existingItem)}` }));+ const field = screen.getByLabelText(s.updateFieldLabel);+ await userEvent.clear(field);+ await userEvent.type(field, s.updateFieldValue);+ await userEvent.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(s.api.update).toHaveBeenCalledWith('work-1', s.existingItem.id, s.updatePayload, { silent: true }));+ await screen.findByText(s.updateFieldValue);+ });++ it('failed delete: surfaces an error toast and keeps the item in the list', async () => {+ s.api.list.mockResolvedValue([s.existingItem]);+ s.api.remove.mockRejectedValue(new Error('network down'));++ render(<s.Component workId="work-1" />);+ await screen.findByText(displayText(s.existingItem));++ await userEvent.click(screen.getByRole('button', { name: `Edit ${displayText(s.existingItem)}` }));+ await userEvent.click(screen.getByRole('button', { name: 'Delete' }));++ await waitFor(() => expect(s.api.remove).toHaveBeenCalledWith('work-1', s.existingItem.id, { silent: true }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Delete failed: network down'));+ // Editor stays open (delete failed) and the record is still rendered once+ // cancelled back out to the row view.+ await userEvent.click(screen.getByRole('button', { name: 'Cancel edit' }));+ expect(screen.getByText(displayText(s.existingItem))).toBeInTheDocument();+ });++ it('a11y: the identity field exposes an accessible name matching its config label', async () => {+ s.api.list.mockResolvedValue([]);+ render(<s.Component workId="work-1" />);+ await screen.findByText(/no .* yet/i);++ await userEvent.click(screen.getByRole('button', { name: 'Add' }));+ expect(screen.getByRole('textbox', { name: s.primaryLabel })).toBeInTheDocument();+ });+});diff --git a/client/src/components/writers-room/CharactersBible.jsx b/client/src/components/writers-room/CharactersBible.jsxindex 41640cc2cc..948445043d 100644--- a/client/src/components/writers-room/CharactersBible.jsx+++ b/client/src/components/writers-room/CharactersBible.jsx@@ -1,287 +1,73 @@-import { useEffect, useState } from 'react';-import { AlertTriangle, Check, Loader2, Pencil, Plus, Trash2, X } from 'lucide-react';-import toast from '../ui/Toast';+import BibleSection, { BibleAiBadge } from './BibleSection';import {listWritersRoomCharacters,createWritersRoomCharacter,updateWritersRoomCharacter,deleteWritersRoomCharacter,} from '../../services/apiWritersRoom';-import useMounted from '../../hooks/useMounted';-const CHARACTER_FIELDS = [- { key: 'aliases', label: 'Aliases', placeholder: 'nicknames, titles (comma-separated)', kind: 'csv' },- { key: 'role', label: 'Role', placeholder: 'protagonist, mentor, antagonist…', kind: 'text' },- { key: 'physicalDescription', label: 'Physical description', placeholder: 'Age, build, hair, eyes, distinctive features, signature wardrobe. Used directly in image-gen prompts.', kind: 'multiline' },- { key: 'personality', label: 'Personality', placeholder: 'Temperament, voice, quirks', kind: 'multiline' },- { key: 'background', label: 'Background', placeholder: 'Who they are, where they come from', kind: 'multiline' },- { key: 'notes', label: 'Notes', placeholder: 'Anything else worth tracking', kind: 'multiline' },-];+const CHARACTER_CONFIG = {+ icon: null,+ countLabel: (n) => `${n} character${n === 1 ? '' : 's'} · Edits persist across re-runs and feed image gen.`,+ emptyText: 'No profiles yet. Click "Refresh from prose" above to extract them, or add one manually.',+ editButtonTitle: 'Edit profile',+ primary: {+ key: 'name',+ label: 'Name',+ placeholder: 'Character name',+ inputExtraClass: 'font-semibold',+ },+ fields: [+ { key: 'aliases', label: 'Aliases', placeholder: 'nicknames, titles (comma-separated)', kind: 'csv' },+ { key: 'role', label: 'Role', placeholder: 'protagonist, mentor, antagonist…', kind: 'text' },+ { key: 'physicalDescription', label: 'Physical description', placeholder: 'Age, build, hair, eyes, distinctive features, signature wardrobe. Used directly in image-gen prompts.', kind: 'multiline', rows: 3 },+ { key: 'personality', label: 'Personality', placeholder: 'Temperament, voice, quirks', kind: 'multiline', rows: 2 },+ { key: 'background', label: 'Background', placeholder: 'Who they are, where they come from', kind: 'multiline', rows: 2 },+ { key: 'notes', label: 'Notes', placeholder: 'Anything else worth tracking', kind: 'multiline', rows: 2 },+ ],+ bodyField: 'physicalDescription',+ bodyEmptyText: 'No physical description — image gen will use scene context only',+ detailBlocks: [],+ blanksExcludeKeys: ['notes', 'aliases'],+ renderTitle: (item, { light }) => (+ <span className={`font-semibold ${light ? 'text-gray-900' : 'text-white'}`}>{item.name}</span>+ ),+ renderHeaderExtras: (item) => (+ <>+ {item.role && <span className="text-[9px] uppercase tracking-wider text-port-accent">{item.role}</span>}+ {item.source === 'ai' && <BibleAiBadge />}+ {item.aliases?.length > 0 && (+ <span className="text-[10px] text-gray-500 truncate">aka {item.aliases.join(', ')}</span>+ )}+ </>+ ),+ getDisplayName: (item) => item.name,+ getSortKey: (item) => item.name || '',+ validate: (draft) => (draft.name.trim() ? null : 'Name is required'),+ api: {+ list: listWritersRoomCharacters,+ create: createWritersRoomCharacter,+ update: updateWritersRoomCharacter,+ remove: deleteWritersRoomCharacter,+ },+};// Editable character bible — persistent across analysis runs and consumed by-// image gen to inject physicalDescription into per-scene prompts.+// image gen to inject physicalDescription into per-scene prompts. See+// BibleSection.jsx for the shared implementation these three configure.//// Controlled vs. uncontrolled: caller may pass `characters` to keep multiple// mounts in sync (e.g. drawer + storyboard chip count). When omitted we fetch// and own the list so this can stand alone.-export default function CharactersBible({ workId, characters: charactersProp, onCharactersChange, readingTheme = 'dark', hotRefId = null }) {- const [internalCharacters, setInternalCharacters] = useState(charactersProp || []);- const characters = charactersProp ?? internalCharacters;- const [editingId, setEditingId] = useState(null);- const [creating, setCreating] = useState(false);- const [loading, setLoading] = useState(false);- const mountedRef = useMounted();-- useEffect(() => {- if (charactersProp) return;- if (!workId) return;- setLoading(true);- listWritersRoomCharacters(workId)- .then((list) => { if (mountedRef.current) setInternalCharacters(list); })- .catch(() => { if (mountedRef.current) setInternalCharacters([]); })- .finally(() => { if (mountedRef.current) setLoading(false); });- }, [workId, charactersProp, mountedRef]);-- const upsert = (next) => {- const update = (prev) => {- const idx = prev.findIndex((c) => c.id === next.id);- const sorted = (arr) => arr.sort((a, b) => (a.name || '').localeCompare(b.name || ''));- if (idx < 0) return sorted([...prev, next]);- const copy = [...prev];- copy[idx] = next;- return sorted(copy);- };- setInternalCharacters(update);- onCharactersChange?.(update(characters));- };-- const removeOne = (id) => {- const next = characters.filter((c) => c.id !== id);- setInternalCharacters(next);- onCharactersChange?.(next);- };-- return (- <div className="text-xs">- <div className="flex items-center justify-between mb-2">- <div className="text-[11px] text-gray-500">- {characters.length} character{characters.length === 1 ? '' : 's'} · Edits persist across re-runs and feed image gen.- </div>- <button- onClick={() => { setCreating(true); setEditingId(null); }}- className="flex items-center gap-1 text-[11px] text-gray-400 hover:text-port-accent"- >- <Plus size={12} /> Add- </button>- </div>-- {loading && characters.length === 0 && (- <div className="text-gray-500 italic">Loading…</div>- )}-- {!loading && characters.length === 0 && !creating && (- <div className="text-gray-500 italic px-1 mb-2">- No profiles yet. Click "Refresh from prose" above to extract them, or add one manually.- </div>- )}-- {creating && (- <CharacterEditor- workId={workId}- character={null}- onSaved={(c) => { upsert(c); setCreating(false); }}- onCancel={() => setCreating(false)}- />- )}-- <ul className="space-y-1.5">- {characters.map((c) => {- const isEditing = editingId === c.id;- if (isEditing) {- return (- <li key={c.id}>- <CharacterEditor- workId={workId}- character={c}- onSaved={(updated) => { upsert(updated); setEditingId(null); }}- onDeleted={() => { removeOne(c.id); setEditingId(null); }}- onCancel={() => setEditingId(null)}- />- </li>- );- }- const isHot = hotRefId === c.id;- return (- <li- key={c.id}- className={`border rounded transition-all ${- isHot- ? 'border-port-accent ring-2 ring-port-accent/40 shadow-[0_0_0_3px_rgba(59,130,246,0.08)]'- : 'border-port-border'- }`}- >- <CharacterRow character={c} onEdit={() => setEditingId(c.id)} readingTheme={readingTheme} />- </li>- );- })}- </ul>- </div>- );-}--function CharacterRow({ character, onEdit, readingTheme }) {- const light = readingTheme === 'light';- const blanks = CHARACTER_FIELDS.filter((f) => {- if (f.key === 'notes' || f.key === 'aliases') return false;- return !String(character[f.key] || '').trim();- });- return (- <div className="px-3 py-2">- <div className="flex items-start gap-2">- <div className="flex-1 min-w-0">- <div className="flex items-center gap-2 flex-wrap">- <span className={`font-semibold ${light ? 'text-gray-900' : 'text-white'}`}>{character.name}</span>- {character.role && (- <span className="text-[9px] uppercase tracking-wider text-port-accent">{character.role}</span>- )}- {character.source === 'ai' && (- <span className="text-[9px] text-gray-500" title="Created by AI extraction — edit to mark as user-curated">ai</span>- )}- {character.aliases?.length > 0 && (- <span className="text-[10px] text-gray-500 truncate">aka {character.aliases.join(', ')}</span>- )}- </div>- {character.physicalDescription ? (- <div className={`text-[11px] mt-0.5 ${light ? 'text-gray-700' : 'text-gray-400'}`}>- {character.physicalDescription}- </div>- ) : (- <div className="text-[11px] mt-0.5 text-port-warning italic">No physical description — image gen will use scene context only</div>- )}- {blanks.length > 0 && (- <div className="text-[10px] text-port-warning mt-1 flex items-center gap-1">- <AlertTriangle size={9} /> Missing: {blanks.map((f) => f.label.toLowerCase()).join(', ')}- </div>- )}- {character.missingFromProse?.length > 0 && (- <div className="text-[10px] text-gray-500 mt-1">- <span className="uppercase tracking-wider text-[9px]">Prose gaps:</span> {character.missingFromProse.join(', ')}- </div>- )}- </div>- <button- onClick={onEdit}- className="text-gray-500 hover:text-port-accent shrink-0"- title="Edit profile"- aria-label={`Edit ${character.name}`}- >- <Pencil size={11} />- </button>- </div>- </div>- );-}--function CharacterEditor({ workId, character, onSaved, onDeleted, onCancel }) {- const isCreate = !character;- const [draft, setDraft] = useState(() => {- const seed = { name: character?.name || '' };- for (const f of CHARACTER_FIELDS) {- seed[f.key] = f.kind === 'csv' ? (character?.[f.key] || []).join(', ') : (character?.[f.key] || '');- }- return seed;- });- const [saving, setSaving] = useState(false);-- const set = (field) => (e) => setDraft((d) => ({ ...d, [field]: e.target.value }));-- const save = async () => {- if (!draft.name.trim()) {- toast.error('Name is required');- return;- }- setSaving(true);- const payload = { name: draft.name.trim() };- for (const f of CHARACTER_FIELDS) {- payload[f.key] = f.kind === 'csv'- ? draft[f.key].split(',').map((s) => s.trim()).filter(Boolean)- : draft[f.key];- }- const result = await (isCreate- ? createWritersRoomCharacter(workId, payload, { silent: true })- : updateWritersRoomCharacter(workId, character.id, payload, { silent: true })- ).catch((err) => {- toast.error(`Save failed: ${err.message}`);- return null;- });- setSaving(false);- if (!result) return;- toast.success(`${result.name} saved`);- onSaved?.(result);- };-- const remove = async () => {- if (!character) return;- setSaving(true);- const ok = await deleteWritersRoomCharacter(workId, character.id, { silent: true }).then(() => true).catch((err) => {- toast.error(`Delete failed: ${err.message}`);- return false;- });- setSaving(false);- if (ok) {- toast.success(`${character.name} removed`);- onDeleted?.();- }- };-- const inputCls = 'w-full bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-gray-200 focus:border-port-accent outline-none';-+export default function CharactersBible({ workId, characters, onCharactersChange, readingTheme = 'dark', hotRefId = null }) {return (- <div className="border border-port-accent/40 rounded p-2 bg-port-card/40 space-y-1.5">- <div className="flex items-center justify-between gap-2">- <input- value={draft.name}- onChange={set('name')}- placeholder="Character name"- className={`${inputCls} font-semibold`}- />- <button- onClick={onCancel}- className="text-gray-500 hover:text-white shrink-0"- aria-label="Cancel edit"- title="Cancel"- >- <X size={12} />- </button>- </div>- {CHARACTER_FIELDS.map((f) => (- <label key={f.key} className="block">- <span className="text-[9px] uppercase tracking-wider text-gray-500">{f.label}</span>- {f.kind === 'multiline' ? (- <textarea value={draft[f.key]} onChange={set(f.key)} placeholder={f.placeholder} rows={f.key === 'physicalDescription' ? 3 : 2} className={`${inputCls} font-sans resize-y`} />- ) : (- <input value={draft[f.key]} onChange={set(f.key)} placeholder={f.placeholder} className={inputCls} />- )}- </label>- ))}- <div className="flex items-center justify-between pt-1">- {!isCreate ? (- <button- onClick={remove}- disabled={saving}- className="flex items-center gap-1 text-[10px] text-port-error hover:underline disabled:opacity-50"- >- <Trash2 size={10} /> Delete- </button>- ) : <span />}- <button- onClick={save}- disabled={saving}- className="flex items-center gap-1 px-2 py-1 bg-port-accent text-white rounded text-[10px] hover:bg-port-accent/80 disabled:opacity-50"- >- {saving ? <Loader2 size={10} className="animate-spin" /> : <Check size={10} />} Save- </button>- </div>- </div>+ <BibleSection+ workId={workId}+ items={characters}+ onItemsChange={onCharactersChange}+ readingTheme={readingTheme}+ hotRefId={hotRefId}+ config={CHARACTER_CONFIG}+ />);}diff --git a/client/src/components/writers-room/ObjectsBible.jsx b/client/src/components/writers-room/ObjectsBible.jsxindex 147abeae13..102036a17b 100644--- a/client/src/components/writers-room/ObjectsBible.jsx+++ b/client/src/components/writers-room/ObjectsBible.jsx@@ -1,289 +1,71 @@-import { useEffect, useState } from 'react';-import { AlertTriangle, Check, Loader2, Package, Pencil, Plus, Trash2, X } from 'lucide-react';-import toast from '../ui/Toast';+import { Package } from 'lucide-react';+import BibleSection, { BibleAiBadge } from './BibleSection';import {listWritersRoomObjects,createWritersRoomObject,updateWritersRoomObject,deleteWritersRoomObject,} from '../../services/apiWritersRoom';-import useMounted from '../../hooks/useMounted';-const OBJECT_FIELDS = [- { key: 'description', label: 'Description', placeholder: 'Material, color, condition, distinguishing marks. Used in image-gen prompts when this object appears in a scene.', kind: 'multiline', rows: 3 },- { key: 'significance', label: 'Significance', placeholder: 'Why does this object matter? What does it represent? How does its meaning evolve across scenes?', kind: 'multiline', rows: 2 },- { key: 'notes', label: 'Notes', placeholder: 'Anything else worth tracking', kind: 'multiline', rows: 2 },-];--// Editable recurring-objects bible. Mirrors CharactersBible / PlacesBible.+const OBJECT_CONFIG = {+ icon: Package,+ iconClassName: 'text-amber-400 shrink-0',+ countLabel: (n) => `${n} object${n === 1 ? '' : 's'} · Recurring symbolic items extracted from prose.`,+ emptyText: 'No recurring objects yet. Click "Refresh from prose" above to extract them, or add one manually.',+ editButtonTitle: 'Edit object',+ primary: {+ key: 'name',+ label: 'Name',+ placeholder: "the letter, the fedora, her grandmother's locket…",+ autoFocus: true,+ },+ fields: [+ { key: 'aliases', label: 'Aliases (comma-separated)', placeholder: 'the envelope, the note', kind: 'csv' },+ { key: 'description', label: 'Description', placeholder: 'Material, color, condition, distinguishing marks. Used in image-gen prompts when this object appears in a scene.', kind: 'multiline', rows: 3 },+ { key: 'significance', label: 'Significance', placeholder: 'Why does this object matter? What does it represent? How does its meaning evolve across scenes?', kind: 'multiline', rows: 2 },+ { key: 'notes', label: 'Notes', placeholder: 'Anything else worth tracking', kind: 'multiline', rows: 2 },+ ],+ bodyField: 'description',+ bodyEmptyText: 'No description yet',+ detailBlocks: [+ { key: 'significance', label: 'Significance', marginClass: 'mt-1' },+ ],+ blanksExcludeKeys: ['notes', 'aliases'],+ renderTitle: (item, { light }) => (+ <span className={`font-semibold ${light ? 'text-gray-900' : 'text-white'}`}>{item.name}</span>+ ),+ renderHeaderExtras: (item) => (+ <>+ {item.aliases?.length > 0 && (+ <span className="text-[10px] text-gray-500 truncate">aka {item.aliases.join(', ')}</span>+ )}+ {item.source === 'ai' && <BibleAiBadge />}+ </>+ ),+ getDisplayName: (item) => item.name,+ getSortKey: (item) => item.name || '',+ validate: (draft) => (draft.name.trim() ? null : 'Name is required'),+ api: {+ list: listWritersRoomObjects,+ create: createWritersRoomObject,+ update: updateWritersRoomObject,+ remove: deleteWritersRoomObject,+ },+};++// Editable recurring-objects bible. Mirrors CharactersBible / PlacesBible —+// see BibleSection.jsx for the shared implementation these three configure.// Distinct from analysis snapshots — this is the canonical roster that// survives across `objects` analysis runs and accepts hand-edits.-export default function ObjectsBible({ workId, objects: objectsProp, onObjectsChange, readingTheme = 'dark', hotRefId = null }) {- const [internalObjects, setInternalObjects] = useState(objectsProp || []);- const objects = objectsProp ?? internalObjects;- const [editingId, setEditingId] = useState(null);- const [creating, setCreating] = useState(false);- const [loading, setLoading] = useState(false);- const mountedRef = useMounted();-- useEffect(() => {- if (objectsProp) return;- if (!workId) return;- setLoading(true);- listWritersRoomObjects(workId)- .then((list) => { if (mountedRef.current) setInternalObjects(list); })- .catch(() => { if (mountedRef.current) setInternalObjects([]); })- .finally(() => { if (mountedRef.current) setLoading(false); });- }, [workId, objectsProp, mountedRef]);-- const upsert = (next) => {- const update = (prev) => {- const idx = prev.findIndex((o) => o.id === next.id);- const sorted = (arr) => arr.sort((a, b) => (a.name || '').localeCompare(b.name || ''));- if (idx < 0) return sorted([...prev, next]);- const copy = [...prev];- copy[idx] = next;- return sorted(copy);- };- setInternalObjects(update);- onObjectsChange?.(update(objects));- };-- const removeOne = (id) => {- const next = objects.filter((o) => o.id !== id);- setInternalObjects(next);- onObjectsChange?.(next);- };-- return (- <div className="text-xs">- <div className="flex items-center justify-between mb-2">- <div className="text-[11px] text-gray-500">- {objects.length} object{objects.length === 1 ? '' : 's'} · Recurring symbolic items extracted from prose.- </div>- <button- onClick={() => { setCreating(true); setEditingId(null); }}- className="flex items-center gap-1 text-[11px] text-gray-400 hover:text-port-accent"- >- <Plus size={12} /> Add- </button>- </div>-- {loading && objects.length === 0 && (- <div className="text-gray-500 italic">Loading…</div>- )}-- {!loading && objects.length === 0 && !creating && (- <div className="text-gray-500 italic px-1 mb-2">- No recurring objects yet. Click "Refresh from prose" above to extract them, or add one manually.- </div>- )}-- {creating && (- <ObjectEditor- workId={workId}- object={null}- onSaved={(o) => { upsert(o); setCreating(false); }}- onCancel={() => setCreating(false)}- />- )}-- <ul className="space-y-1.5">- {objects.map((o) => {- const isEditing = editingId === o.id;- if (isEditing) {- return (- <li key={o.id}>- <ObjectEditor- workId={workId}- object={o}- onSaved={(updated) => { upsert(updated); setEditingId(null); }}- onDeleted={() => { removeOne(o.id); setEditingId(null); }}- onCancel={() => setEditingId(null)}- />- </li>- );- }- const isHot = hotRefId === o.id;- return (- <li- key={o.id}- className={`border rounded transition-all ${- isHot- ? 'border-port-accent ring-2 ring-port-accent/40 shadow-[0_0_0_3px_rgba(59,130,246,0.08)]'- : 'border-port-border'- }`}- >- <ObjectRow object={o} onEdit={() => setEditingId(o.id)} readingTheme={readingTheme} />- </li>- );- })}- </ul>- </div>- );-}--function ObjectRow({ object, onEdit, readingTheme }) {- const light = readingTheme === 'light';- const blanks = OBJECT_FIELDS.filter((f) => {- if (f.key === 'notes') return false;- return !String(object[f.key] || '').trim();- });- return (- <div className="px-3 py-2">- <div className="flex items-start gap-2">- <div className="flex-1 min-w-0">- <div className="flex items-center gap-2 flex-wrap">- <Package size={11} className="text-amber-400 shrink-0" />- <span className={`font-semibold ${light ? 'text-gray-900' : 'text-white'}`}>{object.name}</span>- {object.aliases?.length > 0 && (- <span className="text-[10px] text-gray-500 truncate">aka {object.aliases.join(', ')}</span>- )}- {object.source === 'ai' && (- <span className="text-[9px] text-gray-500" title="Created by AI extraction — edit to mark as user-curated">ai</span>- )}- </div>- {object.description ? (- <div className={`text-[11px] mt-0.5 ${light ? 'text-gray-700' : 'text-gray-400'}`}>- {object.description}- </div>- ) : (- <div className="text-[11px] mt-0.5 text-port-warning italic">No description yet</div>- )}- {object.significance && (- <div className="text-[10px] text-gray-500 mt-1">- <span className="uppercase tracking-wider text-[9px]">Significance:</span> {object.significance}- </div>- )}- {blanks.length > 0 && (- <div className="text-[10px] text-port-warning mt-1 flex items-center gap-1">- <AlertTriangle size={9} /> Missing: {blanks.map((f) => f.label.toLowerCase()).join(', ')}- </div>- )}- {object.missingFromProse?.length > 0 && (- <div className="text-[10px] text-gray-500 mt-1">- <span className="uppercase tracking-wider text-[9px]">Prose gaps:</span> {object.missingFromProse.join(', ')}- </div>- )}- </div>- <button- onClick={onEdit}- className="text-gray-500 hover:text-port-accent shrink-0"- title="Edit object"- aria-label={`Edit ${object.name}`}- >- <Pencil size={11} />- </button>- </div>- </div>- );-}--function ObjectEditor({ workId, object, onSaved, onDeleted, onCancel }) {- const isCreate = !object;- const [draft, setDraft] = useState(() => {- const seed = {- name: object?.name || '',- aliases: (object?.aliases || []).join(', '),- };- for (const f of OBJECT_FIELDS) seed[f.key] = object?.[f.key] || '';- return seed;- });- const [saving, setSaving] = useState(false);-- const set = (field) => (e) => setDraft((d) => ({ ...d, [field]: e.target.value }));-- const save = async () => {- if (!draft.name.trim()) {- toast.error('Name is required');- return;- }- setSaving(true);- const payload = {- name: draft.name.trim(),- aliases: draft.aliases.split(',').map((a) => a.trim()).filter(Boolean),- };- for (const f of OBJECT_FIELDS) payload[f.key] = draft[f.key];- const result = await (isCreate- ? createWritersRoomObject(workId, payload, { silent: true })- : updateWritersRoomObject(workId, object.id, payload, { silent: true })- ).catch((err) => {- toast.error(`Save failed: ${err.message}`);- return null;- });- setSaving(false);- if (!result) return;- toast.success(`${result.name} saved`);- onSaved?.(result);- };-- const remove = async () => {- if (!object) return;- setSaving(true);- const ok = await deleteWritersRoomObject(workId, object.id, { silent: true }).then(() => true).catch((err) => {- toast.error(`Delete failed: ${err.message}`);- return false;- });- setSaving(false);- if (ok) {- toast.success(`${object.name} removed`);- onDeleted?.();- }- };-- const inputCls = 'w-full bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-gray-200 focus:border-port-accent outline-none';-+export default function ObjectsBible({ workId, objects, onObjectsChange, readingTheme = 'dark', hotRefId = null }) {return (- <div className="border border-port-accent/40 rounded p-2 bg-port-card/40 space-y-1.5">- <div className="flex items-center justify-between gap-2">- <input- value={draft.name}- onChange={set('name')}- placeholder="the letter, the fedora, her grandmother's locket…"- className={inputCls}- autoFocus- />- <button- onClick={onCancel}- className="text-gray-500 hover:text-white shrink-0"- aria-label="Cancel edit"- title="Cancel"- >- <X size={12} />- </button>- </div>- <label className="block">- <span className="text-[9px] uppercase tracking-wider text-gray-500">Aliases (comma-separated)</span>- <input value={draft.aliases} onChange={set('aliases')} placeholder="the envelope, the note" className={inputCls} />- </label>- {OBJECT_FIELDS.map((f) => (- <label key={f.key} className="block">- <span className="text-[9px] uppercase tracking-wider text-gray-500">{f.label}</span>- {f.kind === 'multiline' ? (- <textarea value={draft[f.key]} onChange={set(f.key)} placeholder={f.placeholder} rows={f.rows || 2} className={`${inputCls} font-sans resize-y`} />- ) : (- <input value={draft[f.key]} onChange={set(f.key)} placeholder={f.placeholder} className={inputCls} />- )}- </label>- ))}- <div className="flex items-center justify-between pt-1">- {!isCreate ? (- <button- onClick={remove}- disabled={saving}- className="flex items-center gap-1 text-[10px] text-port-error hover:underline disabled:opacity-50"- >- <Trash2 size={10} /> Delete- </button>- ) : <span />}- <button- onClick={save}- disabled={saving}- className="flex items-center gap-1 px-2 py-1 bg-port-accent text-white rounded text-[10px] hover:bg-port-accent/80 disabled:opacity-50"- >- {saving ? <Loader2 size={10} className="animate-spin" /> : <Check size={10} />} Save- </button>- </div>- </div>+ <BibleSection+ workId={workId}+ items={objects}+ onItemsChange={onObjectsChange}+ readingTheme={readingTheme}+ hotRefId={hotRefId}+ config={OBJECT_CONFIG}+ />);}diff --git a/client/src/components/writers-room/PlacesBible.jsx b/client/src/components/writers-room/PlacesBible.jsxindex 6ead741382..fee0e280b3 100644--- a/client/src/components/writers-room/PlacesBible.jsx+++ b/client/src/components/writers-room/PlacesBible.jsx@@ -1,310 +1,83 @@-import { useEffect, useState } from 'react';-import { AlertTriangle, Check, Loader2, MapPin, Pencil, Plus, Trash2, X } from 'lucide-react';-import toast from '../ui/Toast';+import { MapPin } from 'lucide-react';+import BibleSection, { BibleAiBadge } from './BibleSection';import {listWritersRoomPlaces,createWritersRoomPlace,updateWritersRoomPlace,deleteWritersRoomPlace,} from '../../services/apiWritersRoom';-import useMounted from '../../hooks/useMounted';-const PLACE_FIELDS = [- { key: 'description', label: 'Description', placeholder: 'Architecture, scale, materials, lighting sources, recurring set-dressing. Used directly in image-gen prompts.', kind: 'multiline', rows: 3 },- { key: 'palette', label: 'Palette', placeholder: 'Comma-separated dominant colors / lighting cues', kind: 'text' },- { key: 'era', label: 'Era', placeholder: 'near-future, 1950s noir, present day…', kind: 'text' },- { key: 'weather', label: 'Weather / mood', placeholder: 'Recurring atmospheric conditions inside this place', kind: 'text' },- { key: 'recurringDetails', label: 'Recurring details', placeholder: 'Distinctive props or fixtures the prose returns to', kind: 'multiline', rows: 2 },- { key: 'notes', label: 'Notes', placeholder: 'Anything else worth tracking', kind: 'multiline', rows: 2 },-];+const PLACE_CONFIG = {+ icon: MapPin,+ iconClassName: 'text-port-accent shrink-0',+ countLabel: (n) => `${n} location${n === 1 ? '' : 's'} · Edits persist across re-runs and feed image gen.`,+ emptyText: 'No locations yet. Click "Refresh from prose" above to extract them, or add one manually.',+ editButtonTitle: 'Edit place',+ primary: {+ key: 'slugline',+ label: 'Slugline',+ placeholder: 'INT. KITCHEN — NIGHT',+ inputExtraClass: 'font-mono uppercase',+ },+ fields: [+ { key: 'name', label: 'Name (optional, human-readable)', placeholder: "The Kitchen, Curry O'City…", kind: 'text', trim: true },+ { key: 'description', label: 'Description', placeholder: 'Architecture, scale, materials, lighting sources, recurring set-dressing. Used directly in image-gen prompts.', kind: 'multiline', rows: 3 },+ { key: 'palette', label: 'Palette', placeholder: 'Comma-separated dominant colors / lighting cues', kind: 'text' },+ { key: 'era', label: 'Era', placeholder: 'near-future, 1950s noir, present day…', kind: 'text' },+ { key: 'weather', label: 'Weather / mood', placeholder: 'Recurring atmospheric conditions inside this place', kind: 'text' },+ { key: 'recurringDetails', label: 'Recurring details', placeholder: 'Distinctive props or fixtures the prose returns to', kind: 'multiline', rows: 2 },+ { key: 'notes', label: 'Notes', placeholder: 'Anything else worth tracking', kind: 'multiline', rows: 2 },+ ],+ bodyField: 'description',+ bodyEmptyText: "No description — image gen will use the scene's visualPrompt only",+ detailBlocks: [+ { key: 'palette', label: 'Palette', marginClass: 'mt-1' },+ { key: 'recurringDetails', label: 'Anchors', marginClass: 'mt-0.5' },+ ],+ blanksExcludeKeys: ['notes', 'name'],+ renderTitle: (item, { light }) => (+ item.slugline ? (+ <span className={`font-mono text-[11px] uppercase ${light ? 'text-gray-900' : 'text-white'}`}>{item.slugline}</span>+ ) : (+ <span className={`font-semibold ${light ? 'text-gray-900' : 'text-white'}`}>{item.name}</span>+ )+ ),+ renderHeaderExtras: (item) => (+ <>+ {item.slugline && item.name && item.name !== item.slugline && (+ <span className="text-[10px] text-gray-500 truncate">aka {item.name}</span>+ )}+ {item.era && <span className="text-[9px] uppercase tracking-wider text-port-accent">{item.era}</span>}+ {item.source === 'ai' && <BibleAiBadge />}+ </>+ ),+ getDisplayName: (item) => item.slugline || item.name,+ getSortKey: (item) => item.slugline || item.name || '',+ validate: (draft) => (draft.slugline.trim() || draft.name.trim() ? null : 'Slugline or name is required'),+ api: {+ list: listWritersRoomPlaces,+ create: createWritersRoomPlace,+ update: updateWritersRoomPlace,+ remove: deleteWritersRoomPlace,+ },+};// Editable places/world bible — persistent across analysis runs and consumed-// by image gen to inject location descriptions into per-scene prompts.+// by image gen to inject location descriptions into per-scene prompts. See+// BibleSection.jsx for the shared implementation these three configure.//// Controlled vs. uncontrolled: caller may pass `places` to keep multiple// mounts in sync (e.g. drawer + storyboard chip count). When omitted we fetch// and own the list so this can stand alone.-export default function PlacesBible({ workId, places: placesProp, onPlacesChange, readingTheme = 'dark', hotRefId = null }) {- const [internalPlaces, setInternalPlaces] = useState(placesProp || []);- const places = placesProp ?? internalPlaces;- const [editingId, setEditingId] = useState(null);- const [creating, setCreating] = useState(false);- const [loading, setLoading] = useState(false);- const mountedRef = useMounted();-- useEffect(() => {- if (placesProp) return;- if (!workId) return;- setLoading(true);- listWritersRoomPlaces(workId)- .then((list) => { if (mountedRef.current) setInternalPlaces(list); })- .catch(() => { if (mountedRef.current) setInternalPlaces([]); })- .finally(() => { if (mountedRef.current) setLoading(false); });- }, [workId, placesProp, mountedRef]);-- const upsert = (next) => {- const update = (prev) => {- const idx = prev.findIndex((s) => s.id === next.id);- const sorted = (arr) => arr.sort((a, b) => (a.slugline || a.name || '').localeCompare(b.slugline || b.name || ''));- if (idx < 0) return sorted([...prev, next]);- const copy = [...prev];- copy[idx] = next;- return sorted(copy);- };- setInternalPlaces(update);- onPlacesChange?.(update(places));- };-- const removeOne = (id) => {- const next = places.filter((s) => s.id !== id);- setInternalPlaces(next);- onPlacesChange?.(next);- };-- return (- <div className="text-xs">- <div className="flex items-center justify-between mb-2">- <div className="text-[11px] text-gray-500">- {places.length} location{places.length === 1 ? '' : 's'} · Edits persist across re-runs and feed image gen.- </div>- <button- onClick={() => { setCreating(true); setEditingId(null); }}- className="flex items-center gap-1 text-[11px] text-gray-400 hover:text-port-accent"- >- <Plus size={12} /> Add- </button>- </div>-- {loading && places.length === 0 && (- <div className="text-gray-500 italic">Loading…</div>- )}-- {!loading && places.length === 0 && !creating && (- <div className="text-gray-500 italic px-1 mb-2">- No locations yet. Click "Refresh from prose" above to extract them, or add one manually.- </div>- )}-- {creating && (- <PlaceEditor- workId={workId}- place={null}- onSaved={(s) => { upsert(s); setCreating(false); }}- onCancel={() => setCreating(false)}- />- )}-- <ul className="space-y-1.5">- {places.map((s) => {- const isEditing = editingId === s.id;- if (isEditing) {- return (- <li key={s.id}>- <PlaceEditor- workId={workId}- place={s}- onSaved={(updated) => { upsert(updated); setEditingId(null); }}- onDeleted={() => { removeOne(s.id); setEditingId(null); }}- onCancel={() => setEditingId(null)}- />- </li>- );- }- const isHot = hotRefId === s.id;- return (- <li- key={s.id}- className={`border rounded transition-all ${- isHot- ? 'border-port-accent ring-2 ring-port-accent/40 shadow-[0_0_0_3px_rgba(59,130,246,0.08)]'- : 'border-port-border'- }`}- >- <PlaceRow place={s} onEdit={() => setEditingId(s.id)} readingTheme={readingTheme} />- </li>- );- })}- </ul>- </div>- );-}--function PlaceRow({ place, onEdit, readingTheme }) {- const light = readingTheme === 'light';- const blanks = PLACE_FIELDS.filter((f) => {- if (f.key === 'notes') return false;- return !String(place[f.key] || '').trim();- });- return (- <div className="px-3 py-2">- <div className="flex items-start gap-2">- <div className="flex-1 min-w-0">- <div className="flex items-center gap-2 flex-wrap">- <MapPin size={11} className="text-port-accent shrink-0" />- {place.slugline ? (- <span className={`font-mono text-[11px] uppercase ${light ? 'text-gray-900' : 'text-white'}`}>{place.slugline}</span>- ) : (- <span className={`font-semibold ${light ? 'text-gray-900' : 'text-white'}`}>{place.name}</span>- )}- {place.slugline && place.name && place.name !== place.slugline && (- <span className="text-[10px] text-gray-500 truncate">aka {place.name}</span>- )}- {place.era && (- <span className="text-[9px] uppercase tracking-wider text-port-accent">{place.era}</span>- )}- {place.source === 'ai' && (- <span className="text-[9px] text-gray-500" title="Created by AI extraction — edit to mark as user-curated">ai</span>- )}- </div>- {place.description ? (- <div className={`text-[11px] mt-0.5 ${light ? 'text-gray-700' : 'text-gray-400'}`}>- {place.description}- </div>- ) : (- <div className="text-[11px] mt-0.5 text-port-warning italic">No description — image gen will use the scene's visualPrompt only</div>- )}- {place.palette && (- <div className="text-[10px] text-gray-500 mt-1">- <span className="uppercase tracking-wider text-[9px]">Palette:</span> {place.palette}- </div>- )}- {place.recurringDetails && (- <div className="text-[10px] text-gray-500 mt-0.5">- <span className="uppercase tracking-wider text-[9px]">Anchors:</span> {place.recurringDetails}- </div>- )}- {blanks.length > 0 && (- <div className="text-[10px] text-port-warning mt-1 flex items-center gap-1">- <AlertTriangle size={9} /> Missing: {blanks.map((f) => f.label.toLowerCase()).join(', ')}- </div>- )}- {place.missingFromProse?.length > 0 && (- <div className="text-[10px] text-gray-500 mt-1">- <span className="uppercase tracking-wider text-[9px]">Prose gaps:</span> {place.missingFromProse.join(', ')}- </div>- )}- </div>- <button- onClick={onEdit}- className="text-gray-500 hover:text-port-accent shrink-0"- title="Edit place"- aria-label={`Edit ${place.slugline || place.name}`}- >- <Pencil size={11} />- </button>- </div>- </div>- );-}--function PlaceEditor({ workId, place, onSaved, onDeleted, onCancel }) {- const isCreate = !place;- const [draft, setDraft] = useState(() => {- const seed = {- slugline: place?.slugline || '',- name: place?.name || '',- };- for (const f of PLACE_FIELDS) {- seed[f.key] = place?.[f.key] || '';- }- return seed;- });- const [saving, setSaving] = useState(false);-- const set = (field) => (e) => setDraft((d) => ({ ...d, [field]: e.target.value }));-- const save = async () => {- if (!draft.slugline.trim() && !draft.name.trim()) {- toast.error('Slugline or name is required');- return;- }- setSaving(true);- const payload = {- slugline: draft.slugline.trim(),- name: draft.name.trim(),- };- for (const f of PLACE_FIELDS) {- payload[f.key] = draft[f.key];- }- const result = await (isCreate- ? createWritersRoomPlace(workId, payload, { silent: true })- : updateWritersRoomPlace(workId, place.id, payload, { silent: true })- ).catch((err) => {- toast.error(`Save failed: ${err.message}`);- return null;- });- setSaving(false);- if (!result) return;- toast.success(`${result.slugline || result.name} saved`);- onSaved?.(result);- };-- const remove = async () => {- if (!place) return;- setSaving(true);- const ok = await deleteWritersRoomPlace(workId, place.id, { silent: true }).then(() => true).catch((err) => {- toast.error(`Delete failed: ${err.message}`);- return false;- });- setSaving(false);- if (ok) {- toast.success(`${place.slugline || place.name} removed`);- onDeleted?.();- }- };-- const inputCls = 'w-full bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-gray-200 focus:border-port-accent outline-none';-+export default function PlacesBible({ workId, places, onPlacesChange, readingTheme = 'dark', hotRefId = null }) {return (- <div className="border border-port-accent/40 rounded p-2 bg-port-card/40 space-y-1.5">- <div className="flex items-center justify-between gap-2">- <input- value={draft.slugline}- onChange={set('slugline')}- placeholder="INT. KITCHEN — NIGHT"- className={`${inputCls} font-mono uppercase`}- />- <button- onClick={onCancel}- className="text-gray-500 hover:text-white shrink-0"- aria-label="Cancel edit"- title="Cancel"- >- <X size={12} />- </button>- </div>- <label className="block">- <span className="text-[9px] uppercase tracking-wider text-gray-500">Name (optional, human-readable)</span>- <input value={draft.name} onChange={set('name')} placeholder="The Kitchen, Curry O'City…" className={inputCls} />- </label>- {PLACE_FIELDS.map((f) => (- <label key={f.key} className="block">- <span className="text-[9px] uppercase tracking-wider text-gray-500">{f.label}</span>- {f.kind === 'multiline' ? (- <textarea value={draft[f.key]} onChange={set(f.key)} placeholder={f.placeholder} rows={f.rows || 2} className={`${inputCls} font-sans resize-y`} />- ) : (- <input value={draft[f.key]} onChange={set(f.key)} placeholder={f.placeholder} className={inputCls} />- )}- </label>- ))}- <div className="flex items-center justify-between pt-1">- {!isCreate ? (- <button- onClick={remove}- disabled={saving}- className="flex items-center gap-1 text-[10px] text-port-error hover:underline disabled:opacity-50"- >- <Trash2 size={10} /> Delete- </button>- ) : <span />}- <button- onClick={save}- disabled={saving}- className="flex items-center gap-1 px-2 py-1 bg-port-accent text-white rounded text-[10px] hover:bg-port-accent/80 disabled:opacity-50"- >- {saving ? <Loader2 size={10} className="animate-spin" /> : <Check size={10} />} Save- </button>- </div>- </div>+ <BibleSection+ workId={workId}+ items={places}+ onItemsChange={onPlacesChange}+ readingTheme={readingTheme}+ hotRefId={hotRefId}+ config={PLACE_CONFIG}+ />);}