Something went wrong. Try again.
A free, open-source, self-hosted place to write a novel.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352import { and, asc, eq, isNull, sql } from 'drizzle-orm';import { db, tables } from './db/index.ts';import { contentTargetInProject, projectIdOfStoryline } from './access.ts';import { loadManuscript } from './manuscript.ts';import { chapterEntries, type Manuscript } from '#lib/manuscript-tree.ts';import { recordCardVersion } from './item-history.ts';import { liveCardInCell, liveCardInProject } from './plot-cell.ts';import { recordProjectCheckpoint } from './checkpoints.ts';import { contentTargetColumns, contentTargetFromColumns, contentTargetKey, type ContentTarget} from '#lib/content-target.ts';import { listOrderedSiblings, planRequestedOrder, writeOrder } from './ordered-siblings.ts';
export type PlotColumn = ContentTarget & { /** `scene:<id>` or `chapter:<id>`. */ key: string; title: string; /** Chapter columns can group their scenes under one heading. */ chapterTitle?: string; bookId?: string; bookTitle?: string; /** The scene a chapter column opens: its first, or null for an empty chapter. */ firstSceneId?: string | null;};
export type PlotCardView = { id: string; storylineId: string; column: ContentTarget; title: string; body: string;};
export type PlotRow = { id: string; title: string; accent: string; cards: PlotCardView[];};
export type PlotGrid = { columns: PlotColumn[]; rows: PlotRow[]; mode: 'scene' | 'chapter';};
export function loadPlotGrid(projectId: string, mode: 'scene' | 'chapter'): PlotGrid { const manuscript = loadManuscript(projectId); const rows = db .select() .from(tables.storyline) .where(and(eq(tables.storyline.projectId, projectId), isNull(tables.storyline.deletedAt))) .orderBy(asc(tables.storyline.ordinal)) .all();
const cards = db .select() .from(tables.plotCard) .where( and( isNull(tables.plotCard.deletedAt), sql`${tables.plotCard.storylineId} in ( select id from ${tables.storyline} where project_id = ${projectId} )` ) ) .orderBy(asc(tables.plotCard.ordinal)) .all();
const sceneColumns = columnsFor(manuscript, 'scene'); const chapterColumns = columnsFor(manuscript, 'chapter'); const columns = mode === 'scene' ? sceneColumns : chapterColumns; const availableTargets = new Set( [...sceneColumns, ...chapterColumns].map((column) => column.key) ); const views = cards.flatMap((card): PlotCardView[] => { const column = contentTargetFromColumns(card); if (!column || !availableTargets.has(contentTargetKey(column))) return [];
return [ { id: card.id, storylineId: card.storylineId, column, title: card.title, body: card.body } ]; });
return { mode, columns, rows: rows.map((row) => ({ id: row.id, title: row.title, accent: row.accent, cards: views.filter((card) => card.storylineId === row.id) })) };}
function columnsFor(manuscript: Manuscript, mode: 'scene' | 'chapter'): PlotColumn[] { const chapters = chapterEntries(manuscript);
if (mode === 'scene') { const out: PlotColumn[] = []; for (const { book, chapter } of chapters) { for (const scene of chapter.scenes) { const column: ContentTarget = { kind: 'scene', id: scene.id }; out.push({ ...column, key: contentTargetKey(column), title: scene.title, chapterTitle: chapter.title, bookId: book.id, bookTitle: book.title }); } } return out; }
return chapters.map(({ book, chapter }) => { const column: ContentTarget = { kind: 'chapter', id: chapter.id }; return { ...column, key: contentTargetKey(column), title: chapter.title, bookId: book.id, bookTitle: book.title, firstSceneId: chapter.scenes[0]?.id ?? null }; });}
export function createStoryline(projectId: string, title: string, accent: string): string { const id = crypto.randomUUID(); const last = db .select({ n: sql<number>`coalesce(max(ordinal), -1)` }) .from(tables.storyline) .where(eq(tables.storyline.projectId, projectId)) .get();
db.insert(tables.storyline) .values({ id, projectId, title, accent, ordinal: (last?.n ?? -1) + 1 }) .run();
return id;}
/** * Saves a card's words, but only while the card is still in the project. * * The card id arrives in a form, so it is matched to the project through its * storyline: another project's card reads as one that never existed. */export function updateCard( projectId: string, cardId: string, patch: { title?: string; body?: string }): boolean { try { return db.transaction(() => { const card = liveCardInProject(projectId, cardId); if (!card) return false; const title = patch.title ?? card.title; const body = patch.body ?? card.body; if (title === card.title && body === card.body) return true;
recordCardVersion(projectId, cardId); const written = db .update(tables.plotCard) .set({ title, body, updatedAt: new Date() }) .where(eq(tables.plotCard.id, cardId)) .returning({ id: tables.plotCard.id }) .get(); if (!written) throw new CardSaveRefused(); return true; }); } catch (error) { if (error instanceof CardSaveRefused) return false; throw error; }}
/** * Creates the card if the cell is empty and reports the id either way, so a click * on an empty cell is one round trip rather than a create and a refresh. * * The storyline and the column both arrive in a form and are checked against the * project: a card never sits on another project's storyline, scene or chapter. */export function ensureCard( projectId: string, storylineId: string, column: ContentTarget): string | null { if (projectIdOfStoryline(storylineId) !== projectId) return null; if (!contentTargetInProject(projectId, column)) return null;
const existing = liveCardInCell(storylineId, column); if (existing) return existing.id;
const id = crypto.randomUUID();
db.insert(tables.plotCard) .values({ id, storylineId, ...contentTargetColumns(column), title: '', body: '' }) .run();
return id;}
/** * Only this project's storylines take part: an id from elsewhere is dropped * before the rewrite, so it cannot leave a gap in the ordinals. */export function reorderStorylines(projectId: string, orderedIds: string[]) { db.transaction((tx) => { const rows = listOrderedSiblings('storyline', eq(tables.storyline.projectId, projectId), tx); const { ids, changed } = planRequestedOrder(rows, orderedIds); if (!changed) return;
recordProjectCheckpoint(projectId, 'Before reordering storylines'); writeOrder('storyline', ids, { executor: tx }); });}
/** The project comes first, and the id is checked inside it. */export function renameStoryline(projectId: string, storylineId: string, title: string): boolean { const next = title.trim(); if (next.length === 0) return false; if (projectIdOfStoryline(storylineId) !== projectId) return false;
const row = db.select().from(tables.storyline).where(eq(tables.storyline.id, storylineId)).get(); if (!row) return false; if (row.title === next) return true;
db.update(tables.storyline) .set({ title: next, updatedAt: new Date() }) .where(eq(tables.storyline.id, storylineId)) .run();
return true;}
/** * The cards stay in the table, so a restore from Recovery trash brings them back * with the row. */export function deleteStoryline(projectId: string, storylineId: string): boolean { if (projectIdOfStoryline(storylineId) !== projectId) return false;
db.transaction(() => { recordProjectCheckpoint(projectId, 'Before deleting a storyline'); db.update(tables.storyline) .set({ deletedAt: new Date(), updatedAt: new Date() }) .where(eq(tables.storyline.id, storylineId)) .run(); });
return true;}
/** * A card is identified by its storyline and column, so the target cell must be * empty: two cards in one cell leave no way to tell which a click meant. */export function moveCard( projectId: string, cardId: string, target: { storylineId: string; column: ContentTarget }, patch: { title?: string; body?: string } = {}): boolean { return db.transaction(() => { if (projectIdOfStoryline(target.storylineId) !== projectId) return false; if (!contentTargetInProject(projectId, target.column)) return false;
const card = liveCardInProject(projectId, cardId); if (!card) return false; const title = patch.title ?? card.title; const body = patch.body ?? card.body; const sameCell = card.storylineId === target.storylineId && contentTargetKey(card.column) === contentTargetKey(target.column); if (sameCell && title === card.title && body === card.body) return true;
const occupied = liveCardInCell(target.storylineId, target.column, cardId); if (occupied) throw new CardCellTaken();
recordCardVersion(projectId, cardId); db.update(tables.plotCard) .set({ storylineId: target.storylineId, ...contentTargetColumns(target.column), title, body, updatedAt: new Date() }) .where(eq(tables.plotCard.id, cardId)) .run();
return true; });}
/** Recovery trash restores it, and item history keeps its words. */export function deleteCard(projectId: string, cardId: string): boolean { return db.transaction(() => { if (!liveCardInProject(projectId, cardId)) return false;
recordCardVersion(projectId, cardId); db.update(tables.plotCard) .set({ deletedAt: new Date(), updatedAt: new Date() }) .where(eq(tables.plotCard.id, cardId)) .run();
return true; });}
export class CardMoveRefused extends Error { constructor(message: string) { super(message); this.name = 'CardMoveRefused'; }}
class CardCellTaken extends CardMoveRefused { constructor() { super('That cell already has a card.'); this.name = 'CardCellTaken'; }}
class CardSaveRefused extends Error {}