import { isDeepStrictEqual } from 'node:util'; import { and, asc, eq, isNull, sql } from 'drizzle-orm'; import { db, tables } from './db/index.ts'; import { bodyToText } from './markdown.ts'; import { canWriteProject, noteTypeInProject, projectIdOfNoteType } from './access.ts'; import type { DocumentVersion, SaveOutcome, SavePrecondition } from './save-request.ts'; import { planRequestedOrder, writeOrder } from './ordered-siblings.ts'; /** * Note types are the shelves of the story bible, and a type's template is the * shape a new note starts from. * * Types belong to the project, so a series shares one bible. They hold no prose, so * deleting one unfiles its notes and keeps every word: a hard delete with a counted * confirm, not a soft one. * * A template keeps no item history and takes no snapshot, but it keeps the save * contract, so two co-authors editing it cannot silently overwrite each other. */ /** The accents a note type can use, from the Digital Rust failure palette. */ export const NOTE_TYPE_ACCENTS = [ { value: 'fractured-shell', label: 'Fractured Shell' }, { value: 'dead-thread', label: 'Dead Thread' }, { value: 'stack-overglow', label: 'Stack Overglow' }, { value: 'blue-screen', label: 'Blue Screen' }, { value: 'memory-leek', label: 'Memory Leek' }, { value: 'thermal-throttle', label: 'Thermal Throttle' } ] as const; export const DEFAULT_NOTE_TYPE_ACCENT = 'blue-screen'; export type NoteType = { id: string; name: string; pluralName: string; accent: string; /** The revision the template is at, which a template save must name. */ revision: number; /** True when a new note of this type starts from a template. */ hasTemplate: boolean; }; export type NoteTypeDetail = NoteType & { template: unknown; noteCount: number }; export class NoteTypeError extends Error { constructor(message: string) { super(message); this.name = 'NoteTypeError'; } } const MAX_NAME = 60; /** * The types in a project, in the order the panel shows them. * * The template body is left out: shipping every template to the workspace grows the * page for a button that says "Use template". */ export function listNoteTypes(projectId: string): NoteType[] { const rows = db .select() .from(tables.noteType) .where(eq(tables.noteType.projectId, projectId)) .orderBy(asc(tables.noteType.ordinal), asc(tables.noteType.id)) .all(); return rows.map((row) => ({ id: row.id, name: row.name, pluralName: row.pluralName, accent: row.accent, revision: row.revision, hasTemplate: row.template !== null })); } export function loadNoteType(projectId: string, typeId: string): NoteTypeDetail | null { const row = db .select() .from(tables.noteType) .where(and(eq(tables.noteType.id, typeId), eq(tables.noteType.projectId, projectId))) .get(); if (!row) return null; return { ...toType(row), template: row.template, noteCount: countNotesInType(typeId) }; } export function listNoteTypeDetails(projectId: string): NoteTypeDetail[] { const types = db .select() .from(tables.noteType) .where(eq(tables.noteType.projectId, projectId)) .orderBy(asc(tables.noteType.ordinal), asc(tables.noteType.id)) .all(); const counts = new Map( db .select({ typeId: tables.note.noteTypeId, count: sql`count(*)` }) .from(tables.note) .where(and(eq(tables.note.projectId, projectId), isNull(tables.note.deletedAt))) .groupBy(tables.note.noteTypeId) .all() .map((row) => [row.typeId ?? '', row.count]) ); return types.map((row) => ({ ...toType(row), template: row.template, noteCount: counts.get(row.id) ?? 0 })); } function toType(row: typeof tables.noteType.$inferSelect): NoteType { return { id: row.id, name: row.name, pluralName: row.pluralName, accent: row.accent, revision: row.revision, hasTemplate: row.template !== null }; } function countNotesInType(typeId: string): number { const row = db .select({ count: sql`count(*)` }) .from(tables.note) .where(and(eq(tables.note.noteTypeId, typeId), isNull(tables.note.deletedAt))) .get(); return row?.count ?? 0; } /** * Adds a type at the end of the list. It starts with no template, so its notes begin * as blank pages until the writer says otherwise. */ export function createNoteType( projectId: string, input: { name: string; pluralName?: string; accent?: string } ): string { const name = input.name.trim().slice(0, MAX_NAME); if (name.length === 0) throw new NoteTypeError('A note type needs a name.'); // An empty plural field means the writer left it alone, not that the plural is the // singular; the derived form is only a starting point they can overwrite. const given = (input.pluralName ?? '').trim(); const pluralName = (given.length > 0 ? given : pluralOf(name)).slice(0, MAX_NAME); const accent = readAccent(input.accent); const id = crypto.randomUUID(); db.transaction((tx) => { const last = tx .select({ ordinal: tables.noteType.ordinal }) .from(tables.noteType) .where(eq(tables.noteType.projectId, projectId)) .orderBy(sql`${tables.noteType.ordinal} desc`) .get(); tx.insert(tables.noteType) .values({ id, projectId, name, pluralName, accent, ordinal: (last?.ordinal ?? -1) + 1 }) .run(); }); return id; } /** * Changes a type's label and accent, and leaves `revision` alone: a rename must not * refuse the next autosave from a template editor that is already open. */ export function updateNoteType( projectId: string, typeId: string, input: { name: string; pluralName: string; accent: string } ): boolean { return db.transaction(() => { if (!noteTypeInProject(projectId, typeId)) return false; const name = input.name.trim().slice(0, MAX_NAME); if (name.length === 0) throw new NoteTypeError('A note type needs a name.'); const pluralName = input.pluralName.trim().slice(0, MAX_NAME); db.update(tables.noteType) .set({ name, pluralName: pluralName.length > 0 ? pluralName : name, accent: readAccent(input.accent) }) .where(eq(tables.noteType.id, typeId)) .run(); return true; }); } /** * Removes a type. Its notes keep every word and become Unfiled: the foreign key sets * `note_type_id` to null in the same statement, so none point at a row that is gone. * The delete is hard because only the grouping and the template are lost, and the * caller has already warned about both. */ export function deleteNoteType(projectId: string, typeId: string): boolean { return db.transaction(() => { if (!noteTypeInProject(projectId, typeId)) return false; db.delete(tables.noteType).where(eq(tables.noteType.id, typeId)).run(); // A row already deleted elsewhere is not a failure, but a surviving row means the // delete did not land and the page keeps showing the type. return !noteTypeInProject(projectId, typeId); }); } /** * Rewrites the order 0..n-1. Ids the project does not own are dropped, and types * missing from the list keep their order at the end. Unlike `reorderStorylines`, * there is no project checkpoint: a shelf order is not the manuscript. */ export function reorderNoteTypes(projectId: string, orderedIds: string[]): boolean { return db.transaction((tx) => { const rows = tx .select({ id: tables.noteType.id, ordinal: tables.noteType.ordinal }) .from(tables.noteType) .where(eq(tables.noteType.projectId, projectId)) .orderBy(asc(tables.noteType.ordinal), asc(tables.noteType.id)) .all(); const { ids, changed } = planRequestedOrder(rows, orderedIds); if (!changed) return true; writeOrder('note_type', ids, { executor: tx }); return true; }); } /** * Saves a type's template if it is still at the revision the caller built it on; a * stale save changes nothing and returns the current version. * * A body with no text clears the template instead of storing an empty document, or * "a blank template" would disagree with the `hasTemplate` flag the notes panel reads. */ export function saveNoteTypeTemplate( projectId: string, typeId: string, body: unknown, precondition: SavePrecondition, actorUserId?: string ): SaveOutcome { const doc = templateOrNull(body); const text = doc === null ? '' : bodyToText(doc); const stored = text.trim().length === 0 ? null : doc; try { return db.transaction((): SaveOutcome => { const liveProjectId = projectIdOfNoteType(typeId); const existing = db .select() .from(tables.noteType) .where(and(eq(tables.noteType.id, typeId), eq(tables.noteType.projectId, projectId))) .get(); if ( !existing || liveProjectId !== projectId || (actorUserId !== undefined && !canWriteProject(actorUserId, projectId)) ) { return { ok: false, reason: 'gone' }; } if (existing.revision !== precondition.baseRevision) { return { ok: false, reason: 'conflict', current: toVersion(existing) }; } if (isDeepStrictEqual(existing.template ?? null, stored)) { return { ok: true, revision: existing.revision }; } const written = db .update(tables.noteType) .set({ template: stored ?? null, revision: sql`${tables.noteType.revision} + 1`, updatedAt: new Date() }) .where( and( eq(tables.noteType.id, typeId), eq(tables.noteType.revision, precondition.baseRevision) ) ) .returning({ revision: tables.noteType.revision }) .get(); if (!written) throw new TemplateSaveRefused(toVersion(existing)); return { ok: true, revision: written.revision }; }); } catch (error) { if (error instanceof TemplateSaveRefused) { return { ok: false, reason: 'conflict', current: error.current }; } throw error; } } class TemplateSaveRefused extends Error { constructor(public readonly current: DocumentVersion) { super('The template changed before the save.'); } } function toVersion(row: typeof tables.noteType.$inferSelect): DocumentVersion { const text = row.template === null ? '' : bodyToText(row.template); return { revision: row.revision, body: row.template, text, words: text.trim().split(/\s+/u).filter(Boolean).length, savedAt: row.updatedAt }; } /** * A template arrives from an import or a save, so it is checked before the editor * sees it. Anything that is not a document becomes null, because TipTap throws on it. */ export function templateOrNull(value: unknown): unknown | null { if (!value || typeof value !== 'object') return null; const doc = value as { type?: unknown; content?: unknown }; if (doc.type !== 'doc') return null; if (doc.content !== undefined && !Array.isArray(doc.content)) return null; return doc; } /** * The four types a fresh project gets, each with a template that asks the questions * the type exists to answer. */ export function defaultNoteTypes() { return [ { name: 'Character', pluralName: 'Characters', accent: 'fractured-shell', template: promptTemplate(['Wants', 'Fears', 'Refuses to say']) }, { name: 'Place', pluralName: 'Places', accent: 'dead-thread', template: promptTemplate(['What it looks like', 'Who goes there', 'What it costs']) }, { name: 'Object', pluralName: 'Objects', accent: 'stack-overglow', template: promptTemplate(['What it is', 'Who wants it', 'What it remembers']) }, { name: 'Idea', pluralName: 'Ideas', accent: 'blue-screen', template: promptTemplate(['The question', 'Why it belongs here']) } ]; } /** * A document of empty paragraphs under headings, for a starter template. The empty * paragraph first puts the caret where the writer can type; starting on a heading * would put the first keystroke into the heading itself. */ export function promptTemplate(prompts: string[]): unknown { return { type: 'doc', content: [ { type: 'paragraph' }, ...prompts.flatMap((prompt) => [ { type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: prompt }] }, { type: 'paragraph' } ]) ] }; } export function ensureDefaultNoteTypes(projectId: string) { const existing = db .select({ id: tables.noteType.id }) .from(tables.noteType) .where(eq(tables.noteType.projectId, projectId)) .all(); if (existing.length > 0) return; db.transaction((tx) => { for (const [index, type] of defaultNoteTypes().entries()) { tx.insert(tables.noteType) .values({ id: crypto.randomUUID(), projectId, ...type, ordinal: index }) .run(); } }); } function readAccent(value: string | undefined): string { const known = NOTE_TYPE_ACCENTS.find((accent) => accent.value === value); return known?.value ?? DEFAULT_NOTE_TYPE_ACCENT; } function pluralOf(name: string): string { if (name.endsWith('y') && !/[aeiou]y$/iu.test(name)) return `${name.slice(0, -1)}ies`; if (/(s|x|z|ch|sh)$/iu.test(name)) return `${name}es`; return `${name}s`; }