import { ContentEditable } from "@common/components/ContentEditable"; import { useState } from "preact/hooks"; import styles from '../../assets/lore-editor.module.css'; import { useAppState, type LoreEntry } from "../../contexts/state"; export const LoreEditor = ({ visible }: { visible: boolean }) => { const { currentWorld, currentStory, dispatch } = useAppState(); const [editingId, setEditingId] = useState(null); const [newTitle, setNewTitle] = useState(''); const [showDeleteConfirm, setShowDeleteConfirm] = useState(null); if (!currentWorld || !visible) { return null; } // When a story is selected, edit story-level lore; otherwise world-level lore const storyId = currentStory?.id ?? null; const worldId = currentWorld.id; const lore = currentStory ? currentStory.lore : currentWorld.lore; const handleAddEntry = () => { if (!newTitle.trim()) return; dispatch({ type: 'ADD_LORE_ENTRY', worldId, storyId, entry: { id: crypto.randomUUID(), title: newTitle.trim(), text: '', }, }); setNewTitle(''); setEditingId(null); }; const handleEditEntry = (entryId: string, field: keyof LoreEntry, value: string) => { dispatch({ type: 'EDIT_LORE_ENTRY', worldId, storyId, entryId, updates: { [field]: value }, }); }; const handleDeleteEntry = (entryId: string) => { dispatch({ type: 'DELETE_LORE_ENTRY', worldId, storyId, entryId, }); }; const handleMoveUp = (index: number) => { if (index === 0) return; const entryIds = lore.map(e => e.id); [entryIds[index - 1], entryIds[index]] = [entryIds[index], entryIds[index - 1]]; dispatch({ type: 'REORDER_LORE_ENTRIES', worldId, storyId, entryIds, }); }; const handleMoveDown = (index: number) => { if (index === lore.length - 1) return; const entryIds = lore.map(e => e.id); [entryIds[index], entryIds[index + 1]] = [entryIds[index + 1], entryIds[index]]; dispatch({ type: 'REORDER_LORE_ENTRIES', worldId, storyId, entryIds, }); }; return (

{currentStory ? 'Story Lore' : 'World Lore'}

setNewTitle(e.currentTarget.value)} onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); handleAddEntry(); } }} placeholder="New lore entry title..." />
{lore.length === 0 && (

No lore entries yet. Add your first entry!

)} {lore.map((entry, index) => (
{editingId === entry.id ? ( handleEditEntry(entry.id, 'title', e.currentTarget.value)} onBlur={() => setEditingId(null)} onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); setEditingId(null); } else if (e.key === 'Escape') { setEditingId(null); } }} autoFocus /> ) : (

setEditingId(entry.id)} title="Click to edit" > {entry.title}

)}
{showDeleteConfirm === entry.id ? (
Delete?
) : ( )}
handleEditEntry(entry.id, 'text', e.currentTarget.textContent || '')} placeholder="Enter lore content..." />
))}
); };