import { and, asc, eq, inArray, isNull } from 'drizzle-orm'; import { findBook, findChapter, findScene, type BookNode, type ChapterNode, type Manuscript, type PartNode, type SceneNode } from '#lib/manuscript-tree.ts'; import { orderedBookChapters } from '#lib/matter.ts'; import { db, tables } from './db/index.ts'; import { chapterLocation, sceneLocation } from './access.ts'; /** * The part of a project a surface may show or hand over. Every scoped surface * names one of these, and the server decides what it contains. */ export type ContentScope = | { kind: 'project' } | { kind: 'book'; bookId: string } | { kind: 'chapter'; chapterId: string } | { kind: 'scene'; sceneId: string }; export const PROJECT_SCOPE: ContentScope = { kind: 'project' }; /** The chapter and book a scoped node sits inside, for links and labels. */ export type ScopePath = { projectId: string; bookId: string; chapterId: string; sceneId?: string; }; export type ScopeTreeNode = { book?: BookNode; part?: PartNode; chapter?: ChapterNode; scene?: SceneNode; }; export type ScopeOption = { value: string; label: string; kind: 'book' | 'chapter' | 'scene'; id: string; }; export type ScopeOptions = { books: ScopeOption[]; chapters: ScopeOption[]; scenes: ScopeOption[]; }; /** * Export and a share form pick one explicit scope. Reading uses * `readingScope`, which falls back when a stale id no longer resolves. */ export function scopeFromSearch(params: URLSearchParams): ContentScope { const scene = params.get('scene'); const chapter = params.get('chapter'); const book = params.get('book'); if (scene) return { kind: 'scene', sceneId: scene }; if (chapter) return { kind: 'chapter', chapterId: chapter }; if (book) return { kind: 'book', bookId: book }; return PROJECT_SCOPE; } /** * A stale id opens the nearest scope that still exists, so an old read link is * a page rather than an error. An export never uses this: a stale id there must * fail closed. */ export function readingScope(manuscript: Manuscript, params: URLSearchParams): ContentScope { const scene = params.get('scene'); const chapter = params.get('chapter'); const book = params.get('book'); if (scene && findScene(manuscript, scene)) return { kind: 'scene', sceneId: scene }; if (chapter && findChapter(manuscript, chapter)) return { kind: 'chapter', chapterId: chapter }; if (book && findBook(manuscript, book)) return { kind: 'book', bookId: book }; return PROJECT_SCOPE; } export function scopeQuery(scope: ContentScope): string { switch (scope.kind) { case 'book': return `book=${encodeURIComponent(scope.bookId)}`; case 'chapter': return `chapter=${encodeURIComponent(scope.chapterId)}`; case 'scene': return `scene=${encodeURIComponent(scope.sceneId)}`; default: return ''; } } export function scopeValue(scope: ContentScope): string { switch (scope.kind) { case 'book': return `book:${scope.bookId}`; case 'chapter': return `chapter:${scope.chapterId}`; case 'scene': return `scene:${scope.sceneId}`; default: return 'project'; } } export function scopeFromValue(value: string): ContentScope | null { if (value === 'project') return PROJECT_SCOPE; const at = value.indexOf(':'); if (at < 1) return null; const kind = value.slice(0, at); const id = value.slice(at + 1); if (!id) return null; if (kind === 'book') return { kind: 'book', bookId: id }; if (kind === 'chapter') return { kind: 'chapter', chapterId: id }; if (kind === 'scene') return { kind: 'scene', sceneId: id }; return null; } /** The pure tree filter. A missing id makes an empty manuscript, never the whole one. */ export function scopeManuscript(manuscript: Manuscript, scope: ContentScope): Manuscript { if (scope.kind === 'project') return manuscript; const books = manuscript.books .map((book) => scopeBook(book, scope)) .filter((book): book is BookNode => book !== null); const storylineIds = new Set( books.flatMap((book) => [...book.parts.flatMap((part) => part.chapters), ...book.chapters] .flatMap((chapter) => chapter.scenes) .flatMap((scene) => (scene.storylineId ? [scene.storylineId] : [])) ) ); return { ...manuscript, books, words: books.reduce((sum, book) => sum + book.words, 0), storylines: manuscript.storylines.filter((line) => storylineIds.has(line.id)) }; } function scopeBook( book: BookNode, scope: Exclude ): BookNode | null { if (scope.kind === 'book') { if (book.id !== scope.bookId) return null; const parts = book.parts.map(narrowPart); const chapters = book.chapters.map(narrowChapter); return { ...book, parts, chapters, words: parts.reduce((sum, part) => sum + part.words, 0) + chapters.reduce((sum, chapter) => sum + chapter.words, 0) }; } const keepChapter = (chapter: ChapterNode) => scope.kind === 'chapter' ? chapter.id === scope.chapterId : chapter.scenes.some((scene) => scene.id === scope.sceneId); const parts = book.parts .map((part) => { const chapters = part.chapters .filter(keepChapter) .map(narrowChapterForScope(scope)) .filter((chapter): chapter is ChapterNode => chapter !== null); if (chapters.length === 0) return null; return { ...part, chapters, words: chapters.reduce((sum, chapter) => sum + chapter.words, 0) }; }) .filter((part): part is PartNode => part !== null); const chapters = book.chapters .filter(keepChapter) .map(narrowChapterForScope(scope)) .filter((chapter): chapter is ChapterNode => chapter !== null); if (parts.length === 0 && chapters.length === 0) return null; return { ...book, parts, chapters, words: parts.reduce((sum, part) => sum + part.words, 0) + chapters.reduce((sum, chapter) => sum + chapter.words, 0) }; } function narrowChapter(chapter: ChapterNode): ChapterNode { return { ...chapter, words: chapter.scenes.reduce((sum, scene) => sum + scene.words, 0) }; } function narrowChapterForScope( scope: Exclude ): (chapter: ChapterNode) => ChapterNode | null { return (chapter) => { const scenes = scope.kind === 'scene' ? chapter.scenes.filter((scene) => scene.id === scope.sceneId) : chapter.scenes; if (scenes.length === 0) return null; return { ...chapter, scenes, words: scenes.reduce((sum, scene) => sum + scene.words, 0) }; }; } function narrowPart(part: PartNode): PartNode { const chapters = part.chapters.map(narrowChapter); return { ...part, chapters, words: chapters.reduce((sum, chapter) => sum + chapter.words, 0) }; } export function scopeTreeNode(manuscript: Manuscript, scope: ContentScope): ScopeTreeNode | null { if (scope.kind === 'project') return {}; if (scope.kind === 'book') { const book = findBook(manuscript, scope.bookId); return book ? { book } : null; } if (scope.kind === 'chapter') return findChapter(manuscript, scope.chapterId); return findScene(manuscript, scope.sceneId); } /** The narrowest title, with no kind word. A project has none. */ export function scopeLabel(manuscript: Manuscript, scope: ContentScope): string | null { if (scope.kind === 'project') return null; const node = scopeTreeNode(manuscript, scope); return node?.scene?.title ?? node?.chapter?.title ?? node?.book?.title ?? null; } /** Book, part, chapter, scene, in reading order. */ export function scopeBreadcrumb(manuscript: Manuscript, scope: ContentScope): string[] { if (scope.kind === 'project') return []; const node = scopeTreeNode(manuscript, scope); if (!node) return []; return [node.book?.title, node.part?.title, node.chapter?.title, node.scene?.title].filter( (part): part is string => Boolean(part) ); } export function scenePath(manuscript: Manuscript, sceneId: string): ScopePath | null { const node = findScene(manuscript, sceneId); if (!node?.book || !node.chapter) return null; return { projectId: manuscript.project.id, bookId: node.book.id, chapterId: node.chapter.id, sceneId }; } export function chapterPath(manuscript: Manuscript, chapterId: string): ScopePath | null { const node = findChapter(manuscript, chapterId); if (!node?.book || !node.chapter) return null; return { projectId: manuscript.project.id, bookId: node.book.id, chapterId }; } export function scopeAllowsScene(scope: ContentScope, path: ScopePath): boolean { switch (scope.kind) { case 'project': return true; case 'book': return path.bookId === scope.bookId; case 'chapter': return path.chapterId === scope.chapterId; case 'scene': return path.sceneId === scope.sceneId; } } export function scopeAllowsChapter(scope: ContentScope, path: ScopePath): boolean { switch (scope.kind) { case 'project': return true; case 'book': return path.bookId === scope.bookId; case 'chapter': return path.chapterId === scope.chapterId; case 'scene': return false; } } /** A live database check for a scope a visitor named or a writer chose. */ export function scopeExists(projectId: string, scope: ContentScope): boolean { if (scope.kind === 'project') { return Boolean( db .select({ id: tables.project.id }) .from(tables.project) .where(and(eq(tables.project.id, projectId), isNull(tables.project.deletedAt))) .get() ); } if (scope.kind === 'book') { return Boolean( db .select({ id: tables.book.id }) .from(tables.book) .where( and( eq(tables.book.id, scope.bookId), eq(tables.book.projectId, projectId), isNull(tables.book.deletedAt) ) ) .get() ); } if (scope.kind === 'chapter') { return chapterLocation(scope.chapterId)?.projectId === projectId; } return sceneLocation(scope.sceneId)?.projectId === projectId; } export function sceneInScope(projectId: string, scope: ContentScope, sceneId: string): boolean { const location = sceneLocation(sceneId); if (!location || location.projectId !== projectId) return false; return scopeAllowsScene(scope, location); } /** * The picker needs titles without prose. `loadManuscript` reads every scene's * bodyText for its excerpts, so the Sharing page must not use it for this. */ export function loadScopeOptions(projectId: string): ScopeOptions { const books = db .select({ id: tables.book.id, title: tables.book.title, ordinal: tables.book.ordinal }) .from(tables.book) .where(and(eq(tables.book.projectId, projectId), isNull(tables.book.deletedAt))) .orderBy(asc(tables.book.ordinal), asc(tables.book.createdAt)) .all(); const bookIds = books.map((book) => book.id); if (bookIds.length === 0) return { books: [], chapters: [], scenes: [] }; const parts = db .select({ id: tables.part.id, bookId: tables.part.bookId, title: tables.part.title, ordinal: tables.part.ordinal }) .from(tables.part) .where(and(inArray(tables.part.bookId, bookIds), isNull(tables.part.deletedAt))) .orderBy(asc(tables.part.ordinal), asc(tables.part.createdAt)) .all(); const partById = new Map(parts.map((part) => [part.id, part])); const chapters = db .select({ id: tables.chapter.id, bookId: tables.chapter.bookId, partId: tables.chapter.partId, title: tables.chapter.title, matter: tables.chapter.matter, ordinal: tables.chapter.ordinal }) .from(tables.chapter) .where(and(inArray(tables.chapter.bookId, bookIds), isNull(tables.chapter.deletedAt))) .orderBy(asc(tables.chapter.ordinal), asc(tables.chapter.createdAt)) .all() .filter((chapter) => !chapter.partId || partById.has(chapter.partId)); const chapterIds = chapters.map((chapter) => chapter.id); const scenes = chapterIds.length ? db .select({ id: tables.scene.id, chapterId: tables.scene.chapterId, title: tables.scene.title, ordinal: tables.scene.ordinal }) .from(tables.scene) .where(and(inArray(tables.scene.chapterId, chapterIds), isNull(tables.scene.deletedAt))) .orderBy(asc(tables.scene.ordinal), asc(tables.scene.createdAt)) .all() : []; const options: ScopeOptions = { books: [], chapters: [], scenes: [] }; const chapterRowById = new Map(chapters.map((chapter) => [chapter.id, chapter])); for (const book of books) { options.books.push({ value: scopeValue({ kind: 'book', bookId: book.id }), label: book.title, kind: 'book', id: book.id }); const bookParts = parts .filter((part) => part.bookId === book.id) .map((part) => ({ id: part.id, title: part.title, chapters: chapters .filter((chapter) => chapter.partId === part.id) .map((chapter) => ({ kind: 'chapter' as const, id: chapter.id, title: chapter.title, section: false, matter: chapter.matter, words: 0, synopsis: '', scenes: [] })) })); const looseChapters = chapters .filter((chapter) => chapter.bookId === book.id && !chapter.partId) .map((chapter) => ({ kind: 'chapter' as const, id: chapter.id, title: chapter.title, section: false, matter: chapter.matter, words: 0, synopsis: '', scenes: [] })); const ordered = orderedBookChapters({ parts: bookParts, chapters: looseChapters }); for (const chapter of ordered) { const partId = chapterRowById.get(chapter.id)?.partId; const part = partId ? partById.get(partId) : undefined; const chapterLabel = [book.title, part?.title, chapter.title] .filter((part): part is string => Boolean(part)) .join(' / '); options.chapters.push({ value: scopeValue({ kind: 'chapter', chapterId: chapter.id }), label: chapterLabel, kind: 'chapter', id: chapter.id }); for (const scene of scenes.filter((row) => row.chapterId === chapter.id)) { options.scenes.push({ value: scopeValue({ kind: 'scene', sceneId: scene.id }), label: `${chapterLabel} / ${scene.title}`, kind: 'scene', id: scene.id }); } } } return options; } export function scopeOptionLabel(options: ScopeOptions, value: string): string | null { for (const group of [options.books, options.chapters, options.scenes]) { const found = group.find((option) => option.value === value); if (found) return found.label; } return null; } /** A strict resolver for export routes: a stale or foreign id is not a scope. */ export function exportScope(projectId: string, params: URLSearchParams): ContentScope | null { const requested = scopeFromSearch(params); return scopeExists(projectId, requested) ? requested : null; }