Something went wrong. Try again.
A free, open-source, self-hosted place to write a novel.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866<script module lang="ts"> /* * One id per browser tab, shared by every inspector it opens: drafts belong to the tab, * not to a panel mount, and another tab must never treat them as abandoned. */ const tabId = `${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;</script>
<script lang="ts"> import { onDestroy, untrack } from 'svelte'; import { resolve } from '$app/paths'; import { enhance, type SubmitFunction } from '$app/forms'; import Swatch from '#lib/components/Swatch.svelte'; import type { NoteCard } from '#lib/server/notes.ts'; import type { NoteType } from '#lib/server/note-types.ts'; import type { SceneNoteLink } from '#lib/server/links.ts'; import { timeAgo } from '#lib/time.ts';
/** * Planning for the open scene, and the notes it touches. None of these fields changes * the scene's words, its revision or its history, so the panel can save as often as * the writer likes without burying a version. The notes panel lists the scenes a note * appears in, the reverse of this list. */ let { projectId, scene, sceneNotes, notes, types, viewpoints, onnote, onclose }: { /** Named so every form posts to the workspace route, not the page that happens to be open. */ projectId: string; scene: { id: string; title: string; synopsis: string; status: 'drafting' | 'revising' | 'complete'; viewpoint: string; }; sceneNotes: SceneNoteLink[]; notes: NoteCard[]; types: NoteType[]; /** Every viewpoint already used in the project, offered as suggestions. */ viewpoints: string[]; /** Present where the panel covers the prose and the writer needs a way back. */ onclose?: () => void; /** Opens a note in the notes panel. */ onnote: (noteId: string) => void; } = $props();
/* * The forms name their route instead of using `?/action`. A relative action resolves * against whatever page is current when the form submits, and this panel can submit * during a navigation, because leaving the workspace flushes the draft first. The * destination page's action then refuses the fields, and the words are lost. */ const workspaceBase = $derived(resolve('/p/[id]', { id: projectId }));
function actionFor(name: 'detail' | 'linkNote' | 'unlinkNote'): string { return `${workspaceBase}?/${name}`; }
const statuses = [ { value: 'drafting', label: 'Drafting' }, { value: 'revising', label: 'Revising' }, { value: 'complete', label: 'Complete' } ] as const;
/* * The workspace keys this panel on the scene id, so a new scene remounts it and these * initial values are read once, on purpose. */ let synopsis = $state(untrack(() => scene.synopsis)); let status = $state<(typeof statuses)[number]['value']>(untrack(() => scene.status)); let viewpoint = $state(untrack(() => scene.viewpoint));
/* * The last values the server confirmed, which a save compares against. It starts as the * values this panel mounted with, on purpose. */ let baseline = $state( untrack(() => ({ synopsis, status, viewpoint })) );
let noteError = $state<string | null>(null); let savedAt = $state<number | null>(null); let saving = $state(false); let inFlight: Promise<boolean> | null = null; let followUp: ReturnType<typeof setTimeout> | undefined;
/* * A browser copy of the draft, the same promise the prose keeps. A save can fail, a * session can end, and the panel can unmount before the retry lands, so every draft * names its tab and a tab deletes only its own copy: another tab cannot know whether * the writer still has that tab open. */ const draftPrefix = untrack(() => `fablewright:planning:${scene.id}:`); const draftKey = `${draftPrefix}${tabId}:${Math.random().toString(36).slice(2)}`;
type Draft = { synopsis: string; status: (typeof statuses)[number]['value']; viewpoint: string; at: number; /** The tab that wrote it. An older draft can have no owner. */ owner: string; };
/** A draft from this browser, offered rather than applied. */ let offered = $state<{ key: string; draft: Draft } | null>(null);
/* * Offers this tab has already answered. Declining is remembered in session storage, * which is per tab, so the same draft does not return every time the inspector reopens. * It is a preference, not a deletion. */ const declinedKey = untrack(() => `fablewright:planning-declined:${scene.id}`);
function readDeclined(): string[] { try { const raw = sessionStorage.getItem(declinedKey); const parsed = raw ? (JSON.parse(raw) as unknown) : [];
return Array.isArray(parsed) ? parsed.filter((key) => typeof key === 'string') : []; } catch { return []; } }
let declined = $state<string[]>(untrack(readDeclined));
function decline(key: string) { if (declined.includes(key)) return;
declined = [...declined, key];
try { sessionStorage.setItem(declinedKey, JSON.stringify(declined)); } catch { // The offer can return after a remount. Nothing is lost. } }
function parseDraft(raw: string): Draft | null { try { const parsed = JSON.parse(raw) as Partial<Draft>; const known = parsed.status === 'drafting' || parsed.status === 'revising' || parsed.status === 'complete';
if (typeof parsed.synopsis !== 'string' || typeof parsed.viewpoint !== 'string') { return null; }
if (!known) return null;
return { synopsis: parsed.synopsis, status: parsed.status as Draft['status'], viewpoint: parsed.viewpoint, at: typeof parsed.at === 'number' ? parsed.at : 0, owner: typeof parsed.owner === 'string' ? parsed.owner : '' }; } catch { return null; } }
function listDrafts(): { key: string; draft: Draft }[] { const found: { key: string; draft: Draft }[] = [];
try { for (let index = 0; index < localStorage.length; index += 1) { const key = localStorage.key(index);
if (!key || !key.startsWith(draftPrefix)) continue;
const raw = localStorage.getItem(key); const draft = raw ? parseDraft(raw) : null;
if (draft) found.push({ key, draft }); } } catch { return []; }
return found.sort((a, b) => b.draft.at - a.draft.at); }
function isOwn(key: string): boolean { return key.startsWith(`${draftPrefix}${tabId}:`); }
function storeDraft() { try { localStorage.setItem( draftKey, JSON.stringify({ synopsis, status, viewpoint, at: Date.now(), owner: tabId }) ); } catch { // A browser with no storage still saves to the server. It cannot keep // the extra copy. } }
function removeDraft(key: string) { try { localStorage.removeItem(key); } catch { // Nothing to clean up. } }
/* * A draft left by a failed save, or by a tab that closed, is offered on mount and never * applied on its own. Planning has no revision to compare, so writing a stale copy over * newer server text is a silent overwrite. The writer chooses instead. */ function offerNextDraft() { for (const entry of listDrafts()) { if (declined.includes(entry.key)) continue;
const same = entry.draft.synopsis === synopsis && entry.draft.status === status && entry.draft.viewpoint === viewpoint;
if (same) { // These words are already on the server, so this tab's own copy has nothing // to keep. Another tab's key is never removed, even when it looks redundant. if (isOwn(entry.key)) removeDraft(entry.key); continue; }
offered = entry; return; }
offered = null; }
untrack(offerNextDraft);
/** * True when the fields differ from what the server confirmed. Planning text saves * itself, so closing the panel or picking another scene cannot drop a half-typed * summary. */ const dirty = $derived( synopsis !== baseline.synopsis || status !== baseline.status || viewpoint !== baseline.viewpoint );
/** * Takes an offer off the screen. Only this tab's own copy is deleted: a draft from * another tab stays in storage, because that tab can still be open with the words on * screen. A discard is one writer's choice about an offer, not permission to erase * another tab's only copy. */ function settleOffered() { if (!offered) return;
if (isOwn(offered.key)) removeDraft(offered.key);
decline(offered.key); offered = null; }
function restoreOffered() { if (!offered) return;
synopsis = offered.draft.synopsis; status = offered.draft.status; viewpoint = offered.draft.viewpoint; settleOffered(); }
function discardOffered() { settleOffered(); offerNextDraft(); }
/** * Sends the three fields now, by a `fetch` to the workspace action rather than an * enhanced submit: this save can happen during a navigation, because leaving the * workspace flushes the draft first, and an enhanced submit applies the result to the * page, which cancels the navigation the writer asked for. */ function saveNow(): Promise<boolean> { if (inFlight) return inFlight;
const run = async (): Promise<boolean> => { saving = true; noteError = null;
const body = new FormData(); body.set('sceneId', scene.id); body.set('synopsis', synopsis); body.set('status', status); body.set('viewpoint', viewpoint);
const sent = { synopsis, status, viewpoint };
try { const response = await fetch(actionFor('detail'), { method: 'POST', body }); const answer = (await response.json().catch(() => null)) as { type?: string; data?: unknown; } | null;
/* * Only a `success` is a save. An ending session answers with a redirect, and a * proxy can answer with HTML. Neither is a save, and treating one as a save * removes the only other copy of the words. */ if (!response.ok || answer?.type !== 'success') { noteError = answer?.type === 'redirect' ? 'Your session has ended. Sign in again to save your planning.' : ((answer?.data as { message?: string } | undefined)?.message ?? 'The planning text was not saved.'); return false; }
baseline = sent; savedAt = Date.now();
const newer = synopsis !== sent.synopsis || status !== sent.status || viewpoint !== sent.viewpoint;
if (newer) { /* * Words arrived while this save was in flight. The draft still holds them, so * it stays, and the save runs again rather than wait on an effect whose * inputs did not change. */ clearTimeout(followUp); followUp = setTimeout(() => void saveNow(), 300); } else { // Only this tab's copy is settled. Another tab's draft is not this tab's // save, and deleting it loses their words. removeDraft(draftKey); }
return true; } catch { noteError = 'The planning text was not saved. Check the connection.'; return false; } finally { saving = false; inFlight = null; } };
inFlight = run();
return inFlight; }
export function hasUnsavedChanges(): boolean { return dirty; }
/** * Writes pending planning text before the panel leaves the screen. It loops because * words can arrive while a save is in flight, and the panel is not safe to unmount * until the newest words are the saved ones. */ export async function flush(): Promise<boolean> { for (let attempt = 0; attempt < 3 && dirty; attempt += 1) { await saveNow(); }
return !dirty; }
onDestroy(() => clearTimeout(followUp));
function onSubmit(event: SubmitEvent) { event.preventDefault(); void saveNow(); }
// Every keystroke reaches the browser copy before it reaches the server. $effect(() => { if (!dirty) return;
/* * Typing is the newer intent. An offer from another tab steps aside, but its key * stays, because that tab can still be open and still writing. */ if (offered) { decline(offered.key); offered = null; }
storeDraft(); });
// Autosave after a pause, so the server always holds the latest draft. $effect(() => { if (!dirty) return;
const timer = setTimeout(() => void saveNow(), 900);
return () => clearTimeout(timer); });
/** The notes linked here, resolved against the project's notes. */ const linked = $derived( sceneNotes .map((link) => notes.find((note) => note.id === link.noteId)) .filter((note): note is NoteCard => note !== undefined) );
/** Notes that are not linked yet, grouped by type, plus the unfiled ones. */ const linkable = $derived.by(() => { const linkedIds = new Set(linked.map((note) => note.id)); const open = notes.filter((note) => !linkedIds.has(note.id)); const known = new Set(types.map((type) => type.id)); const groups = types .map((type) => ({ type, items: open.filter((note) => note.typeId === type.id) })) .filter((group) => group.items.length > 0); const unfiled = open.filter((note) => note.typeId === null || !known.has(note.typeId));
return { groups, unfiled, total: open.length }; });
const afterAction = (onSuccess?: () => void): SubmitFunction => () => async ({ result, update }) => { if (result.type === 'failure') { const message = (result.data as { message?: string } | undefined)?.message; noteError = message ?? 'That did not work.'; savedAt = null; } else { noteError = null; onSuccess?.(); }
await update({ reset: false }); };</script>
<svelte:window onpagehide={() => void saveNow()} />
<aside class="scene-panel" aria-label="Scene planning"> <div class="head"> <div class="head-row"> <p class="label">Scene</p> {#if onclose} <button type="button" class="close tap-area" onclick={onclose} aria-label="Close scene planning" > × </button> {/if} </div> <h2>{scene.title}</h2> </div>
{#if offered} <div class="offer" role="status"> <p> Planning text from this browser was not saved ({timeAgo(offered.draft.at)}). Restoring it replaces the three fields below. The next save keeps it. </p> <div class="offer-acts"> <button class="btn btn-sm" type="button" onclick={restoreOffered}>Restore it</button> <button class="btn btn-sm btn-ghost" type="button" onclick={discardOffered} >Discard it</button > </div> </div> {/if}
<form class="fields" method="POST" action={actionFor('detail')} onsubmit={onSubmit}> <input type="hidden" name="sceneId" value={scene.id} />
<label class="field-label" for="scene-synopsis">Synopsis</label> <textarea id="scene-synopsis" class="field synopsis" name="synopsis" rows="5" bind:value={synopsis} placeholder="What happens, and what it costs."></textarea>
<label class="field-label" for="scene-status">Status</label> <select id="scene-status" class="field status" name="status" bind:value={status}> {#each statuses as option (option.value)} <option value={option.value}>{option.label}</option> {/each} </select>
<label class="field-label" for="scene-viewpoint">Viewpoint</label> <input id="scene-viewpoint" class="field" name="viewpoint" type="text" list="scene-viewpoints" bind:value={viewpoint} placeholder="Maren, third limited" maxlength="200" /> <datalist id="scene-viewpoints"> {#each viewpoints as option (option)} <option value={option}></option> {/each} </datalist>
<div class="acts"> <button class="btn btn-sm" type="submit" disabled={saving}> {saving ? 'Saving…' : 'Save now'} </button> {#if noteError} <span class="note-error" role="alert">{noteError}</span> {:else if savedAt} <span class="saved" role="status">Saved.</span> {:else} <span class="saved">Saves as you type.</span> {/if} </div> </form>
<section class="linked" aria-labelledby="scene-notes-title"> <h3 class="group-head" id="scene-notes-title"> Notes for this scene <span class="tnum count">{linked.length}</span> </h3>
{#if linked.length === 0} <p class="empty">No notes yet. Link a character, place, or object this scene turns on.</p> {:else} <ul class="note-list"> {#each linked as note (note.id)} <li class="note-row"> <Swatch accent={note.accent} size={8} /> <button class="note-open" type="button" onclick={() => onnote(note.id)}> {note.title} {#if note.typeName} <span class="note-type">{note.typeName}</span> {/if} </button> <form method="POST" action={actionFor('unlinkNote')} use:enhance={afterAction()} aria-label={`Unlink ${note.title}`} > <input type="hidden" name="sceneId" value={scene.id} /> <input type="hidden" name="noteId" value={note.id} /> <button class="btn btn-sm btn-ghost unlink tap-area" type="submit" aria-label={`Unlink ${note.title}`} title="Unlink this note">×</button > </form> </li> {/each} </ul> {/if}
{#if linkable.total > 0} <form class="link" method="POST" action={actionFor('linkNote')} use:enhance={afterAction()}> <input type="hidden" name="sceneId" value={scene.id} /> <label class="sr-only" for="scene-link-note">Note to link</label> <select id="scene-link-note" class="field" name="noteId" required> {#each linkable.groups as group (group.type.id)} <optgroup label={group.type.pluralName}> {#each group.items as note (note.id)} <option value={note.id}>{note.title}</option> {/each} </optgroup> {/each} {#if linkable.unfiled.length > 0} <optgroup label="Unfiled"> {#each linkable.unfiled as note (note.id)} <option value={note.id}>{note.title}</option> {/each} </optgroup> {/if} </select> <button class="btn btn-sm" type="submit">Link note</button> </form> {:else if linked.length > 0} <p class="empty">Every note in this project is linked to this scene.</p> {/if} </section></aside>
<style> /* The name `panel` belongs to the card in components.css, which would draw a rounded box with four walls. A board needs one wall, on its inner edge. */ .scene-panel { display: flex; flex-direction: column; min-height: 0; height: 100%; background: var(--dr-surface-secondary); border-left: 2px solid var(--dr-border-color-container); overflow-y: auto; }
.head { display: flex; flex-direction: column; gap: 0.25rem; padding: var(--dr-space-md); border-bottom: 1px solid var(--dr-border-color-container); flex: none; }
.head h2 { margin: 0; font-family: var(--dr-font-body); font-weight: 500; font-size: var(--dr-text-lg); color: var(--dr-text-primary); }
/* * On a phone this panel covers the draft. The close key is the way back to the * sentence, and it sits where every other panel's key already sits. */ .head-row { display: flex; align-items: center; justify-content: space-between; gap: var(--dr-space-sm); }
.close { margin-left: auto; border: 1px solid transparent; border-radius: var(--dr-radius-sm); background: transparent; color: var(--dr-text-secondary); font-size: var(--dr-text-lg); line-height: 1; cursor: pointer; padding: 0 0.25rem; }
.close:hover { background: var(--dr-surface-highlight); color: var(--dr-text-primary); }
.close:focus-visible { outline: var(--dr-focus-ring); outline-offset: 1px; }
.offer { display: flex; flex-direction: column; gap: var(--dr-space-sm); padding: var(--dr-space-md); border-bottom: 1px solid var(--dr-border-color-container); background: var(--dr-surface-base); }
.offer p { margin: 0; font-size: var(--dr-text-xs); line-height: 1.5; color: var(--dr-text-secondary); }
.offer-acts { display: flex; flex-wrap: wrap; gap: var(--dr-space-sm); }
.fields { display: flex; flex-direction: column; gap: 0.375rem; padding: var(--dr-space-md); border-bottom: 1px solid var(--dr-border-color-container); }
.field-label { margin-top: var(--dr-space-xs); font-family: var(--dr-font-heading); font-size: var(--fw-text-2xs); letter-spacing: 0.12em; text-transform: uppercase; color: var(--dr-heading-sub); }
.field-label:first-of-type { margin-top: 0; }
.synopsis { resize: vertical; font-size: var(--dr-text-sm); }
.status { font-size: var(--dr-text-sm); }
.acts { display: flex; flex-wrap: wrap; align-items: center; gap: var(--dr-space-sm); margin-top: var(--dr-space-xs); }
.saved, .note-error { font-family: var(--dr-font-mono); font-size: var(--dr-text-xs); }
.saved { color: var(--dr-text-muted); }
.note-error { color: var(--dr-danger-text); }
.linked { display: flex; flex-direction: column; gap: var(--dr-space-sm); padding: var(--dr-space-md); }
.group-head { display: flex; align-items: center; gap: 0.5rem; margin: 0; font-family: var(--dr-font-heading); font-weight: 600; font-size: var(--fw-text-2xs); letter-spacing: 0.12em; text-transform: uppercase; color: var(--dr-heading-sub); }
.count { margin-left: auto; color: var(--dr-text-muted); }
.empty { margin: 0; font-size: var(--dr-text-xs); line-height: 1.45; color: var(--dr-text-muted); }
.note-list { display: flex; flex-direction: column; gap: 2px; margin: 0; padding: 0; list-style: none; }
.note-row { display: flex; align-items: center; gap: 0.5rem; padding: 0.25rem 0; }
.note-open { display: flex; flex-direction: column; align-items: flex-start; gap: 0.0625rem; flex: 1; min-width: 0; padding: 0.125rem 0; border: 0; background: transparent; text-align: left; font-size: var(--dr-text-sm); color: var(--dr-text-primary); cursor: pointer; }
.note-open:hover { color: var(--dr-accent-hover); }
.note-open:focus-visible { outline: var(--dr-focus-ring); outline-offset: 2px; }
.note-type { font-family: var(--dr-font-heading); font-size: var(--fw-text-2xs); letter-spacing: 0.1em; text-transform: uppercase; color: var(--dr-text-muted); }
/* A quiet but legible remove: a bare × at the row's end, never the accent. */ .unlink { display: grid; place-items: center; min-width: 1.75rem; height: 1.75rem; padding: 0; font-size: 1.125rem; line-height: 1; color: var(--dr-text-secondary); }
.unlink:hover:not(:disabled) { color: var(--dr-danger-text); }
.link { display: flex; flex-wrap: wrap; gap: var(--dr-space-sm); align-items: center; padding-top: var(--dr-space-xs); border-top: 1px solid var(--dr-border-color-container); }
.link .field { flex: 1 1 9rem; min-width: 0; font-size: var(--dr-text-xs); }
@media (pointer: coarse) { .note-open, .link .field { min-height: 44px; } }</style>