Something went wrong. Try again.
A free, open-source, self-hosted place to write a novel.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185/** * Stored scene bodies as HTML for the reading view, which mounts no editor: no * ProseMirror, no autosave, so there is no second copy of the words to keep in * step. Every string passes through `escapeHtml`, including link addresses and * attribute values, so a scene holding `<script>` or a quote in a link shows * those characters instead of running them. Only the node and mark set the editor * produces is handled, and an unknown node keeps its text. Every body arrives * through `sanitiseBody`, so a row an import stored in the wrong shape renders * instead of throwing. */
import { canonicalMark, sanitiseBody, type SafeNode as DocNode } from '#lib/body.ts';import { safeHref } from '#lib/link-address.ts';
type Annotation = { id: string; start: number; end: number };type ReviewRender = { offset: number; blocks: number; annotations: Annotation[] };
export function bodyToReviewHtml(body: unknown, annotations: Annotation[] = []): string { const doc = sanitiseBody(body); return doc ? blocksToHtml(doc.content, { offset: 0, blocks: 0, annotations }) : '';}
function beginBlock(review?: ReviewRender) { if (!review) return; if (review.blocks++) review.offset += 2;}
export function escapeHtml(value: string): string { return value .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, ''');}
export function bodyToHtml(body: unknown): string { const doc = sanitiseBody(body);
if (!doc) return '';
return blocksToHtml(doc.content);}
function blocksToHtml(nodes: DocNode[], review?: ReviewRender): string { return nodes .map((node) => blockToHtml(node, review)) .filter((part) => part.length > 0) .join('\n');}
function blockToHtml(node: DocNode, review?: ReviewRender): string { switch (node.type) { case 'paragraph': { beginBlock(review); const inline = inlineToHtml(node.content ?? [], review);
return `<p>${inline || '<br />'}</p>`; }
case 'heading': { beginBlock(review); const level = Number(node.attrs?.level ?? 2); const safe = level === 3 ? 3 : 2;
return `<h${safe}>${inlineToHtml(node.content ?? [], review)}</h${safe}>`; }
case 'blockquote': return `<blockquote>${blocksToHtml(node.content ?? [], review)}</blockquote>`;
case 'bulletList': return `<ul>${listItems(node, review)}</ul>`;
case 'orderedList': { const start = Number(node.attrs?.start ?? 1); const attr = Number.isInteger(start) && start !== 1 ? ` start="${start}"` : '';
return `<ol${attr}>${listItems(node, review)}</ol>`; }
case 'horizontalRule': return '<hr />';
default: return unknownToHtml(node, review); }}
function listItems(node: DocNode, review?: ReviewRender): string { return (node.content ?? []) .map((item) => `<li>${blocksToHtml(item.content ?? [], review)}</li>`) .join('');}
/** A node the editor does not produce still holds the writer's words, so its text is kept. */function unknownToHtml(node: DocNode, review?: ReviewRender): string { const children = node.content ?? []; const inline = children.some((child) => child.type === 'text' || child.type === 'hardBreak');
if (inline) { const mapped = node.type === 'codeBlock' ? review : undefined; beginBlock(mapped); return `<p>${inlineToHtml(children, mapped)}</p>`; }
return blocksToHtml(children, review);}
function inlineToHtml(nodes: DocNode[], review?: ReviewRender): string { return nodes .map((node) => { if (node.type === 'hardBreak') return '<br />';
const text = textOf(node); if (!review) return applyMarks(escapeHtml(text), node.marks ?? []); const start = review.offset; review.offset += text.length; const end = review.offset; const annotations = review.annotations.filter((item) => item.start < end && item.end > start); const boundaries = [ ...new Set([ start, end, ...annotations.flatMap((item) => [Math.max(start, item.start), Math.min(end, item.end)]) ]) ].sort((a, b) => a - b); let html = ''; for (let i = 0; i < boundaries.length - 1; i++) { const from = boundaries[i], to = boundaries[i + 1]; let part = escapeHtml(text.slice(from - start, to - start)); const ids = annotations .filter((item) => item.start <= from && item.end >= to) .map((item) => item.id); if (ids.length) part = `<mark data-feedback="${escapeHtml(ids.join(' '))}">${part}</mark>`; html += part; } return `<span data-review-start="${start}">${applyMarks(html, node.marks ?? [])}</span>`; }) .join('');}
/** * The order matches `toMarkdown`: code innermost, then the decorations, then * emphasis and strong, with a link around all of them. The text is already * escaped, so nothing added here can come from the document. */function applyMarks( text: string, marks: { type: string; attrs?: Record<string, unknown> }[]): string { let out = text;
/* * A stored body names its marks the way TipTap does, `bold` and `italic`; one * from Markdown import names them `strong` and `em`. Asking through * `canonicalMark` stops a word being bold in the editor and plain here. */ const names = new Set(marks.map((mark) => canonicalMark(mark.type))); const has = (type: string) => names.has(type); const attr = (type: string, key: string) => marks.find((mark) => canonicalMark(mark.type) === type)?.attrs?.[key];
if (has('code')) out = `<code>${out}</code>`; if (has('strike')) out = `<s>${out}</s>`; if (has('underline')) out = `<u>${out}</u>`; if (has('italic')) out = `<em>${out}</em>`; if (has('bold')) out = `<strong>${out}</strong>`;
const href = safeHref(attr('link', 'href'));
if (href) { out = `<a href="${escapeHtml(href)}" rel="noreferrer noopener">${out}</a>`; }
return out;}
function textOf(node: DocNode): string { if (node.type === 'text') return node.text ?? '';
return (node.content ?? []).map(textOf).join('');}