import type { SyntaxNode, Tree } from '@lezer/common'; import { parser } from '../editor/lang/parser.js'; /** * The publisher-agnostic view of a script, and the one place the syntax tree is * read for export. * * Every docx format needs the same things out of the tree — page/panel numbering * (spreads count for two), Origin/Style carryover, and inline emphasis unwrapped * into styled runs — and serifu2 solved them by copy-pasting the same ~250-line * tree walk into five exporters. Here that logic lives once and the formats * (`formats/`) become pure `ScriptDoc → DocxSpec` functions with no parser * knowledge at all. * * Purely structural: no CodeMirror, no DOM, no docx. Give it the document text * and it parses with the standalone Lezer parser, so it's testable against * hand-written `.serifu` strings. */ /** A span of content with its emphasis resolved — markers already stripped. */ export interface Run { text: string; bold?: boolean; italic?: boolean; } /** A dialogue line: an attribution plus the balloon's content. */ export interface TextLine { kind: 'text'; /** Attribution after carryover — the last Origin seen at or above this line. */ origin: string; /** Style after carryover. A new Origin ends the previous Style's run. */ style: string; /** * Whether this line wrote its own Origin rather than inheriting one. Fused * balloons (a bare `: …` continuing the same speaker) read as false, which is * how the One Peace format knows not to break them apart. */ explicitOrigin: boolean; /** Whether the content came from a `===` block (a hand-broken balloon). */ styleBlock: boolean; /** * The balloon's content, split into its typeset lines. A plain line has * exactly one entry; a style block has one per hand-break. Always non-empty — * a `TL:` awaiting a translation is a single empty line, not zero lines. */ lines: Run[][]; } /** An SFX line. `origin` is the source-language sound, unwrapped from parens. */ export interface SfxLine { kind: 'sfx'; translation: string; origin: string | null; } /** A `!` translator note. `text` excludes the `!`. */ export interface NoteLine { kind: 'note'; text: string; } /** * An `@ …` source line. Carried through the model even though no publisher * format emits it — exports are deliverables, and the source text is scaffolding * for the translator. Modelling it keeps a bilingual format a format-layer * change rather than a re-parse. */ export interface SourceLine { kind: 'source'; text: string; } export type ScriptLine = TextLine | SfxLine | NoteLine | SourceLine; /** `number` is 1-based within its page and resets on every page. */ export interface ScriptPanel { number: number; lines: ScriptLine[]; } /** `number` is the Serifu page number; a spread's is the first of its two. */ export interface ScriptPage { number: number; spread: boolean; panels: ScriptPanel[]; } export interface ScriptDoc { pages: ScriptPage[]; } /** Strip `n` marker characters from each end (`*text*`, `**text**`, `/=text=/`). */ function unwrap(raw: string, n: number): string { return raw.length >= 2 * n ? raw.slice(n, raw.length - n) : raw; } /** How many marker characters each emphasis node carries per side. */ const MARKERS: Record = { Bold: 1, Ital: 1, BoldItal: 2, BlockText: 2, }; /** Emphasis flags per node type. `BlockText` is verbatim text, not emphasis. */ const EMPHASIS: Record = { Bold: { bold: true }, Ital: { italic: true }, BoldItal: { bold: true, italic: true }, }; /** * Node types that contribute their text verbatim: prose plus the lone * punctuation the grammar hands back when it isn't part of an emphasis pair * (a `*` that never closed, a `:` inside dialogue). */ const VERBATIM = new Set(['UnstyledText', 'Star', 'Colon', 'DoubleStar', 'Underscore']); /** * Flatten a `Content` node into typeset lines. Inside a `===` block a `Newline` * ends the current line and starts the next; everywhere else the whole content * is one line. * * Exported because emphasis unwrapping is one set of rules, not two: the source * pane's text preview (`vision/previewText.ts`) needs the same `Run`s this * builds, and a second implementation would be a second thing to keep in step * with the grammar. It reads through `read` rather than off a whole-document * string so a caller with a live CodeMirror doc can slice only the spans it * wants — on the typing path, `doc.toString()` per keystroke is not free. */ export function readContent( content: SyntaxNode | null, read: (from: number, to: number) => string, ): Pick { const lines: Run[][] = [[]]; let styleBlock = false; const push = (run: Run) => { // Emphasis markers can wrap an empty span; nothing to typeset. if (run.text !== '') lines[lines.length - 1].push(run); }; const readSpans = (parent: SyntaxNode) => { for (let node = parent.firstChild; node; node = node.nextSibling) { const name = node.name; const raw = read(node.from, node.to); if (name === 'StyleBlock') { styleBlock = true; readSpans(node); } else if (name === 'Newline') { lines.push([]); } else if (name in MARKERS) { push({ text: unwrap(raw, MARKERS[name]), ...EMPHASIS[name] }); } else if (VERBATIM.has(name)) { push({ text: raw }); } } }; if (content) readSpans(content); return { lines, styleBlock }; } /** The text of a `!note` or `@source` line, minus its sigil and newline. */ function sigilText(node: SyntaxNode, text: string): string { return text.slice(node.from + 1, node.to).trim(); } /** * Read a `Line` node into the model, threading Origin/Style carryover through * `attrib`. Returns null for a line the model has nothing to say about (an * error node, or an `Sfx` with no translation). */ function readLine( line: SyntaxNode, text: string, attrib: { origin: string; style: string }, ): ScriptLine | null { const node = line.firstChild; if (!node) return null; if (node.name === 'Text') { const attribNode = node.getChild('Attrib'); const originNode = attribNode?.getChild('Origin') ?? null; const styleNode = attribNode?.getChild('Style') ?? null; // A new Origin ends the previous line's Style run — naming a speaker starts // them plain. A line that names only a Style keeps the carried Origin. if (originNode) { attrib.origin = text.slice(originNode.from, originNode.to).trim(); attrib.style = ''; } if (styleNode) attrib.style = text.slice(styleNode.from, styleNode.to).trim(); return { kind: 'text', origin: attrib.origin, style: attrib.style, explicitOrigin: originNode !== null, ...readContent(node.getChild('Content'), (from, to) => text.slice(from, to)), }; } if (node.name === 'Sfx') { // No sound yet (a bare `*`) is still an SFX — like `TL:` with no content, // a line awaiting input. The model keeps it so it agrees with the editor // (Find, pairing, the Tab slots) about what the script holds; whether a // publisher sees an empty one is each format's call. const translation = node.getChild('SfxTranslation'); const originNode = node.getChild('SfxOrigin'); let origin: string | null = null; if (originNode) { origin = text.slice(originNode.from, originNode.to).trim(); // The tokenizer keeps the parens; the model stores the sound itself, and // formats that show it re-wrap in whatever brackets they use. if (origin.startsWith('(') && origin.endsWith(')')) origin = origin.slice(1, -1); } return { kind: 'sfx', translation: translation ? text.slice(translation.from, translation.to).trim() : '', origin, }; } if (node.name === 'Note') return { kind: 'note', text: sigilText(node, text) }; if (node.name === 'Source') return { kind: 'source', text: sigilText(node, text) }; return null; } /** Build the export model from a Serifu document's text. */ export function buildScriptDoc(text: string): ScriptDoc { return scriptDocFromTree(parser.parse(text), text); } /** * The tree-taking form, for callers that already have one parsed (and for tests * that want to feed a specific tree). */ export function scriptDocFromTree(tree: Tree, text: string): ScriptDoc { const pages: ScriptPage[] = []; // Origin/Style carry across panels and pages, not just within one — the run // ends only at the next explicit attribution. const attrib = { origin: '', style: '' }; let number = 1; for (let page = tree.topNode.firstChild; page; page = page.nextSibling) { if (page.name !== 'Page' && page.name !== 'Spread') continue; const spread = page.name === 'Spread'; const panels: ScriptPanel[] = []; for (let panel = page.firstChild; panel; panel = panel.nextSibling) { if (panel.name !== 'Panel') continue; const lines: ScriptLine[] = []; for (let line = panel.firstChild; line; line = line.nextSibling) { if (line.name !== 'Line') continue; const read = readLine(line, text, attrib); if (read) lines.push(read); } panels.push({ number: panels.length + 1, lines }); } pages.push({ number, spread, panels }); number += spread ? 2 : 1; } return { pages }; }